Compare commits
126 Commits
88a25207e9
...
johns-bran
Author | SHA1 | Date | |
---|---|---|---|
|
ab5a51d3b1 | ||
|
a4c1c502ab | ||
|
7d441116bd | ||
|
8afa3b8461 | ||
|
84ecf316cd | ||
|
7ddea8f18d | ||
46154fbb01 | |||
9aac795c07 | |||
e59f4e7190 | |||
|
e6a2b0fe9d | ||
|
44c2f551de | ||
|
bad034acfd | ||
|
ba73e1bd45 | ||
|
b7affd75ae | ||
|
2ef50f93a9 | ||
|
1cf1aaf837 | ||
|
2bf73385af | ||
|
b072af346b | ||
|
27baa429b4 | ||
bd76135895 | |||
|
6cec17eb45 | ||
87be850a0e | |||
72f82ff863 | |||
7419953510 | |||
449b895d20 | |||
f0dd6d5eb6 | |||
8956362033 | |||
|
ed4aa2d59b | ||
|
6760a17f00 | ||
|
671317f28b | ||
|
e862a7427b | ||
233725778f | |||
3227d69fc1 | |||
4ca6972ccd | |||
0047f6c08e | |||
88ce9e52f0 | |||
|
437de74cc6 | ||
|
ca77307f0c | ||
|
5f46130439 | ||
3e1456351c | |||
d26cd0c13a | |||
|
cfde5219a4 | ||
|
f414e278bb | ||
|
741a56cb99 | ||
|
02e5f3a729 | ||
|
f7338a06b3 | ||
|
3996082fa7 | ||
903e87901e | |||
775beb60fe | |||
|
2537051668 | ||
|
82356ec189 | ||
|
561eafbf4c | ||
b58fa00c9a | |||
|
92990e4042 | ||
|
3500ffd377 | ||
|
771b92bfd7 | ||
c94c7a6477 | |||
c7ad574474 | |||
22c3850062 | |||
|
21da31dee3 | ||
|
294df16e89 | ||
3112660880 | |||
c135819ba0 | |||
e94cd9cc2a | |||
|
dcd20a2394 | ||
|
71ffb8bb83 | ||
|
2d455ba197 | ||
|
77fecfa476 | ||
|
36e56fa66e | ||
|
f3e3158460 | ||
|
7b1e6fced4 | ||
|
4d5c0017b4 | ||
093beb9ef1 | |||
2ae0988986 | |||
|
18fc17b707 | ||
|
bea71838ac | ||
dfded3e592 | |||
0298e2cb76 | |||
|
dccd34db73 | ||
90f91d58d1 | |||
612c967023 | |||
f12e553ffc | |||
f24e279596 | |||
c5fc378eed | |||
|
27f50b9c66 | ||
3e901ea254 | |||
85ae06048c | |||
cd845cd91c | |||
|
4d21d8e94e | ||
|
a34c7ded50 | ||
78d5528733 | |||
|
10eb17497e | ||
|
576146c4fc | ||
|
bf365194be | ||
|
35b3e9ee46 | ||
|
4e56760dd6 | ||
|
347bdcbd94 | ||
|
d594bacb7d | ||
|
eb313464f0 | ||
|
8163d0b61e | ||
|
92e1daab5b | ||
70a3788030 | |||
|
34d17660ef | ||
|
cc6d26e17d | ||
|
f9743efddc | ||
|
b37e065857 | ||
4c5473827e | |||
d631b01c82 | |||
|
8cd22c6e4c | ||
ef0bc99bbf | |||
99948fef07 | |||
66c9481b3e | |||
fd8d451ba7 | |||
f27a7471bc | |||
a15f684c04 | |||
fb3f822160 | |||
b9f6014f59 | |||
af64f88198 | |||
837e751094 | |||
57c2023215 | |||
09e36a84dc | |||
|
e395c4d96b | ||
|
8a5f307947 | ||
514f7d724a | |||
|
de5c2a5002 | ||
407b03620e |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -83,3 +83,4 @@ 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/raupenpiler/CompilerInput.class
|
||||||
src/test/resources/output/raupenpiler/CompilerInput$Test.class
|
src/test/resources/output/raupenpiler/CompilerInput$Test.class
|
||||||
|
.idea/inspectionProfiles/Project_Default.xml
|
||||||
|
5
.idea/jarRepositories.xml
generated
5
.idea/jarRepositories.xml
generated
@@ -6,6 +6,11 @@
|
|||||||
<option name="name" value="Central Repository" />
|
<option name="name" value="Central Repository" />
|
||||||
<option name="url" value="https://repo.maven.apache.org/maven2" />
|
<option name="url" value="https://repo.maven.apache.org/maven2" />
|
||||||
</remote-repository>
|
</remote-repository>
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="maven_central" />
|
||||||
|
<option name="name" value="Maven Central" />
|
||||||
|
<option name="url" value="https://repo.maven.apache.org/maven2/" />
|
||||||
|
</remote-repository>
|
||||||
<remote-repository>
|
<remote-repository>
|
||||||
<option name="id" value="central" />
|
<option name="id" value="central" />
|
||||||
<option name="name" value="Maven Central repository" />
|
<option name="name" value="Maven Central repository" />
|
||||||
|
2
.idea/misc.xml
generated
2
.idea/misc.xml
generated
@@ -6,7 +6,7 @@
|
|||||||
<PerGrammarGenerationSettings>
|
<PerGrammarGenerationSettings>
|
||||||
<option name="fileName" value="$PROJECT_DIR$/src/main/java/parser/SimpleJava.g4" />
|
<option name="fileName" value="$PROJECT_DIR$/src/main/java/parser/SimpleJava.g4" />
|
||||||
<option name="autoGen" value="true" />
|
<option name="autoGen" value="true" />
|
||||||
<option name="outputDir" value="C:\Users\Johannes\Documents\Github\JavaCompiler\src\main\java" />
|
<option name="outputDir" value="C:\Users\ARB00075\Documents\DH\Compilerbau\NichtHaskell2.0\src\main\java" />
|
||||||
<option name="libDir" value="" />
|
<option name="libDir" value="" />
|
||||||
<option name="encoding" value="" />
|
<option name="encoding" value="" />
|
||||||
<option name="pkg" value="parser.generated" />
|
<option name="pkg" value="parser.generated" />
|
||||||
|
58
.lib/Kurzdokumentation.md
Normal file
58
.lib/Kurzdokumentation.md
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
# Kurzdokumentation
|
||||||
|
|
||||||
|
## Aufgabenverteilung
|
||||||
|
|
||||||
|
### Maximilian Stahl und Jannik Rombach:
|
||||||
|
- **Scanner**
|
||||||
|
- **Parser**
|
||||||
|
- **AST**
|
||||||
|
- **AstBuilder**
|
||||||
|
- **Modul: ast**
|
||||||
|
- Alle
|
||||||
|
- **Modul: parser**
|
||||||
|
- Alle
|
||||||
|
- **Modul: visitor**
|
||||||
|
- Alle
|
||||||
|
- **Testmodul: parser**
|
||||||
|
- AstBuildertest.java
|
||||||
|
- Helper.java
|
||||||
|
- **Testfiles: singleFeatureTests**
|
||||||
|
- Alle
|
||||||
|
|
||||||
|
### Johannes Ehlert:
|
||||||
|
- **Semantische Analyse**
|
||||||
|
- **Modul: semantic**
|
||||||
|
- **Modul: typecheck**
|
||||||
|
- **Testmodul: parser**
|
||||||
|
- AstBuildertest.java
|
||||||
|
- **Testfiles: typedAstFeatureTests**
|
||||||
|
- Großteil
|
||||||
|
- **Testfiles: typedAstExceptionsTests**
|
||||||
|
- Großteil
|
||||||
|
|
||||||
|
### David Große:
|
||||||
|
- **Bytecodegenerator**
|
||||||
|
- **Modul: bytecode**
|
||||||
|
- Alle
|
||||||
|
|
||||||
|
### Lucas Janker:
|
||||||
|
- **Tests**
|
||||||
|
- **Modul: main**
|
||||||
|
- Alle
|
||||||
|
- **Testmodul: main**
|
||||||
|
- Alle
|
||||||
|
- **Testmodul: parser**
|
||||||
|
- ScannerTest.java
|
||||||
|
- ParserTest.java
|
||||||
|
- **Testmodul: semantic**
|
||||||
|
- **Testfiles: combinedFeatureTests**
|
||||||
|
- Alle
|
||||||
|
- **Testfiles: failureTests**
|
||||||
|
- Alle
|
||||||
|
- **Testfiles: Alle**
|
||||||
|
- Refactoring
|
||||||
|
- **Ordnerstrukturen**
|
||||||
|
- Großteil
|
||||||
|
- **Build**
|
||||||
|
- **Makefile**
|
||||||
|
- **Dokumentation**
|
21
pom.xml
21
pom.xml
@@ -20,7 +20,7 @@
|
|||||||
<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>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
@@ -44,6 +44,18 @@
|
|||||||
<version>3.26.0</version>
|
<version>3.26.0</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-api</artifactId>
|
||||||
|
<version>5.11.0-M2</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-core</artifactId>
|
||||||
|
<version>5.11.0</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@@ -78,4 +90,11 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
<repositories>
|
||||||
|
<repository>
|
||||||
|
<id>maven_central</id>
|
||||||
|
<name>Maven Central</name>
|
||||||
|
<url>https://repo.maven.apache.org/maven2/</url>
|
||||||
|
</repository>
|
||||||
|
</repositories>
|
||||||
</project>
|
</project>
|
@@ -4,6 +4,7 @@ import ast.type.AccessModifierNode;
|
|||||||
import ast.members.ConstructorNode;
|
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 semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
@@ -15,30 +16,20 @@ public class ClassNode implements ASTNode, Visitable {
|
|||||||
public AccessModifierNode accessType;
|
public AccessModifierNode accessType;
|
||||||
public String identifier;
|
public String identifier;
|
||||||
public List<MemberNode> members = new ArrayList<>();
|
public List<MemberNode> members = new ArrayList<>();
|
||||||
public boolean hasConstructor;
|
|
||||||
|
|
||||||
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;
|
||||||
hasConstructor = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addMember(MemberNode member) {
|
public void addMember(MemberNode member) {
|
||||||
if (member instanceof ConstructorNode) {
|
|
||||||
this.hasConstructor = true;
|
|
||||||
}
|
|
||||||
members.add(member);
|
members.add(member);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ensureConstructor(){
|
|
||||||
if(!hasConstructor) {
|
|
||||||
ConstructorNode constructor = new ConstructorNode(new AccessModifierNode("public"), identifier);
|
|
||||||
members.addFirst(constructor);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
||||||
@@ -54,4 +45,9 @@ public class ClassNode implements ASTNode, Visitable {
|
|||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(ClassVisitor classVisitor) {
|
||||||
|
classVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -1,5 +1,6 @@
|
|||||||
package ast;
|
package ast;
|
||||||
|
|
||||||
|
import bytecode.visitor.ProgramVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
@@ -18,4 +19,9 @@ public class ProgramNode implements ASTNode, Visitable {
|
|||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(ProgramVisitor programVisitor) {
|
||||||
|
programVisitor.visit(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -8,4 +8,6 @@ public interface IExpressionNode extends ASTNode, Visitable {
|
|||||||
|
|
||||||
ITypeNode getType();
|
ITypeNode getType();
|
||||||
|
|
||||||
|
void setType(ITypeNode type);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -2,10 +2,14 @@ package ast.expressions.binaryexpressions;
|
|||||||
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class BinaryNode implements IExpressionNode {
|
public class BinaryNode implements IExpressionNode, Visitable {
|
||||||
|
|
||||||
|
private ITypeNode typeNode;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
@@ -14,6 +18,16 @@ public class BinaryNode implements IExpressionNode {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ITypeNode getType() {
|
public ITypeNode getType() {
|
||||||
return null;
|
return typeNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setType(ITypeNode type) {
|
||||||
|
this.typeNode = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
package ast.expressions.binaryexpressions;
|
package ast.expressions.binaryexpressions;
|
||||||
|
|
||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -8,6 +9,7 @@ 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;
|
||||||
@@ -32,9 +34,10 @@ public class CalculationNode extends BinaryNode {
|
|||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ITypeNode getType() {
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
return null;
|
methodVisitor.visit(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
package ast.expressions.binaryexpressions;
|
package ast.expressions.binaryexpressions;
|
||||||
|
|
||||||
import ast.type.type.*;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -35,8 +35,8 @@ public class DotNode extends BinaryNode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ITypeNode getType() {
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
return null;
|
methodVisitor.visit(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -4,6 +4,7 @@ import ast.expressions.unaryexpressions.MemberAccessNode;
|
|||||||
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
import ast.type.ValueNode;
|
import ast.type.ValueNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -37,8 +38,8 @@ public class DotSubstractionNode extends BinaryNode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ITypeNode getType() {
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
return null;
|
methodVisitor.visit(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -3,6 +3,7 @@ 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 ast.type.type.*;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -43,8 +44,8 @@ public class NonCalculationNode extends BinaryNode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ITypeNode getType() {
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
return null;
|
methodVisitor.visit(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -1,13 +1,19 @@
|
|||||||
package ast.expressions.unaryexpressions;
|
package ast.expressions.unaryexpressions;
|
||||||
|
|
||||||
import ast.ASTNode;
|
import ast.ASTNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
|
import ast.type.type.ITypeNode;
|
||||||
|
import semantic.SemanticVisitor;
|
||||||
|
import typechecker.TypeCheckResult;
|
||||||
|
import visitor.Visitable;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class MemberAccessNode implements ASTNode {
|
public class MemberAccessNode implements ASTNode, Visitable {
|
||||||
public Boolean thisExpr;
|
public Boolean thisExpr;
|
||||||
public List<String> identifiers = new ArrayList<>();
|
public List<String> identifiers = new ArrayList<>();
|
||||||
|
private ITypeNode typeNode;
|
||||||
|
|
||||||
public MemberAccessNode(Boolean thisExpr) {
|
public MemberAccessNode(Boolean thisExpr) {
|
||||||
this.thisExpr = thisExpr;
|
this.thisExpr = thisExpr;
|
||||||
@@ -17,4 +23,21 @@ public class MemberAccessNode implements ASTNode {
|
|||||||
identifiers.add(identifier);
|
identifiers.add(identifier);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
|
return visitor.analyze(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ITypeNode getTypeNode() {
|
||||||
|
return typeNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTypeNode(ITypeNode typeNode) {
|
||||||
|
this.typeNode = typeNode;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -2,12 +2,26 @@ package ast.expressions.unaryexpressions;
|
|||||||
|
|
||||||
import ast.ASTNode;
|
import ast.ASTNode;
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
|
import semantic.SemanticVisitor;
|
||||||
|
import typechecker.TypeCheckResult;
|
||||||
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class NotNode implements ASTNode {
|
public class NotNode implements ASTNode, Visitable {
|
||||||
public IExpressionNode expression;
|
public IExpressionNode expression;
|
||||||
|
|
||||||
public NotNode(IExpressionNode expression) {
|
public NotNode(IExpressionNode expression) {
|
||||||
this.expression = expression;
|
this.expression = expression;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -4,6 +4,7 @@ import ast.expressions.IExpressionNode;
|
|||||||
import ast.statements.IStatementNode;
|
import ast.statements.IStatementNode;
|
||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
import ast.type.ValueNode;
|
import ast.type.ValueNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -61,4 +62,9 @@ public class UnaryNode implements IExpressionNode {
|
|||||||
this.type = type;
|
this.type = type;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
11
src/main/java/ast/literal/BooleanLiteralNode.java
Normal file
11
src/main/java/ast/literal/BooleanLiteralNode.java
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package ast.literal;
|
||||||
|
|
||||||
|
public class BooleanLiteralNode {
|
||||||
|
private String value;
|
||||||
|
|
||||||
|
public BooleanLiteralNode(String value) {this.value = value;}
|
||||||
|
|
||||||
|
public String getValue() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
11
src/main/java/ast/literal/CharLiteralNode.java
Normal file
11
src/main/java/ast/literal/CharLiteralNode.java
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package ast.literal;
|
||||||
|
|
||||||
|
public class CharLiteralNode {
|
||||||
|
public String value;
|
||||||
|
|
||||||
|
public CharLiteralNode(String value) {this.value = value;}
|
||||||
|
|
||||||
|
public String getValue() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
31
src/main/java/ast/literal/LiteralNode.java
Normal file
31
src/main/java/ast/literal/LiteralNode.java
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
@@ -3,21 +3,19 @@ package ast.members;
|
|||||||
import ast.parameters.ParameterNode;
|
import ast.parameters.ParameterNode;
|
||||||
import ast.statements.BlockNode;
|
import ast.statements.BlockNode;
|
||||||
import ast.type.AccessModifierNode;
|
import ast.type.AccessModifierNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
|
import visitor.Visitable;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
public class ConstructorNode extends MethodNode {
|
public class ConstructorNode extends MethodNode implements Visitable {
|
||||||
public AccessModifierNode accessType;
|
public AccessModifierNode accessType;
|
||||||
public String identifier;
|
public String identifier;
|
||||||
public List<ParameterNode> parameters = new ArrayList<>();
|
public List<ParameterNode> parameters = new ArrayList<>();
|
||||||
public BlockNode block;
|
public BlockNode block;
|
||||||
|
|
||||||
public ConstructorNode(AccessModifierNode accessType, String identifier) {
|
|
||||||
this.accessType = accessType;
|
|
||||||
this.identifier = identifier;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ConstructorNode(String accessType, String identifier, BlockNode block) {
|
public ConstructorNode(String accessType, String identifier, BlockNode block) {
|
||||||
this.accessType = new AccessModifierNode(accessType);
|
this.accessType = new AccessModifierNode(accessType);
|
||||||
this.identifier = identifier;
|
this.identifier = identifier;
|
||||||
@@ -28,4 +26,22 @@ public class ConstructorNode extends MethodNode {
|
|||||||
parameters.add(parameterNode);
|
parameters.add(parameterNode);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isSame(MethodNode methodNode) {
|
||||||
|
if (!(Objects.equals(this.identifier, methodNode.getIdentifier()))
|
||||||
|
|| getParameters().size() != methodNode.getParameters().size()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < this.getParameters().size(); i++) {
|
||||||
|
if (!this.getParameters().get(i).type.equals(methodNode.getParameters().get(i).type)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -2,6 +2,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.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
@@ -22,4 +24,9 @@ public class FieldNode implements MemberNode, Visitable {
|
|||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(ClassVisitor classVisitor) {
|
||||||
|
classVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -1,11 +1,18 @@
|
|||||||
package ast.members;
|
package ast.members;
|
||||||
|
|
||||||
import ast.statements.BlockNode;
|
import ast.statements.BlockNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class MainMethodNode extends MethodNode {
|
public class MainMethodNode extends MethodNode implements Visitable {
|
||||||
public BlockNode block;
|
public BlockNode block;
|
||||||
|
|
||||||
public MainMethodNode(BlockNode block) {
|
public MainMethodNode(BlockNode block) {
|
||||||
this.block = block;
|
this.block = block;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -21,7 +21,8 @@ public class MethodNode implements MemberNode, Visitable {
|
|||||||
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);
|
||||||
@@ -46,7 +47,7 @@ public class MethodNode implements MemberNode, Visitable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (int i = 0; i < this.getParameters().size(); i++) {
|
for (int i = 0; i < this.getParameters().size(); i++) {
|
||||||
if (this.getParameters().get(i).type.equals(methodNode.getParameters().get(i).type)) {
|
if (!this.getParameters().get(i).type.equals(methodNode.getParameters().get(i).type)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
11
src/main/java/ast/statement/BlockStatementNode.java
Normal file
11
src/main/java/ast/statement/BlockStatementNode.java
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
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;}
|
||||||
|
}
|
@@ -1,6 +1,7 @@
|
|||||||
package ast.statementexpressions;
|
package ast.statementexpressions;
|
||||||
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -18,4 +19,9 @@ public class AssignNode implements IStatementExpressionNode {
|
|||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -1,11 +1,13 @@
|
|||||||
package ast.statementexpressions;
|
package ast.statementexpressions;
|
||||||
|
|
||||||
import ast.expressions.unaryexpressions.MemberAccessNode;
|
import ast.expressions.unaryexpressions.MemberAccessNode;
|
||||||
|
import ast.type.type.ITypeNode;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
public class AssignableNode implements IStatementExpressionNode {
|
public class AssignableNode implements IStatementExpressionNode {
|
||||||
public String identifier;
|
public String identifier;
|
||||||
|
private ITypeNode typeNode;
|
||||||
|
|
||||||
public MemberAccessNode memberAccess;
|
public MemberAccessNode memberAccess;
|
||||||
|
|
||||||
@@ -22,4 +24,12 @@ public class AssignableNode implements IStatementExpressionNode {
|
|||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ITypeNode getTypeNode() {
|
||||||
|
return typeNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTypeNode(ITypeNode typeNode) {
|
||||||
|
this.typeNode = typeNode;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
package ast.statementexpressions;
|
package ast.statementexpressions;
|
||||||
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -24,4 +25,9 @@ public class NewDeclarationNode implements IStatementExpressionNode {
|
|||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -2,8 +2,10 @@ package ast.statementexpressions.crementexpressions;
|
|||||||
|
|
||||||
import ast.statementexpressions.AssignableNode;
|
import ast.statementexpressions.AssignableNode;
|
||||||
import ast.statementexpressions.IStatementExpressionNode;
|
import ast.statementexpressions.IStatementExpressionNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class DecrementNode implements IStatementExpressionNode {
|
public class DecrementNode implements IStatementExpressionNode {
|
||||||
public CrementType crementType;
|
public CrementType crementType;
|
||||||
@@ -18,5 +20,4 @@ public class DecrementNode implements IStatementExpressionNode {
|
|||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -2,6 +2,7 @@ package ast.statementexpressions.crementexpressions;
|
|||||||
|
|
||||||
import ast.statementexpressions.AssignableNode;
|
import ast.statementexpressions.AssignableNode;
|
||||||
import ast.statementexpressions.IStatementExpressionNode;
|
import ast.statementexpressions.IStatementExpressionNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -18,5 +19,4 @@ public class IncrementNode implements IStatementExpressionNode {
|
|||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -2,11 +2,15 @@ package ast.statementexpressions.methodcallstatementnexpressions;
|
|||||||
|
|
||||||
import ast.ASTNode;
|
import ast.ASTNode;
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
|
import semantic.SemanticVisitor;
|
||||||
|
import typechecker.TypeCheckResult;
|
||||||
|
import visitor.Visitable;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class ChainedMethodNode implements ASTNode {
|
public class ChainedMethodNode implements ASTNode, Visitable {
|
||||||
public String identifier;
|
public String identifier;
|
||||||
public List<IExpressionNode> expressions = new ArrayList<>();
|
public List<IExpressionNode> expressions = new ArrayList<>();
|
||||||
|
|
||||||
@@ -17,4 +21,14 @@ public class ChainedMethodNode implements ASTNode {
|
|||||||
public void addExpression(IExpressionNode expression) {
|
public void addExpression(IExpressionNode expression) {
|
||||||
expressions.add(expression);
|
expressions.add(expression);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -2,6 +2,7 @@ package ast.statementexpressions.methodcallstatementnexpressions;
|
|||||||
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import ast.statements.IStatementNode;
|
import ast.statements.IStatementNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -32,4 +33,9 @@ public class MethodCallNode implements IStatementNode {
|
|||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -3,8 +3,12 @@ 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 typechecker.TypeCheckResult;
|
||||||
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class TargetNode implements ASTNode {
|
public class TargetNode implements ASTNode, Visitable {
|
||||||
public Boolean thisTar;
|
public Boolean thisTar;
|
||||||
public MemberAccessNode memberAccess;
|
public MemberAccessNode memberAccess;
|
||||||
public NewDeclarationNode newDeclaration;
|
public NewDeclarationNode newDeclaration;
|
||||||
@@ -25,4 +29,10 @@ public class TargetNode implements ASTNode {
|
|||||||
public TargetNode(String identifier) {
|
public TargetNode(String identifier) {
|
||||||
this.identifier = identifier;
|
this.identifier = identifier;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
|
return visitor.analyze(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
10
src/main/java/ast/statements/BlockStatementNode.java
Normal file
10
src/main/java/ast/statements/BlockStatementNode.java
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package ast.statements;
|
||||||
|
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class BlockStatementNode {
|
||||||
|
List<IStatementNode> statements;
|
||||||
|
|
||||||
|
public BlockStatementNode(List<IStatementNode> statements) {this.statements = statements;}
|
||||||
|
}
|
@@ -1,11 +1,10 @@
|
|||||||
package ast.statements;
|
package ast.statements;
|
||||||
|
|
||||||
import ast.ASTNode;
|
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
public class ElseNode implements IStatementNode {
|
public class ElseNode implements IStatementNode {
|
||||||
BlockNode block;
|
public BlockNode block;
|
||||||
|
|
||||||
public ElseNode(BlockNode block) {
|
public ElseNode(BlockNode block) {
|
||||||
this.block = block;
|
this.block = block;
|
||||||
@@ -14,6 +13,6 @@ public class ElseNode implements IStatementNode {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return null;
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,5 @@
|
|||||||
package ast.statements;
|
package ast.statements;
|
||||||
|
|
||||||
import ast.ASTNode;
|
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -8,9 +7,9 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class IfElseNode implements IStatementNode {
|
public class IfElseNode implements IStatementNode {
|
||||||
IfNode ifStatement;
|
public IfNode ifStatement;
|
||||||
List<IfNode> elseIfStatements = new ArrayList<>();
|
public List<IfNode> elseIfStatements = new ArrayList<>();
|
||||||
ElseNode elseStatement;
|
public ElseNode elseStatement;
|
||||||
|
|
||||||
public IfElseNode(IfNode ifStatement, ElseNode elseNode) {
|
public IfElseNode(IfNode ifStatement, ElseNode elseNode) {
|
||||||
this.ifStatement = ifStatement;
|
this.ifStatement = ifStatement;
|
||||||
@@ -23,6 +22,6 @@ public class IfElseNode implements IStatementNode {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return null;
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,13 +1,12 @@
|
|||||||
package ast.statements;
|
package ast.statements;
|
||||||
|
|
||||||
import ast.ASTNode;
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
public class IfNode implements IStatementNode {
|
public class IfNode implements IStatementNode {
|
||||||
IExpressionNode expression;
|
public IExpressionNode expression;
|
||||||
BlockNode block;
|
public BlockNode block;
|
||||||
|
|
||||||
public IfNode(IExpressionNode expression, BlockNode block) {
|
public IfNode(IExpressionNode expression, BlockNode block) {
|
||||||
this.expression = expression;
|
this.expression = expression;
|
||||||
@@ -16,6 +15,6 @@ public class IfNode implements IStatementNode {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return null;
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -2,6 +2,7 @@ package ast.statements;
|
|||||||
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -23,4 +24,9 @@ public class LocalVariableDeclarationNode implements IStatementNode {
|
|||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
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 typechecker.TypeCheckResult;
|
||||||
|
|
||||||
@@ -21,4 +22,9 @@ public class ReturnNode implements IStatementNode {
|
|||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -1,13 +1,12 @@
|
|||||||
package ast.statements;
|
package ast.statements;
|
||||||
|
|
||||||
import ast.ASTNode;
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
public class WhileNode implements IStatementNode {
|
public class WhileNode implements IStatementNode {
|
||||||
IExpressionNode expression;
|
public IExpressionNode expression;
|
||||||
BlockNode block;
|
public BlockNode block;
|
||||||
|
|
||||||
public WhileNode(IExpressionNode expression, BlockNode block) {
|
public WhileNode(IExpressionNode expression, BlockNode block) {
|
||||||
this.expression = expression;
|
this.expression = expression;
|
||||||
@@ -21,6 +20,6 @@ public class WhileNode implements IStatementNode {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return null;
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,8 +1,12 @@
|
|||||||
package ast.type;
|
package ast.type;
|
||||||
|
|
||||||
import ast.ASTNode;
|
import ast.ASTNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
|
import semantic.SemanticVisitor;
|
||||||
|
import typechecker.TypeCheckResult;
|
||||||
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class ValueNode implements ASTNode {
|
public class ValueNode implements ASTNode, Visitable {
|
||||||
public EnumValueNode valueType;
|
public EnumValueNode valueType;
|
||||||
public String value;
|
public String value;
|
||||||
|
|
||||||
@@ -10,4 +14,14 @@ public class ValueNode implements ASTNode {
|
|||||||
this.valueType = valueType;
|
this.valueType = valueType;
|
||||||
this.value = value;
|
this.value = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
|
return visitor.analyze(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -2,21 +2,89 @@ package bytecode;
|
|||||||
|
|
||||||
import ast.ProgramNode;
|
import ast.ProgramNode;
|
||||||
import ast.ClassNode;
|
import ast.ClassNode;
|
||||||
|
import ast.members.MainMethodNode;
|
||||||
|
import ast.members.MemberNode;
|
||||||
import bytecode.visitor.ProgramVisitor;
|
import bytecode.visitor.ProgramVisitor;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.jar.JarOutputStream;
|
||||||
|
import java.util.jar.Manifest;
|
||||||
|
|
||||||
public class ByteCodeGenerator implements ProgramVisitor {
|
public class ByteCodeGenerator implements ProgramVisitor {
|
||||||
|
|
||||||
private final String outputDirectoryPath;
|
private JarOutputStream jarOutputStream;
|
||||||
|
private ByteArrayOutputStream byteArrayOutputStream;
|
||||||
|
private String outputDirectory;
|
||||||
|
private boolean generateJar;
|
||||||
|
private boolean generateClassFiles;
|
||||||
|
|
||||||
public ByteCodeGenerator(String outputDirectoryPath) {
|
public ByteCodeGenerator(String outputDirectory, boolean generateJar, boolean generateClassFiles) {
|
||||||
this.outputDirectoryPath = outputDirectoryPath;
|
this.outputDirectory = outputDirectory;
|
||||||
}
|
this.generateJar = generateJar;
|
||||||
|
this.generateClassFiles = generateClassFiles;
|
||||||
@Override
|
}
|
||||||
public void visit(ProgramNode programNode) {
|
|
||||||
for (ClassNode classDeclarationNode : programNode.classes) {
|
@Override
|
||||||
// ClassCodeGen classCodeGen = new ClassCodeGen();
|
public void visit(ProgramNode programNode) {
|
||||||
// classDeclarationNode.accept(classCodeGen);
|
if(generateJar) {
|
||||||
|
byteArrayOutputStream = new ByteArrayOutputStream();
|
||||||
|
try {
|
||||||
|
Manifest manifest = new Manifest();
|
||||||
|
manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
|
||||||
|
boolean foundMainClass = false;
|
||||||
|
for (ClassNode classNode : programNode.classes) {
|
||||||
|
if (foundMainClass) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
for (MemberNode memberNode : classNode.members) {
|
||||||
|
if (memberNode instanceof MainMethodNode) {
|
||||||
|
manifest.getMainAttributes().putValue("Main-Class", classNode.identifier);
|
||||||
|
foundMainClass = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
jarOutputStream = new JarOutputStream(byteArrayOutputStream, manifest);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (ClassNode classDeclarationNode : programNode.classes) {
|
||||||
|
ClassCodeGen classCodeGen = new ClassCodeGen(jarOutputStream, outputDirectory, generateJar, generateClassFiles);
|
||||||
|
classDeclarationNode.accept(classCodeGen);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
jarOutputStream.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
saveJarFile(byteArrayOutputStream.toByteArray(), "output.jar");
|
||||||
|
} else {
|
||||||
|
for (ClassNode classDeclarationNode : programNode.classes) {
|
||||||
|
ClassCodeGen classCodeGen = new ClassCodeGen(jarOutputStream, outputDirectory, generateJar, generateClassFiles);
|
||||||
|
classDeclarationNode.accept(classCodeGen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveJarFile(byte[] jarBytes, String jarFileName) {
|
||||||
|
File directory = new File(outputDirectory);
|
||||||
|
if (!directory.exists()) {
|
||||||
|
directory.mkdirs();
|
||||||
|
}
|
||||||
|
|
||||||
|
File jarFile = new File(directory, jarFileName);
|
||||||
|
try (FileOutputStream fos = new FileOutputStream(jarFile)) {
|
||||||
|
fos.write(jarBytes);
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@@ -10,26 +10,35 @@ import bytecode.visitor.ClassVisitor;
|
|||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
|
||||||
import org.objectweb.asm.ClassWriter;
|
import org.objectweb.asm.ClassWriter;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|
||||||
import java.io.FileOutputStream;
|
import java.io.FileOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.jar.JarEntry;
|
||||||
|
import java.util.jar.JarOutputStream;
|
||||||
|
|
||||||
|
|
||||||
public class ClassCodeGen implements ClassVisitor {
|
public class ClassCodeGen implements ClassVisitor {
|
||||||
private Mapper mapper;
|
private Mapper mapper;
|
||||||
private ClassWriter classWriter;
|
private ClassWriter classWriter;
|
||||||
private final String outputDirectoryPath;
|
private JarOutputStream jarOutputStream;
|
||||||
|
private String outputDirectory;
|
||||||
|
private boolean generateJar;
|
||||||
|
private boolean generateClassFiles;
|
||||||
|
|
||||||
public ClassCodeGen(String outputDirectoryPath) {
|
public ClassCodeGen(JarOutputStream jarOutputStream, String outputDirectory, boolean generateJar, boolean generateClassFiles) {
|
||||||
this.outputDirectoryPath = outputDirectoryPath;
|
|
||||||
mapper = new Mapper();
|
mapper = new Mapper();
|
||||||
|
this.jarOutputStream = jarOutputStream;
|
||||||
|
this.outputDirectory = outputDirectory;
|
||||||
|
this.generateJar = generateJar;
|
||||||
|
this.generateClassFiles = generateClassFiles;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visit(ClassNode classNode) {
|
public void visit(ClassNode classNode) {
|
||||||
classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
|
classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
|
||||||
// classWriter.visit(Opcodes.V1_5, mapper.mapAccessTypeToOpcode(classNode.accessType), classNode.identifier, null,
|
classWriter.visit(Opcodes.V1_5, mapper.mapAccessTypeToOpcode(classNode.accessType), classNode.identifier, null,
|
||||||
// "java/lang/Object", null);
|
"java/lang/Object", null);
|
||||||
|
|
||||||
for (MemberNode memberNode : classNode.members) {
|
for (MemberNode memberNode : classNode.members) {
|
||||||
if (memberNode instanceof FieldNode) {
|
if (memberNode instanceof FieldNode) {
|
||||||
@@ -40,29 +49,31 @@ public class ClassCodeGen implements ClassVisitor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
classWriter.visitEnd();
|
if (generateJar) {
|
||||||
printIntoClassFile(classWriter.toByteArray(), classNode.identifier);
|
writeToJar(classWriter.toByteArray(), classNode.identifier);
|
||||||
|
}
|
||||||
|
if (generateClassFiles) {
|
||||||
|
printIntoClassFile(classWriter.toByteArray(), classNode.identifier, outputDirectory);
|
||||||
|
}
|
||||||
|
|
||||||
classWriter.visitEnd();
|
classWriter.visitEnd();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visit(FieldNode fieldNode) {
|
public void visit(FieldNode fieldNode) {
|
||||||
if(fieldNode.type instanceof BaseType baseTypeNode){
|
if (fieldNode.type instanceof BaseType) {
|
||||||
// classWriter.visitField(mapper.mapAccessTypeToOpcode(fieldNode.accessTypeNode), fieldNode.identifier, mapper.getTypeChar(baseTypeNode.enumType), null, null );
|
classWriter.visitField(mapper.mapAccessTypeToOpcode(fieldNode.accessTypeNode), fieldNode.identifier, mapper.getTypeChar((BaseType) fieldNode.type), null, null);
|
||||||
}
|
}
|
||||||
classWriter.visitEnd();
|
classWriter.visitEnd();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void printIntoClassFile(byte[] byteCode, String name) {
|
private void printIntoClassFile(byte[] byteCode, String name, String outputDirectory) {
|
||||||
// String outputDirectoryPath = "src/main/resources/output";
|
File directory = new File(outputDirectory);
|
||||||
// System.out.println("Output directory path: " + outputDirectoryPath);
|
|
||||||
File directory = new File(outputDirectoryPath);
|
|
||||||
if (!directory.exists()) {
|
if (!directory.exists()) {
|
||||||
directory.mkdirs();
|
directory.mkdirs();
|
||||||
}
|
}
|
||||||
|
|
||||||
String filePath = outputDirectoryPath + "/" + name + ".class";
|
String filePath = outputDirectory + "/" + name + ".class";
|
||||||
try {
|
try {
|
||||||
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
|
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
|
||||||
fileOutputStream.write(byteCode);
|
fileOutputStream.write(byteCode);
|
||||||
@@ -71,4 +82,15 @@ public class ClassCodeGen implements ClassVisitor {
|
|||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void writeToJar(byte[] byteCode, String className) {
|
||||||
|
try {
|
||||||
|
JarEntry jarEntry = new JarEntry(className + ".class");
|
||||||
|
jarOutputStream.putNextEntry(jarEntry);
|
||||||
|
jarOutputStream.write(byteCode);
|
||||||
|
jarOutputStream.closeEntry();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,41 +1,60 @@
|
|||||||
package bytecode;
|
package bytecode;
|
||||||
|
|
||||||
|
import ast.parameters.ParameterNode;
|
||||||
import ast.type.*;
|
import ast.type.*;
|
||||||
|
import ast.type.type.BaseType;
|
||||||
|
import ast.type.type.ReferenceType;
|
||||||
|
import ast.type.type.TypeEnum;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
public class Mapper {
|
public class Mapper {
|
||||||
// public int mapAccessTypeToOpcode(AccessModifierNode type) {
|
public int mapAccessTypeToOpcode(AccessModifierNode accessModifierNode) {
|
||||||
// switch (type.enumAccessTypeNode) {
|
switch (accessModifierNode.accessType) {
|
||||||
// case EnumAccessTypeNode.PUBLIC:
|
case EnumAccessModifierNode.PUBLIC:
|
||||||
// return Opcodes.ACC_PUBLIC;
|
return Opcodes.ACC_PUBLIC;
|
||||||
// case EnumAccessTypeNode.PRIVATE:
|
case EnumAccessModifierNode.PRIVATE:
|
||||||
// return Opcodes.ACC_PRIVATE;
|
return Opcodes.ACC_PRIVATE;
|
||||||
// }
|
case EnumAccessModifierNode.PUBLIC_STATIC:
|
||||||
// return 0;
|
return Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC;
|
||||||
// }
|
case EnumAccessModifierNode.PRIVATE_STATIC:
|
||||||
|
return Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
// public String generateMethodDescriptor(BaseTypeNode baseTypeNode, ParameterListNode parameterListNode) {
|
public String generateMethodDescriptor(BaseType type, List<ParameterNode> parameters) {
|
||||||
// String descriptor = "(";
|
String descriptor = "(";
|
||||||
// for(ParameterNode parameterNode : parameterListNode.parameters) {
|
for (ParameterNode parameterNode : parameters) {
|
||||||
// descriptor += getTypeChar(EnumTypeNode.INT);
|
if(parameterNode.type instanceof BaseType) {
|
||||||
// }
|
descriptor += getTypeChar((BaseType) parameterNode.type);
|
||||||
// descriptor += ")";
|
} else {
|
||||||
// descriptor += getTypeChar(baseTypeNode.enumType);
|
ReferenceType referenceType = (ReferenceType) parameterNode.type;
|
||||||
// return descriptor;
|
descriptor += "L" + referenceType.getIdentifier() + ";";
|
||||||
// }
|
}
|
||||||
|
}
|
||||||
|
descriptor += ")";
|
||||||
|
descriptor += getTypeChar(type);
|
||||||
|
return descriptor;
|
||||||
|
}
|
||||||
|
|
||||||
// public String getTypeChar(TypeEnum enumTypeNode) {
|
public String getTypeChar(BaseType type) {
|
||||||
// String typeChar = "";
|
String typeChar = "";
|
||||||
// switch (enumTypeNode) {
|
switch (type.getTypeEnum()) {
|
||||||
// case TypeEnum.INT:
|
case TypeEnum.INT:
|
||||||
// typeChar = "I";
|
typeChar = "I";
|
||||||
// break;
|
break;
|
||||||
// case TypeEnum.CHAR:
|
case TypeEnum.CHAR:
|
||||||
// typeChar = "C";
|
typeChar = "C";
|
||||||
// break;
|
break;
|
||||||
// case TypeEnum.BOOLEAN:
|
case TypeEnum.BOOL:
|
||||||
// typeChar = "Z";
|
typeChar = "Z";
|
||||||
// break;
|
break;
|
||||||
// }
|
case TypeEnum.VOID:
|
||||||
// return typeChar;
|
typeChar = "V";
|
||||||
// }
|
break;
|
||||||
|
}
|
||||||
|
return typeChar;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,9 +1,31 @@
|
|||||||
package bytecode;
|
package bytecode;
|
||||||
|
|
||||||
|
import ast.expressions.IExpressionNode;
|
||||||
|
import ast.expressions.binaryexpressions.*;
|
||||||
|
import ast.expressions.unaryexpressions.MemberAccessNode;
|
||||||
|
import ast.expressions.unaryexpressions.NotNode;
|
||||||
|
import ast.expressions.unaryexpressions.UnaryNode;
|
||||||
import ast.members.ConstructorNode;
|
import ast.members.ConstructorNode;
|
||||||
|
import ast.members.MainMethodNode;
|
||||||
import ast.members.MethodNode;
|
import ast.members.MethodNode;
|
||||||
|
import ast.parameters.ParameterNode;
|
||||||
|
import ast.statementexpressions.AssignNode;
|
||||||
|
import ast.statementexpressions.NewDeclarationNode;
|
||||||
|
import ast.statementexpressions.crementexpressions.CrementType;
|
||||||
|
import ast.statementexpressions.crementexpressions.DecrementNode;
|
||||||
|
import ast.statementexpressions.crementexpressions.IncrementNode;
|
||||||
|
import ast.statementexpressions.methodcallstatementnexpressions.ChainedMethodNode;
|
||||||
|
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
||||||
|
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
|
||||||
|
import ast.statements.*;
|
||||||
|
import ast.type.ValueNode;
|
||||||
|
import ast.type.type.BaseType;
|
||||||
|
import ast.type.type.ReferenceType;
|
||||||
|
import ast.type.type.TypeEnum;
|
||||||
import org.objectweb.asm.ClassWriter;
|
import org.objectweb.asm.ClassWriter;
|
||||||
|
import org.objectweb.asm.Label;
|
||||||
import org.objectweb.asm.MethodVisitor;
|
import org.objectweb.asm.MethodVisitor;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -17,78 +39,498 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
private Mapper mapper;
|
private Mapper mapper;
|
||||||
private MethodVisitor methodVisitor;
|
private MethodVisitor methodVisitor;
|
||||||
|
|
||||||
private List<String> localVaribales;
|
private List<String> localVariables;
|
||||||
|
|
||||||
public MethodCodeGen(ClassWriter classWriter) {
|
public MethodCodeGen(ClassWriter classWriter) {
|
||||||
this.classWriter = classWriter;
|
this.classWriter = classWriter;
|
||||||
mapper = new Mapper();
|
mapper = new Mapper();
|
||||||
localVaribales = new ArrayList<>();
|
localVariables = new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Method nodes
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visit(ConstructorNode constructorNode) {
|
public void visit(ConstructorNode constructorNode) {
|
||||||
// methodVisitor =
|
methodVisitor =
|
||||||
// classWriter.visitMethod(mapper.mapAccessTypeToOpcode(constructorNode.visibility),
|
classWriter.visitMethod(mapper.mapAccessTypeToOpcode(constructorNode.accessType),
|
||||||
// "<init>",
|
"<init>",
|
||||||
// "()V",
|
mapper.generateMethodDescriptor(new BaseType(TypeEnum.VOID), constructorNode.parameters),
|
||||||
// null,
|
null,
|
||||||
// null);
|
null);
|
||||||
|
|
||||||
methodVisitor.visitCode();
|
methodVisitor.visitCode();
|
||||||
|
localVariables.add("this");
|
||||||
|
// Add all method parameters to localVariables
|
||||||
|
for (ParameterNode parameterNode : constructorNode.parameters) {
|
||||||
|
localVariables.add(parameterNode.identifier);
|
||||||
|
}
|
||||||
|
|
||||||
methodVisitor.visitVarInsn(ALOAD, 0);
|
methodVisitor.visitVarInsn(ALOAD, 0);
|
||||||
methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
||||||
methodVisitor.visitInsn(RETURN);
|
|
||||||
methodVisitor.visitMaxs(1, 1);
|
// Visit all statements
|
||||||
|
for (IStatementNode statementNode : constructorNode.block.statements) {
|
||||||
|
if (statementNode != null) {
|
||||||
|
statementNode.accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
methodVisitor.visitMaxs(0, 0);
|
||||||
|
methodVisitor.visitEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(MainMethodNode mainMethodNode) {
|
||||||
|
methodVisitor = classWriter.visitMethod(mapper.mapAccessTypeToOpcode(mainMethodNode.accesModifier),
|
||||||
|
mainMethodNode.getIdentifier(),
|
||||||
|
"([Ljava/lang/String;)V",
|
||||||
|
null,
|
||||||
|
null);
|
||||||
|
|
||||||
|
methodVisitor.visitCode();
|
||||||
|
localVariables.add("this");
|
||||||
|
localVariables.add("args");
|
||||||
|
|
||||||
|
// Visit all statements
|
||||||
|
for (IStatementNode statementNode : mainMethodNode.block.statements) {
|
||||||
|
statementNode.accept(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
methodVisitor.visitMaxs(0, 0);
|
||||||
methodVisitor.visitEnd();
|
methodVisitor.visitEnd();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visit(MethodNode methodNode) {
|
public void visit(MethodNode methodNode) {
|
||||||
// if (methodNode.type instanceof BaseTypeNode baseTypeNode) {
|
methodVisitor = classWriter.visitMethod(mapper.mapAccessTypeToOpcode(methodNode.accesModifier),
|
||||||
// methodVisitor = classWriter.visitMethod(mapper.mapAccessTypeToOpcode(methodNode.visibility),
|
methodNode.getIdentifier(),
|
||||||
// methodNode.identifier,
|
mapper.generateMethodDescriptor((BaseType) methodNode.getType(), methodNode.parameters),
|
||||||
// mapper.generateMethodDescriptor(baseTypeNode, methodNode.parameters),
|
null,
|
||||||
// null,
|
null);
|
||||||
// null);
|
|
||||||
|
|
||||||
methodVisitor.visitCode();
|
methodVisitor.visitCode();
|
||||||
localVaribales.add("this");
|
localVariables.add("this");
|
||||||
// for (ParameterNode parameterNode : methodNode.parameters.parameters) {
|
// Add all method parameters to localVariables
|
||||||
// localVaribales.add(parameterNode.identifier);
|
for (ParameterNode parameterNode : methodNode.parameters) {
|
||||||
// }
|
localVariables.add(parameterNode.identifier);
|
||||||
|
}
|
||||||
|
|
||||||
//test();
|
// Visit all statements
|
||||||
methodVisitor.visitMaxs(1, localVaribales.size());
|
for (IStatementNode statementNode : methodNode.block.statements) {
|
||||||
methodVisitor.visitEnd();
|
statementNode.accept(this);
|
||||||
// }
|
}
|
||||||
|
|
||||||
|
methodVisitor.visitMaxs(0, 0);
|
||||||
|
methodVisitor.visitEnd();
|
||||||
}
|
}
|
||||||
|
|
||||||
// public void test() {
|
|
||||||
// Label start = new Label();
|
// Binary expressions
|
||||||
// Label loop = new Label();
|
|
||||||
// Label end = new Label();
|
@Override
|
||||||
// methodVisitor.visitLabel(start);
|
public void visit(BinaryNode binaryNode) {
|
||||||
// //methodVisitor.visitVarInsn(Opcodes.ICONST_M1, 99);
|
binaryNode.accept(this);
|
||||||
// //methodVisitor.visitInsn(Opcodes.ICONST_5);
|
}
|
||||||
// methodVisitor.visitLdcInsn(99);
|
|
||||||
// // methodVisitor.visitInsn(Opcodes.ICONST_0);
|
@Override
|
||||||
// //methodVisitor.visitVarInsn(Opcodes.ILOAD, 2);
|
public void visit(CalculationNode calculationNode) {
|
||||||
// methodVisitor.visitVarInsn(Opcodes.ISTORE, 1);
|
if (calculationNode.dotExpression != null) {
|
||||||
// methodVisitor.visitLabel(loop);
|
calculationNode.dotExpression.accept(this);
|
||||||
// methodVisitor.visitVarInsn(Opcodes.ILOAD, 1);
|
}
|
||||||
// methodVisitor.visitInsn(Opcodes.ICONST_5);
|
if (calculationNode.calculationExpression != null) {
|
||||||
// methodVisitor.visitJumpInsn(Opcodes.IF_ICMPGE, end);
|
calculationNode.calculationExpression.accept(this);
|
||||||
// methodVisitor.visitFieldInsn(Opcodes.GETSTATIC,
|
}
|
||||||
// "java/lang/System", "out",
|
if (calculationNode.operator != null) {
|
||||||
// "Ljava/io/PrintStream;");
|
switch (calculationNode.operator) {
|
||||||
// methodVisitor.visitLdcInsn("Bytecode");
|
case PLUS:
|
||||||
// methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
|
methodVisitor.visitInsn(IADD);
|
||||||
// "java/io/PrintStream", "println",
|
break;
|
||||||
// "(Ljava/lang/String;)V", false);
|
case MINUS:
|
||||||
// methodVisitor.visitIincInsn(1, 1);
|
methodVisitor.visitInsn(ISUB);
|
||||||
// methodVisitor.visitJumpInsn(Opcodes.GOTO, loop);
|
break;
|
||||||
// methodVisitor.visitLabel(end);
|
}
|
||||||
// methodVisitor.visitVarInsn(Opcodes.ILOAD, 1);
|
}
|
||||||
// methodVisitor.visitInsn(Opcodes.IRETURN);
|
}
|
||||||
// methodVisitor.visitEnd();
|
|
||||||
// }
|
@Override
|
||||||
|
public void visit(DotNode dotNode) {
|
||||||
|
if (dotNode.dotExpression != null) {
|
||||||
|
dotNode.dotExpression.accept(this);
|
||||||
|
}
|
||||||
|
if (dotNode.dotSubstractionExpression != null) {
|
||||||
|
dotNode.dotSubstractionExpression.accept(this);
|
||||||
|
}
|
||||||
|
if (dotNode.operator != null) {
|
||||||
|
switch (dotNode.operator) {
|
||||||
|
case DIV:
|
||||||
|
methodVisitor.visitInsn(IDIV);
|
||||||
|
break;
|
||||||
|
case MULT:
|
||||||
|
methodVisitor.visitInsn(IMUL);
|
||||||
|
break;
|
||||||
|
case MOD:
|
||||||
|
methodVisitor.visitInsn(IREM);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(DotSubstractionNode dotSubstractionNode) {
|
||||||
|
if (dotSubstractionNode.value != null) {
|
||||||
|
dotSubstractionNode.value.accept(this);
|
||||||
|
} else if (dotSubstractionNode.identifier != null) {
|
||||||
|
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(dotSubstractionNode.identifier));
|
||||||
|
} else if (dotSubstractionNode.memberAccess != null) {
|
||||||
|
dotSubstractionNode.memberAccess.accept(this);
|
||||||
|
} else if (dotSubstractionNode.methodCall != null) {
|
||||||
|
dotSubstractionNode.methodCall.accept(this);
|
||||||
|
} else if (dotSubstractionNode.calculationExpression != null) {
|
||||||
|
dotSubstractionNode.calculationExpression.accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(NonCalculationNode nonCalculationNode) {
|
||||||
|
Label labelFalse = new Label();
|
||||||
|
Label labelTrue = new Label();
|
||||||
|
switch (nonCalculationNode.operator) {
|
||||||
|
case AND:
|
||||||
|
nonCalculationNode.unaryExpression.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(IFEQ, labelFalse); // Value compared to 0 (false)
|
||||||
|
nonCalculationNode.expression.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(IFEQ, labelFalse);
|
||||||
|
break;
|
||||||
|
case OR:
|
||||||
|
nonCalculationNode.unaryExpression.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(IFNE, labelTrue);
|
||||||
|
nonCalculationNode.expression.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(IFEQ, labelFalse);
|
||||||
|
break;
|
||||||
|
case GREATER:
|
||||||
|
nonCalculationNode.unaryExpression.accept(this);
|
||||||
|
nonCalculationNode.expression.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(IF_ICMPLE, labelFalse);
|
||||||
|
break;
|
||||||
|
case LESS:
|
||||||
|
nonCalculationNode.unaryExpression.accept(this);
|
||||||
|
nonCalculationNode.expression.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(IF_ICMPGE, labelFalse);
|
||||||
|
break;
|
||||||
|
case GREATER_EQUAL:
|
||||||
|
nonCalculationNode.unaryExpression.accept(this);
|
||||||
|
nonCalculationNode.expression.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(IF_ICMPLT, labelFalse);
|
||||||
|
break;
|
||||||
|
case LESS_EQUAL:
|
||||||
|
nonCalculationNode.unaryExpression.accept(this);
|
||||||
|
nonCalculationNode.expression.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(IF_ICMPGT, labelFalse);
|
||||||
|
break;
|
||||||
|
case EQUAL:
|
||||||
|
nonCalculationNode.unaryExpression.accept(this);
|
||||||
|
nonCalculationNode.expression.accept(this);
|
||||||
|
if (nonCalculationNode.unaryExpression.getType() instanceof BaseType && nonCalculationNode.expression.getType() instanceof BaseType) {
|
||||||
|
methodVisitor.visitJumpInsn(IF_ICMPNE, labelFalse);
|
||||||
|
} else {
|
||||||
|
methodVisitor.visitJumpInsn(IF_ACMPNE, labelFalse);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case NOT_EQUAL:
|
||||||
|
nonCalculationNode.unaryExpression.accept(this);
|
||||||
|
nonCalculationNode.expression.accept(this);
|
||||||
|
if (nonCalculationNode.unaryExpression.getType() instanceof BaseType && nonCalculationNode.expression.getType() instanceof BaseType) {
|
||||||
|
methodVisitor.visitJumpInsn(IF_ACMPEQ, labelFalse);
|
||||||
|
} else {
|
||||||
|
methodVisitor.visitJumpInsn(IF_ACMPEQ, labelFalse);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
Label labelEndLogicalExpression = new Label();
|
||||||
|
|
||||||
|
methodVisitor.visitLabel(labelTrue);
|
||||||
|
methodVisitor.visitInsn(ICONST_1); // true
|
||||||
|
methodVisitor.visitJumpInsn(GOTO, labelEndLogicalExpression);
|
||||||
|
|
||||||
|
methodVisitor.visitLabel(labelFalse);
|
||||||
|
methodVisitor.visitInsn(ICONST_0); // false
|
||||||
|
|
||||||
|
methodVisitor.visitLabel(labelEndLogicalExpression);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Unary expressions
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(MemberAccessNode memberAccessNode) {
|
||||||
|
// Only used to get, not to put
|
||||||
|
if (memberAccessNode.thisExpr) { // Field
|
||||||
|
// methodVisitor.visitFieldInsn(GETFIELD, memberAccessNode.identifiers.get(0), memberAccessNode.identifiers.get(1), );
|
||||||
|
} else { // Object Attribut
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(NotNode notNode) {
|
||||||
|
Label labelFalse = new Label();
|
||||||
|
Label labelTrue = new Label();
|
||||||
|
|
||||||
|
notNode.expression.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(Opcodes.IFNE, labelFalse); // false if value is true (value != 0)
|
||||||
|
|
||||||
|
Label labelEndLogicalExpression = new Label();
|
||||||
|
|
||||||
|
methodVisitor.visitLabel(labelTrue);
|
||||||
|
methodVisitor.visitInsn(ICONST_1); // true
|
||||||
|
methodVisitor.visitJumpInsn(GOTO, labelEndLogicalExpression);
|
||||||
|
|
||||||
|
methodVisitor.visitLabel(labelFalse);
|
||||||
|
methodVisitor.visitInsn(ICONST_0); // false
|
||||||
|
|
||||||
|
methodVisitor.visitLabel(labelEndLogicalExpression);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(UnaryNode unaryNode) {
|
||||||
|
if (unaryNode.thisExp != null) {
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, 0); // this
|
||||||
|
} else if (unaryNode.identifier != null) {
|
||||||
|
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(unaryNode.identifier));
|
||||||
|
} else if (unaryNode.memberAccess != null) {
|
||||||
|
unaryNode.memberAccess.accept(this);
|
||||||
|
} else if (unaryNode.value != null) {
|
||||||
|
unaryNode.value.accept(this);
|
||||||
|
} else if (unaryNode.notExpression != null) {
|
||||||
|
unaryNode.notExpression.accept(this);
|
||||||
|
} else if (unaryNode.statement != null) {
|
||||||
|
unaryNode.statement.accept(this);
|
||||||
|
} else if (unaryNode.expression != null) {
|
||||||
|
unaryNode.expression.accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Statements
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(IfElseNode ifElseNode) {
|
||||||
|
Label elseLabel = new Label();
|
||||||
|
|
||||||
|
Label[] elseIfLabels = new Label[ifElseNode.elseIfStatements.size()];
|
||||||
|
for (int i = 0; i < ifElseNode.elseIfStatements.size(); i++) {
|
||||||
|
elseIfLabels[i] = new Label();
|
||||||
|
}
|
||||||
|
|
||||||
|
ifElseNode.ifStatement.expression.accept(this);
|
||||||
|
if (ifElseNode.elseIfStatements.isEmpty()) {
|
||||||
|
// No else if
|
||||||
|
methodVisitor.visitJumpInsn(IFEQ, elseLabel);
|
||||||
|
} else {
|
||||||
|
// else if statements
|
||||||
|
methodVisitor.visitJumpInsn(IFEQ, elseIfLabels[0]);
|
||||||
|
}
|
||||||
|
ifElseNode.ifStatement.block.accept(this); // accept if block
|
||||||
|
|
||||||
|
Label endLabel = new Label();
|
||||||
|
methodVisitor.visitJumpInsn(GOTO, endLabel);
|
||||||
|
|
||||||
|
for (int i = 0; i < ifElseNode.elseIfStatements.size(); i++) {
|
||||||
|
methodVisitor.visitLabel(elseIfLabels[i]);
|
||||||
|
ifElseNode.elseIfStatements.get(i).expression.accept(this);
|
||||||
|
if (i + 1 < elseIfLabels.length) {
|
||||||
|
// at least one more else if
|
||||||
|
methodVisitor.visitJumpInsn(IFEQ, elseIfLabels[i + 1]);
|
||||||
|
} else {
|
||||||
|
methodVisitor.visitJumpInsn(IFEQ, elseLabel);
|
||||||
|
}
|
||||||
|
ifElseNode.elseIfStatements.get(i).block.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(GOTO, endLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ifElseNode.elseStatement != null) {
|
||||||
|
methodVisitor.visitLabel(elseLabel);
|
||||||
|
ifElseNode.elseStatement.block.accept(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
methodVisitor.visitLabel(endLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(LocalVariableDeclarationNode localVariableDeclarationNode) {
|
||||||
|
if (localVariableDeclarationNode.expression != null) {
|
||||||
|
// Process expression
|
||||||
|
localVariableDeclarationNode.expression.accept(this);
|
||||||
|
// Store result of expression in variable
|
||||||
|
if (localVariables.contains(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 {
|
||||||
|
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 {
|
||||||
|
if (!localVariables.contains(localVariableDeclarationNode.identifier)) {
|
||||||
|
localVariables.add(localVariableDeclarationNode.identifier);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(AssignNode assignNode) {
|
||||||
|
// Process expression
|
||||||
|
if (assignNode.expression instanceof IncrementNode) {
|
||||||
|
IncrementNode incrementNode = (IncrementNode) assignNode.expression;
|
||||||
|
if (incrementNode.crementType.equals(CrementType.PREFIX)) { // ++i
|
||||||
|
methodVisitor.visitIincInsn(localVariables.indexOf(incrementNode.assignableExpression.identifier), 1);
|
||||||
|
assign(assignNode);
|
||||||
|
} else if (incrementNode.crementType.equals(CrementType.SUFFIX)) { // Suffix: i++
|
||||||
|
assign(assignNode);
|
||||||
|
methodVisitor.visitIincInsn(localVariables.indexOf(incrementNode.assignableExpression.identifier), 1);
|
||||||
|
}
|
||||||
|
} else if (assignNode.expression instanceof DecrementNode) {
|
||||||
|
DecrementNode decrementNode = (DecrementNode) assignNode.expression;
|
||||||
|
if (decrementNode.crementType.equals(CrementType.PREFIX)) {
|
||||||
|
methodVisitor.visitIincInsn(localVariables.indexOf(decrementNode.assignableExpression.identifier), -1);
|
||||||
|
assign(assignNode);
|
||||||
|
} else if (decrementNode.crementType.equals(CrementType.SUFFIX)) {
|
||||||
|
assign(assignNode);
|
||||||
|
methodVisitor.visitIincInsn(localVariables.indexOf(decrementNode.assignableExpression.identifier), 1);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
assignNode.expression.accept(this);
|
||||||
|
assign(assignNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assign(AssignNode assignNode) {
|
||||||
|
if (assignNode.assignable.memberAccess.thisExpr) {
|
||||||
|
assignField(assignNode);
|
||||||
|
} else {
|
||||||
|
assignLocalVar(assignNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assignLocalVar(AssignNode assignNode) {
|
||||||
|
if (assignNode.expression instanceof BaseType) {
|
||||||
|
methodVisitor.visitVarInsn(ISTORE, localVariables.indexOf(assignNode.assignable.identifier));
|
||||||
|
} else if (assignNode.expression instanceof ReferenceType) {
|
||||||
|
methodVisitor.visitVarInsn(ASTORE, localVariables.indexOf(assignNode.assignable.identifier));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assignField(AssignNode assignNode) {
|
||||||
|
if (assignNode.expression 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 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(NewDeclarationNode newDeclarationNode) {
|
||||||
|
methodVisitor.visitTypeInsn(NEW, newDeclarationNode.identifier);
|
||||||
|
methodVisitor.visitInsn(DUP);
|
||||||
|
List<ParameterNode> parameterNodes = new ArrayList<>();
|
||||||
|
for (IExpressionNode expressionNode : newDeclarationNode.expressions) {
|
||||||
|
expressionNode.accept(this);
|
||||||
|
parameterNodes.add(new ParameterNode(expressionNode.getType(), ""));
|
||||||
|
}
|
||||||
|
methodVisitor.visitMethodInsn(INVOKESPECIAL, newDeclarationNode.identifier, "<init>", mapper.generateMethodDescriptor(new BaseType(TypeEnum.VOID),parameterNodes), false);
|
||||||
|
localVariables.add(newDeclarationNode.identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(ValueNode valueNode) {
|
||||||
|
switch (valueNode.valueType) {
|
||||||
|
case INT_VALUE:
|
||||||
|
int intValue = Integer.parseInt(valueNode.value);
|
||||||
|
if (intValue >= Byte.MIN_VALUE && intValue <= Byte.MAX_VALUE) { // load int as byte
|
||||||
|
methodVisitor.visitIntInsn(BIPUSH, intValue);
|
||||||
|
} else if (intValue >= Short.MIN_VALUE && intValue <= Short.MAX_VALUE) { // load int as short
|
||||||
|
methodVisitor.visitIntInsn(SIPUSH, intValue);
|
||||||
|
} else { // load int as const
|
||||||
|
methodVisitor.visitLdcInsn(intValue);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case BOOLEAN_VALUE:
|
||||||
|
if (valueNode.value.equals("true")) {
|
||||||
|
methodVisitor.visitInsn(ICONST_1);
|
||||||
|
} else {
|
||||||
|
methodVisitor.visitInsn(ICONST_0);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case CHAR_VALUE:
|
||||||
|
char charValue = valueNode.value.charAt(0);
|
||||||
|
if (charValue <= Byte.MAX_VALUE) { // load char as byte
|
||||||
|
methodVisitor.visitIntInsn(BIPUSH, charValue);
|
||||||
|
} else if (charValue <= Short.MAX_VALUE) { // load char as short
|
||||||
|
methodVisitor.visitIntInsn(SIPUSH, charValue);
|
||||||
|
} else { // load char as const
|
||||||
|
methodVisitor.visitLdcInsn(charValue);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case NULL_VALUE:
|
||||||
|
methodVisitor.visitInsn(ACONST_NULL);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(ReturnNode returnNode) {
|
||||||
|
if (returnNode.voidReturn) { // Return nothing
|
||||||
|
methodVisitor.visitInsn(RETURN);
|
||||||
|
} else { // Return something
|
||||||
|
// Process expression
|
||||||
|
returnNode.expression.accept(this);
|
||||||
|
// Return result of expression
|
||||||
|
if (returnNode.expression.getType() instanceof BaseType) {
|
||||||
|
methodVisitor.visitInsn(IRETURN);
|
||||||
|
} else if (returnNode.expression.getType() instanceof ReferenceType) {
|
||||||
|
methodVisitor.visitInsn(ARETURN);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(WhileNode whileNode) {
|
||||||
|
Label loopLabel = new Label();
|
||||||
|
Label endOfLoopLabel = new Label();
|
||||||
|
|
||||||
|
methodVisitor.visitLabel(loopLabel);
|
||||||
|
// while loop
|
||||||
|
whileNode.expression.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(IFEQ, endOfLoopLabel); // if condition is false, jump out of loop
|
||||||
|
|
||||||
|
whileNode.block.accept(this);
|
||||||
|
methodVisitor.visitJumpInsn(GOTO, loopLabel);
|
||||||
|
|
||||||
|
methodVisitor.visitLabel(endOfLoopLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(ChainedMethodNode chainedMethodNode) {
|
||||||
|
// TODO: Erstmal abwarten
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(MethodCallNode methodCallNode) {
|
||||||
|
List<ParameterNode> parameterNodes = new ArrayList<>();
|
||||||
|
for(IExpressionNode expressionNode : methodCallNode.parameters) {
|
||||||
|
expressionNode.accept(this);
|
||||||
|
parameterNodes.add(new ParameterNode(expressionNode.getType(), ""));
|
||||||
|
}
|
||||||
|
// TODO: Klassenname und Returntype
|
||||||
|
//methodVisitor.visitMethodInsn(INVOKEVIRTUAL, classname, methodCallNode.identifier, mapper.generateMethodDescriptor(returntype, parameterNodes), false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,9 +1,56 @@
|
|||||||
package bytecode.visitor;
|
package bytecode.visitor;
|
||||||
|
|
||||||
|
import ast.expressions.binaryexpressions.*;
|
||||||
|
import ast.expressions.unaryexpressions.MemberAccessNode;
|
||||||
|
import ast.expressions.unaryexpressions.NotNode;
|
||||||
|
import ast.expressions.unaryexpressions.UnaryNode;
|
||||||
import ast.members.ConstructorNode;
|
import ast.members.ConstructorNode;
|
||||||
|
import ast.members.MainMethodNode;
|
||||||
import ast.members.MethodNode;
|
import ast.members.MethodNode;
|
||||||
|
import ast.statementexpressions.AssignNode;
|
||||||
|
import ast.statementexpressions.AssignableNode;
|
||||||
|
import ast.statementexpressions.NewDeclarationNode;
|
||||||
|
import ast.statementexpressions.crementexpressions.DecrementNode;
|
||||||
|
import ast.statementexpressions.crementexpressions.IncrementNode;
|
||||||
|
import ast.statementexpressions.methodcallstatementnexpressions.ChainedMethodNode;
|
||||||
|
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
||||||
|
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
|
||||||
|
import ast.statements.*;
|
||||||
|
import ast.type.ValueNode;
|
||||||
|
|
||||||
public interface MethodVisitor {
|
public interface MethodVisitor {
|
||||||
|
// members
|
||||||
void visit(ConstructorNode constructorNode);
|
void visit(ConstructorNode constructorNode);
|
||||||
void visit(MethodNode methodNode);
|
void visit(MethodNode methodNode);
|
||||||
|
void visit(MainMethodNode mainMethodNode);
|
||||||
|
|
||||||
|
// Binary expressions
|
||||||
|
void visit(BinaryNode binaryNode);
|
||||||
|
void visit(CalculationNode calculationNode);
|
||||||
|
void visit(DotNode dotNode);
|
||||||
|
void visit(DotSubstractionNode dotSubstractionNode);
|
||||||
|
void visit(NonCalculationNode nonCalculationNode);
|
||||||
|
|
||||||
|
// Unary expressions
|
||||||
|
void visit(MemberAccessNode memberAccessNode);
|
||||||
|
void visit(NotNode notExpressionNode);
|
||||||
|
void visit(UnaryNode unaryExpressionNode);
|
||||||
|
|
||||||
|
// statements
|
||||||
|
void visit(IfElseNode ifElseNode);
|
||||||
|
|
||||||
|
void visit(LocalVariableDeclarationNode localVariableDeclarationNode);
|
||||||
|
void visit(ReturnNode returnNode);
|
||||||
|
void visit(WhileNode whileNode);
|
||||||
|
|
||||||
|
// statement expression
|
||||||
|
void visit(ChainedMethodNode chainedMethodNode);
|
||||||
|
void visit(MethodCallNode methodCallNode);
|
||||||
|
|
||||||
|
void visit(AssignNode assignNode);
|
||||||
|
void visit(NewDeclarationNode newDeclarationNode);
|
||||||
|
|
||||||
|
// type
|
||||||
|
void visit(ValueNode valueNode);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -13,6 +13,7 @@ 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;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,13 +21,11 @@ import java.nio.file.Paths;
|
|||||||
* <p> <code> cd .\src\test\ </code>
|
* <p> <code> cd .\src\test\ </code>
|
||||||
* <p> <code> make clean compile-raupenpiler </code>
|
* <p> <code> make clean compile-raupenpiler </code>
|
||||||
* <p> Start Raupenpiler using jar:
|
* <p> Start Raupenpiler using jar:
|
||||||
* <p> <code> java.exe -jar path_to_jar\JavaCompiler-1.0-SNAPSHOT-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-SNAPSHOT-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 {
|
||||||
if (args.length == 2) {
|
if (args.length == 2) {
|
||||||
// args[0] is the input file path
|
// args[0] is the input file path
|
||||||
@@ -99,7 +98,11 @@ public class Main {
|
|||||||
|
|
||||||
/*------------------------- Bytecode Generator -> Bytecode -------------------------*/
|
/*------------------------- Bytecode Generator -> Bytecode -------------------------*/
|
||||||
// Use the ByteCodeGenerator to generate bytecode from the typed AST and output it to the specified directory
|
// Use the ByteCodeGenerator to generate bytecode from the typed AST and output it to the specified directory
|
||||||
ByteCodeGenerator byteCodeGenerator = new ByteCodeGenerator(outputDirectoryPath);
|
|
||||||
|
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;
|
assert typedAst != null;
|
||||||
byteCodeGenerator.visit((ProgramNode) typedAst);
|
byteCodeGenerator.visit((ProgramNode) typedAst);
|
||||||
// Log the bytecode generation
|
// Log the bytecode generation
|
||||||
|
@@ -16,18 +16,18 @@ import java.util.List;
|
|||||||
import java.util.logging.*;
|
import java.util.logging.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Beispiel für Logging-Arten:
|
* Beispiel für Logging-Arten:
|
||||||
<p><code>logger.severe("Schwerwiegender Fehler");</code>
|
* <p><code>logger.severe("Schwerwiegender Fehler");</code>
|
||||||
<p><code>logger.warning("Warnung");</code>
|
* <p><code>logger.warning("Warnung");</code>
|
||||||
<p><code>logger.info("Information");</code>
|
* <p><code>logger.info("Information");</code>
|
||||||
<p><code>logger.config("Konfigurationshinweis");</code>
|
* <p><code>logger.config("Konfigurationshinweis");</code>
|
||||||
<p><code>logger.fine("Fein");</code>
|
* <p><code>logger.fine("Fein");</code>
|
||||||
<p><code>logger.finer("Feiner");</code>
|
* <p><code>logger.finer("Feiner");</code>
|
||||||
<p><code>logger.finest("Am feinsten");</code>
|
* <p><code>logger.finest("Am feinsten");</code>
|
||||||
<p>You may toggle the logging level of the console and file handlers by
|
* <p>You may toggle the logging level of the console and file handlers by
|
||||||
changing the level ALL/OFF/etc. in the constructor.
|
* changing the level ALL/OFF/etc. in the constructor.
|
||||||
<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 {
|
public class RaupenLogger {
|
||||||
|
|
||||||
@@ -172,9 +172,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()) {
|
||||||
|
// logAST(child, indent + 1);
|
||||||
|
// }
|
||||||
|
|
||||||
// for (ASTNode child : node.) {
|
|
||||||
// printAST(child, indent + 1);
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -44,11 +44,32 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ASTNode visitClassDeclaration(SimpleJavaParser.ClassDeclarationContext ctx) {
|
public ASTNode visitClassDeclaration(SimpleJavaParser.ClassDeclarationContext ctx) {
|
||||||
ClassNode classNode = new ClassNode(ctx.AccessModifier().getText(), ctx.Identifier().getText());
|
ClassNode classNode;
|
||||||
for (SimpleJavaParser.MemberDeclarationContext member : ctx.memberDeclaration()) {
|
if(ctx.AccessModifier() != null){
|
||||||
classNode.addMember((MemberNode) visit(member));
|
classNode = new ClassNode(ctx.AccessModifier().getText(), ctx.Identifier().getText());
|
||||||
}
|
}
|
||||||
classNode.ensureConstructor();
|
else{
|
||||||
|
classNode = new ClassNode("public", ctx.Identifier().getText());
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean hasConstructor = false;
|
||||||
|
|
||||||
|
for (SimpleJavaParser.MemberDeclarationContext member : ctx.memberDeclaration()) {
|
||||||
|
MemberNode memberNode = (MemberNode) visit(member);
|
||||||
|
if(memberNode != null) {
|
||||||
|
if(memberNode instanceof ConstructorNode){
|
||||||
|
hasConstructor = true;
|
||||||
|
}
|
||||||
|
classNode.addMember(memberNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(!hasConstructor){
|
||||||
|
BlockNode blockNode = new BlockNode();
|
||||||
|
blockNode.addStatement(new ReturnNode(null));
|
||||||
|
classNode.members.addFirst(new ConstructorNode("public", ctx.Identifier().getText(), blockNode));
|
||||||
|
}
|
||||||
|
|
||||||
return classNode;
|
return classNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,37 +81,66 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
constructorNode.addParameter((ParameterNode) visit(parameter));
|
constructorNode.addParameter((ParameterNode) visit(parameter));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
constructorNode.block.addStatement(new ReturnNode(null));
|
||||||
return constructorNode;
|
return constructorNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ASTNode visitMethodDeclaration(SimpleJavaParser.MethodDeclarationContext ctx) {
|
public ASTNode visitMethodDeclaration(SimpleJavaParser.MethodDeclarationContext ctx) {
|
||||||
if(ctx.MainMethodDeclaration() != null) {
|
if(ctx.MainMethodDeclaration() != null) {
|
||||||
return new MainMethodNode((BlockNode) visit(ctx.blockStatement()));
|
MainMethodNode mainMethod = new MainMethodNode((BlockNode) visit(ctx.blockStatement()));
|
||||||
|
mainMethod.block.addStatement(new ReturnNode(null));
|
||||||
|
return mainMethod;
|
||||||
} else {
|
} else {
|
||||||
if(ctx.type() != null) {
|
if(ctx.type() != null) {
|
||||||
MethodNode methodNode = new MethodNode(ctx.AccessModifier().getText(), createTypeNode(ctx.type().getText()), false, ctx.Identifier().getText(), (BlockNode) visit(ctx.blockStatement()));
|
if(ctx.AccessModifier() != null) {
|
||||||
if(ctx.parameterList() != null) {
|
MethodNode methodNode = new MethodNode(ctx.AccessModifier().getText(), createTypeNode(ctx.type().getText()), false, ctx.Identifier().getText(), (BlockNode) visit(ctx.blockStatement()));
|
||||||
for(SimpleJavaParser.ParameterContext parameter : ctx.parameterList().parameter()) {
|
if(ctx.parameterList() != null) {
|
||||||
methodNode.addParameter((ParameterNode) visit(parameter));
|
for(SimpleJavaParser.ParameterContext parameter : ctx.parameterList().parameter()) {
|
||||||
|
methodNode.addParameter((ParameterNode) visit(parameter));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
return methodNode;
|
||||||
|
} else {
|
||||||
|
MethodNode methodNode = new MethodNode("public", createTypeNode(ctx.type().getText()), false, ctx.Identifier().getText(), (BlockNode) visit(ctx.blockStatement()));
|
||||||
|
if(ctx.parameterList() != null) {
|
||||||
|
for(SimpleJavaParser.ParameterContext parameter : ctx.parameterList().parameter()) {
|
||||||
|
methodNode.addParameter((ParameterNode) visit(parameter));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return methodNode;
|
||||||
}
|
}
|
||||||
return methodNode;
|
|
||||||
} else {
|
} else {
|
||||||
MethodNode methodNode = new MethodNode(ctx.AccessModifier().getText(), null, true, ctx.Identifier().getText(), (BlockNode) visit(ctx.blockStatement()));
|
if(ctx.AccessModifier() != null) {
|
||||||
if(ctx.parameterList() != null) {
|
MethodNode methodNode = new MethodNode(ctx.AccessModifier().getText(), null, true, ctx.Identifier().getText(), (BlockNode) visit(ctx.blockStatement()));
|
||||||
for(SimpleJavaParser.ParameterContext parameter : ctx.parameterList().parameter()) {
|
if(ctx.parameterList() != null) {
|
||||||
methodNode.addParameter((ParameterNode) visit(parameter));
|
for(SimpleJavaParser.ParameterContext parameter : ctx.parameterList().parameter()) {
|
||||||
|
methodNode.addParameter((ParameterNode) visit(parameter));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
methodNode.block.addStatement(new ReturnNode(null));
|
||||||
|
return methodNode;
|
||||||
|
} else {
|
||||||
|
MethodNode methodNode = new MethodNode("public", null, true, ctx.Identifier().getText(), (BlockNode) visit(ctx.blockStatement()));
|
||||||
|
if(ctx.parameterList() != null) {
|
||||||
|
for(SimpleJavaParser.ParameterContext parameter : ctx.parameterList().parameter()) {
|
||||||
|
methodNode.addParameter((ParameterNode) visit(parameter));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
methodNode.block.addStatement(new ReturnNode(null));
|
||||||
|
return methodNode;
|
||||||
}
|
}
|
||||||
return methodNode;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ASTNode visitFieldDeclaration(SimpleJavaParser.FieldDeclarationContext ctx) {
|
public ASTNode visitFieldDeclaration(SimpleJavaParser.FieldDeclarationContext ctx) {
|
||||||
return new FieldNode(new AccessModifierNode(ctx.AccessModifier().getText()), createTypeNode(ctx.type().getText()), ctx.Identifier().getText());
|
if(ctx.AccessModifier() != null) {
|
||||||
|
return new FieldNode(new AccessModifierNode(ctx.AccessModifier().getText()), createTypeNode(ctx.type().getText()), ctx.Identifier().getText());
|
||||||
|
} else {
|
||||||
|
return new FieldNode(new AccessModifierNode("public"), createTypeNode(ctx.type().getText()), ctx.Identifier().getText());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -133,16 +183,8 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
@Override
|
@Override
|
||||||
public ASTNode visitBlockStatement(SimpleJavaParser.BlockStatementContext ctx) {
|
public ASTNode visitBlockStatement(SimpleJavaParser.BlockStatementContext ctx) {
|
||||||
BlockNode blockNode = new BlockNode();
|
BlockNode blockNode = new BlockNode();
|
||||||
boolean hasReturnStatement = false;
|
|
||||||
for(SimpleJavaParser.StatementContext statement : ctx.statement()) {
|
for(SimpleJavaParser.StatementContext statement : ctx.statement()) {
|
||||||
IStatementNode statementNode = (IStatementNode) visit(statement);
|
blockNode.addStatement((IStatementNode) visit(statement));
|
||||||
if(statementNode instanceof ReturnNode) {
|
|
||||||
hasReturnStatement = true;
|
|
||||||
}
|
|
||||||
blockNode.addStatement(statementNode);
|
|
||||||
}
|
|
||||||
if(!hasReturnStatement) {
|
|
||||||
blockNode.addStatement(new ReturnNode(null));
|
|
||||||
}
|
}
|
||||||
return blockNode;
|
return blockNode;
|
||||||
}
|
}
|
||||||
@@ -188,10 +230,17 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
crement = (IStatementNode) visit(ctx.statementExpression(i));
|
crement = (IStatementNode) visit(ctx.statementExpression(i));
|
||||||
}
|
}
|
||||||
|
|
||||||
BlockNode forBlock = (BlockNode) visit(ctx.blockStatement());
|
BlockNode forBlock = new BlockNode();
|
||||||
|
|
||||||
|
BlockNode forStatements = (BlockNode) visit(ctx.blockStatement());
|
||||||
|
if(forStatements != null) {
|
||||||
|
forBlock.addStatement((IStatementNode) forStatements);
|
||||||
|
}
|
||||||
|
|
||||||
if(crement != null){
|
if(crement != null){
|
||||||
forBlock.addStatement((crement));
|
BlockNode forCrement = new BlockNode();
|
||||||
|
forCrement.addStatement((crement));
|
||||||
|
forBlock.addStatement(forCrement);
|
||||||
}
|
}
|
||||||
|
|
||||||
WhileNode While = new WhileNode(condition, forBlock);
|
WhileNode While = new WhileNode(condition, forBlock);
|
||||||
@@ -263,7 +312,12 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ASTNode visitMethodCall(SimpleJavaParser.MethodCallContext ctx) {
|
public ASTNode visitMethodCall(SimpleJavaParser.MethodCallContext ctx) {
|
||||||
MethodCallNode methodCallStatementExpressionNode = new MethodCallNode((TargetNode) visit(ctx.target()), ctx.Identifier().getText());
|
MethodCallNode methodCallStatementExpressionNode;
|
||||||
|
if(ctx.target() != null) {
|
||||||
|
methodCallStatementExpressionNode = new MethodCallNode((TargetNode) visit(ctx.target()), ctx.Identifier().getText());
|
||||||
|
} else {
|
||||||
|
methodCallStatementExpressionNode = new MethodCallNode(null, ctx.Identifier().getText());
|
||||||
|
}
|
||||||
for(SimpleJavaParser.ChainedMethodContext chainedMethod : ctx.chainedMethod()) {
|
for(SimpleJavaParser.ChainedMethodContext chainedMethod : ctx.chainedMethod()) {
|
||||||
methodCallStatementExpressionNode.addChainedMethod((ChainedMethodNode) visit(chainedMethod));
|
methodCallStatementExpressionNode.addChainedMethod((ChainedMethodNode) visit(chainedMethod));
|
||||||
}
|
}
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
// Generated from C:/Users/Maxi/Documents/DHBW/Compilerbau/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
// Generated from C:/Users/janni/Desktop/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/Maxi/Documents/DHBW/Compilerbau/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
// Generated from C:/Users/janni/Desktop/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/Maxi/Documents/DHBW/Compilerbau/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
// Generated from C:/Users/janni/Desktop/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/Maxi/Documents/DHBW/Compilerbau/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
// Generated from C:/Users/janni/Desktop/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;
|
||||||
|
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
// Generated from C:/Users/Maxi/Documents/DHBW/Compilerbau/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
// Generated from C:/Users/janni/Desktop/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.atn.*;
|
import org.antlr.v4.runtime.atn.*;
|
||||||
import org.antlr.v4.runtime.dfa.DFA;
|
import org.antlr.v4.runtime.dfa.DFA;
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
// Generated from C:/Users/Maxi/Documents/DHBW/Compilerbau/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
// Generated from C:/Users/janni/Desktop/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,7 +1,7 @@
|
|||||||
package semantic;
|
package semantic;
|
||||||
|
|
||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
import semantic.exeptions.AlreadyDeclearedException;
|
import semantic.exceptions.AlreadyDeclaredException;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Stack;
|
import java.util.Stack;
|
||||||
@@ -16,7 +16,7 @@ public class Scope {
|
|||||||
|
|
||||||
public void addLocalVar(String name, ITypeNode type) {
|
public void addLocalVar(String name, ITypeNode type) {
|
||||||
if (this.contains(name)) {
|
if (this.contains(name)) {
|
||||||
throw new AlreadyDeclearedException("Variable " + name + " already exists in this scope");
|
throw new AlreadyDeclaredException("Variable " + name + " already exists in this scope");
|
||||||
}
|
}
|
||||||
localVars.peek().put(name, type);
|
localVars.peek().put(name, type);
|
||||||
}
|
}
|
||||||
|
@@ -9,6 +9,7 @@ import java.util.Objects;
|
|||||||
import ast.*;
|
import ast.*;
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import ast.expressions.binaryexpressions.*;
|
import ast.expressions.binaryexpressions.*;
|
||||||
|
import ast.expressions.unaryexpressions.MemberAccessNode;
|
||||||
import ast.expressions.unaryexpressions.UnaryNode;
|
import ast.expressions.unaryexpressions.UnaryNode;
|
||||||
import ast.members.ConstructorNode;
|
import ast.members.ConstructorNode;
|
||||||
import ast.members.FieldNode;
|
import ast.members.FieldNode;
|
||||||
@@ -20,11 +21,18 @@ 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.statements.*;
|
import ast.statements.*;
|
||||||
|
import ast.type.AccessModifierNode;
|
||||||
|
import ast.type.EnumAccessModifierNode;
|
||||||
|
import ast.type.ValueNode;
|
||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
|
import com.sun.jdi.IntegerType;
|
||||||
|
import semantic.context.ClassContext;
|
||||||
import semantic.context.Context;
|
import semantic.context.Context;
|
||||||
import semantic.exeptions.*;
|
import semantic.exceptions.*;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
public class SemanticAnalyzer implements SemanticVisitor {
|
public class SemanticAnalyzer implements SemanticVisitor {
|
||||||
@@ -116,7 +124,7 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
if (Objects.equals(otherMethod, methodNode))
|
if (Objects.equals(otherMethod, methodNode))
|
||||||
break;
|
break;
|
||||||
if (otherMethod.isSame(methodNode)) {
|
if (otherMethod.isSame(methodNode)) {
|
||||||
errors.add(new AlreadyDeclearedException(
|
errors.add(new AlreadyDeclaredException(
|
||||||
"Method " + methodNode.getIdentifier() + " is already defined in class "
|
"Method " + methodNode.getIdentifier() + " is already defined in class "
|
||||||
+ currentClass.identifier));
|
+ currentClass.identifier));
|
||||||
valid = false;
|
valid = false;
|
||||||
@@ -129,31 +137,25 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
valid = valid && result.isValid();
|
valid = valid && result.isValid();
|
||||||
try {
|
try {
|
||||||
currentScope.addLocalVar(parameter.identifier, parameter.type);
|
currentScope.addLocalVar(parameter.identifier, parameter.type);
|
||||||
} catch (AlreadyDeclearedException e) {
|
} catch (AlreadyDeclaredException e) {
|
||||||
errors.add(new AlreadyDeclearedException(parameter.identifier));
|
errors.add(new AlreadyDeclaredException(parameter.identifier));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
// Check if this method is already declared
|
|
||||||
|
|
||||||
currentMethodReturnType = methodNode.getType();
|
currentMethodReturnType = methodNode.getType();
|
||||||
currentNullType = currentMethodReturnType; // Solange nicht in einem Assign oder Methoden-Aufruf dieser Typ
|
currentNullType = currentMethodReturnType;
|
||||||
|
|
||||||
ITypeNode resultType = new BaseType(TypeEnum.VOID);
|
|
||||||
|
|
||||||
// gesetzt ist, ist dieser der Rückgabewert der Methode
|
|
||||||
var result = methodNode.block.accept(this);
|
var result = methodNode.block.accept(this);
|
||||||
valid = valid && result.isValid();
|
valid = valid && result.isValid();
|
||||||
currentScope.popScope();
|
currentScope.popScope();
|
||||||
resultType = result.getType();
|
ITypeNode resultType = result.getType();
|
||||||
|
|
||||||
if (resultType == null) {
|
if (resultType == null) {
|
||||||
resultType = new BaseType(TypeEnum.VOID);
|
resultType = new BaseType(TypeEnum.VOID);
|
||||||
}
|
}
|
||||||
if (!resultType.equals(methodNode.getType())) {
|
if (methodNode.getType() == null) {
|
||||||
errors.add(new TypeMismatchException("Method-Declaration " + methodNode.getIdentifier() + " with type "
|
methodNode.setType(new BaseType(TypeEnum.VOID));
|
||||||
+ methodNode.getType() + " has at least one Mismatching return Type:"));
|
|
||||||
valid = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return new TypeCheckResult(valid, resultType);
|
return new TypeCheckResult(valid, resultType);
|
||||||
@@ -163,54 +165,83 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
|
|
||||||
@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 AlreadyDeclearedException("Already declared " + toCheck.identifier));
|
errors.add(new AlreadyDeclaredException("Already declared " + toCheck.identifier));
|
||||||
return new TypeCheckResult(false, null);
|
return new TypeCheckResult(false, null);
|
||||||
} else {
|
} else {
|
||||||
currentFields.put(toCheck.identifier, toCheck.type);
|
currentFields.put(toCheck.identifier, toCheck.type);
|
||||||
}
|
}
|
||||||
return new TypeCheckResult(true, null);
|
return new TypeCheckResult(true, null);
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(IfNode toCheck) {
|
public TypeCheckResult analyze(IfNode toCheck) {
|
||||||
|
toCheck.block.accept(this);
|
||||||
|
|
||||||
|
var resultExpression = toCheck.expression.accept(this);
|
||||||
|
if (resultExpression.isValid()) {
|
||||||
|
if (!resultExpression.getType().equals(new BaseType(TypeEnum.BOOL))) {
|
||||||
|
errors.add(new TypeMismatchException("Expression must be Boolean"));
|
||||||
|
return new TypeCheckResult(false, new BaseType(TypeEnum.VOID));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return new TypeCheckResult(true, null);
|
return new TypeCheckResult(true, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(ReturnNode toCheck) {
|
public TypeCheckResult analyze(ReturnNode toCheck) {
|
||||||
|
if (toCheck.expression != null) {
|
||||||
if(toCheck.expression != null){
|
|
||||||
var result = toCheck.expression.accept(this);
|
var result = toCheck.expression.accept(this);
|
||||||
|
if (result.isValid()) {
|
||||||
|
if (!result.getType().equals(currentMethodReturnType)) {
|
||||||
|
errors.add(new TypeMismatchException("Mismatched return Type from method"));
|
||||||
|
}
|
||||||
|
}
|
||||||
return new TypeCheckResult(true, result.getType());
|
return new TypeCheckResult(true, result.getType());
|
||||||
} else {
|
} else if (toCheck.voidReturn) {
|
||||||
return new TypeCheckResult(false, null);
|
return new TypeCheckResult(true, new BaseType(TypeEnum.VOID));
|
||||||
}
|
}
|
||||||
|
return new TypeCheckResult(true, null);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(WhileNode toCheck) {
|
public TypeCheckResult analyze(WhileNode toCheck) {
|
||||||
return null;
|
var expResult = toCheck.expression.accept(this);
|
||||||
|
var blockRes = toCheck.block.accept(this);
|
||||||
|
return new TypeCheckResult(expResult.isValid() && blockRes.isValid(), blockRes.getType());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(ParameterNode toCheck) {
|
public TypeCheckResult analyze(ParameterNode toCheck) {
|
||||||
|
return new TypeCheckResult(true, toCheck.type);
|
||||||
|
|
||||||
return new TypeCheckResult(true, null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(BlockNode blockNode) {
|
public TypeCheckResult analyze(BlockNode blockNode) {
|
||||||
ITypeNode blockReturnType = null;
|
ITypeNode blockReturnType = null;
|
||||||
|
if (blockNode.statements.isEmpty()) {
|
||||||
|
return new TypeCheckResult(true, null);
|
||||||
|
}
|
||||||
for (IStatementNode statementNode : blockNode.statements) {
|
for (IStatementNode statementNode : blockNode.statements) {
|
||||||
var result = statementNode.accept(this);
|
var result = statementNode.accept(this);
|
||||||
if(result.getType() != null){
|
if(!(statementNode instanceof IncrementNode) && !(statementNode instanceof DecrementNode)){
|
||||||
if(blockReturnType == null){
|
if (result.getType() != null) {
|
||||||
blockReturnType = result.getType();
|
if (blockReturnType == null) {
|
||||||
} else {
|
blockReturnType = result.getType();
|
||||||
errors.add(new MultipleReturnTypes("There are multiple Return types"));
|
} else {
|
||||||
|
if (!blockReturnType.equals(result.getType())) {
|
||||||
|
errors.add(new MultipleReturnTypes("There are multiple Return types"));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -219,20 +250,31 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(AssignableNode toCheck) {
|
public TypeCheckResult analyze(AssignableNode toCheck) {
|
||||||
return new TypeCheckResult(true, currentFields.get(toCheck.identifier));
|
|
||||||
|
if (toCheck.memberAccess != null) {
|
||||||
|
var result = toCheck.memberAccess.accept(this);
|
||||||
|
toCheck.setTypeNode(result.getType());
|
||||||
|
return result;
|
||||||
|
} else {
|
||||||
|
if (currentFields.get(toCheck.identifier) != null) {
|
||||||
|
var type = currentFields.get(toCheck.identifier);
|
||||||
|
toCheck.setTypeNode(type);
|
||||||
|
return new TypeCheckResult(true, type);
|
||||||
|
} else if (currentScope.getLocalVar(toCheck.identifier) != null) {
|
||||||
|
var type = currentScope.getLocalVar(toCheck.identifier);
|
||||||
|
return new TypeCheckResult(true, type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TypeCheckResult(true, null);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(ElseNode toCheck) {
|
public TypeCheckResult analyze(ElseNode toCheck) {
|
||||||
return null;
|
return toCheck.block.accept(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*@Override
|
|
||||||
public TypeCheckResult analyze(ForNode toCheck) {
|
|
||||||
return null;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(AssignNode toCheck) {
|
public TypeCheckResult analyze(AssignNode toCheck) {
|
||||||
AssignableNode assignable = toCheck.assignable;
|
AssignableNode assignable = toCheck.assignable;
|
||||||
@@ -242,13 +284,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;
|
||||||
@@ -258,33 +293,70 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
currentNullType = lResult.getType();
|
currentNullType = lResult.getType();
|
||||||
var rResult = rExpression.accept(this);
|
var rResult = rExpression.accept(this);
|
||||||
|
|
||||||
if (!Objects.equals(currentScope.getLocalVar(toCheck.assignable.identifier), rExpression.getType())) {
|
if (!Objects.equals(lResult.getType(), rResult.getType())) {
|
||||||
errors.add(new TypeMismatchException(
|
errors.add(new TypeMismatchException(
|
||||||
"Mismatch types in Assign-Statement: cannot convert from \"" + lResult.getType() + "\" to \""
|
"Mismatch types in Assign-Statement: cannot convert from \"" + lResult.getType() + "\" to \""
|
||||||
+ rResult.getType() + "\""));
|
+ rResult.getType() + "\""));
|
||||||
valid = false;
|
valid = false;
|
||||||
}
|
}
|
||||||
// else {
|
|
||||||
// toCheck.setType(assignable.getType());
|
|
||||||
// }
|
|
||||||
valid = valid && lResult.isValid() && rResult.isValid();
|
valid = valid && lResult.isValid() && rResult.isValid();
|
||||||
currentNullType = null;
|
currentNullType = null;
|
||||||
return new TypeCheckResult(valid, null); // return type is null to get the return type sufficently
|
return new TypeCheckResult(valid, null); // return type is null to get the return type sufficently
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(DecrementNode toCheck) {
|
public TypeCheckResult analyze(DecrementNode decrementNode) {
|
||||||
return null;
|
return decrementNode.assignableExpression.accept(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(IfElseNode toCheck) {
|
public TypeCheckResult analyze(IfElseNode toCheck) {
|
||||||
return new TypeCheckResult(true, null);
|
var resultIf = toCheck.ifStatement.accept(this);
|
||||||
|
var resultElse = toCheck.elseStatement.accept(this);
|
||||||
|
|
||||||
|
return new TypeCheckResult(resultIf.isValid() && resultElse.isValid(), new BaseType(TypeEnum.VOID));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(MethodCallNode toCheck) {
|
public TypeCheckResult analyze(MethodCallNode toCheck) {
|
||||||
return null;
|
|
||||||
|
if (toCheck.target.identifier != null) {
|
||||||
|
var targetType = currentScope.getLocalVar(toCheck.target.identifier);
|
||||||
|
if (targetType == null) {
|
||||||
|
targetType = currentFields.get(toCheck.target.identifier);
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
var result = toCheck.target.accept(this);
|
||||||
|
if (result.getType() instanceof ReferenceType reference) {
|
||||||
|
return new TypeCheckResult(true, getTypeFromMethod(toCheck, reference));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new TypeCheckResult(false, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -295,6 +367,9 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
TypeCheckResult result = localVarDecl.expression.accept(this);
|
TypeCheckResult result = localVarDecl.expression.accept(this);
|
||||||
|
|
||||||
var resultType = localVarDecl.expression.getType();
|
var resultType = localVarDecl.expression.getType();
|
||||||
|
if (result.getType() != null) {
|
||||||
|
resultType = result.getType();
|
||||||
|
}
|
||||||
valid = result.isValid() && valid;
|
valid = result.isValid() && valid;
|
||||||
|
|
||||||
if (!Objects.equals(resultType, localVarDecl.type)) {
|
if (!Objects.equals(resultType, localVarDecl.type)) {
|
||||||
@@ -316,12 +391,17 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(NewDeclarationNode toCheck) {
|
public TypeCheckResult analyze(NewDeclarationNode toCheck) {
|
||||||
|
|
||||||
|
if (context.containsClass(toCheck.identifier)) {
|
||||||
|
return new TypeCheckResult(true, new ReferenceType(toCheck.identifier));
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(IncrementNode toCheck) {
|
public TypeCheckResult analyze(IncrementNode toCheck) {
|
||||||
return null;
|
return toCheck.assignableExpression.accept(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -332,38 +412,256 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(CalculationNode calcNode) {
|
public TypeCheckResult analyze(CalculationNode calcNode) {
|
||||||
if (calcNode.calculationExpression != null) {
|
if (calcNode.calculationExpression != null) {
|
||||||
calcNode.calculationExpression.accept(this);
|
var calcRes = calcNode.calculationExpression.accept(this);
|
||||||
|
if (calcNode.dotExpression != null) {
|
||||||
|
var dotRes = calcNode.dotExpression.accept(this);
|
||||||
|
|
||||||
|
switch (calcNode.operator) {
|
||||||
|
case PLUS, MINUS:
|
||||||
|
if (calcRes.getType() instanceof BaseType calcType && dotRes.getType() instanceof BaseType dotType &&
|
||||||
|
calcType.getTypeEnum().equals(TypeEnum.INT) && dotType.getTypeEnum().equals(TypeEnum.INT)) {
|
||||||
|
return new TypeCheckResult(true, new BaseType(TypeEnum.INT));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
return new TypeCheckResult(calcRes.isValid(), calcRes.getType());
|
||||||
|
}
|
||||||
|
} else if (calcNode.dotExpression != null) {
|
||||||
|
var dotRes = calcNode.dotExpression.accept(this);
|
||||||
|
return new TypeCheckResult(dotRes.isValid(), dotRes.getType());
|
||||||
|
}
|
||||||
|
return new TypeCheckResult(false, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public TypeCheckResult analyze(DotNode toCheck) {
|
||||||
|
if (toCheck.dotSubstractionExpression != null) {
|
||||||
|
return toCheck.dotSubstractionExpression.accept(this);
|
||||||
|
}
|
||||||
|
return new TypeCheckResult(false, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public TypeCheckResult analyze(DotSubstractionNode toCheck) {
|
||||||
|
if (toCheck.value != null) {
|
||||||
|
return toCheck.value.accept(this);
|
||||||
|
} else if (toCheck.memberAccess != null) {
|
||||||
|
return toCheck.memberAccess.accept(this);
|
||||||
|
} else if (toCheck.methodCall != null) {
|
||||||
|
return toCheck.methodCall.accept(this);
|
||||||
|
} else if (toCheck.identifier != null) {
|
||||||
|
if (currentScope.contains(toCheck.identifier)) {
|
||||||
|
return new TypeCheckResult(true, currentScope.getLocalVar(toCheck.identifier));
|
||||||
|
} else if (currentFields.get(toCheck.identifier) != null) {
|
||||||
|
return new TypeCheckResult(true, currentFields.get(toCheck.identifier));
|
||||||
|
}
|
||||||
|
} else if (toCheck.calculationExpression != null) {
|
||||||
|
return toCheck.calculationExpression.accept(this);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(DotNode toCheck) {
|
public TypeCheckResult analyze(NonCalculationNode nonCalculationNode) {
|
||||||
return null;
|
var expResult = nonCalculationNode.expression.accept(this);
|
||||||
}
|
var unaryResult = nonCalculationNode.unaryExpression.accept(this);
|
||||||
|
|
||||||
@Override
|
switch (nonCalculationNode.operator) {
|
||||||
public TypeCheckResult analyze(DotSubstractionNode toCheck) {
|
case LESS, LESS_EQUAL, GREATER, GREATER_EQUAL:
|
||||||
return null;
|
if (expResult.getType() instanceof BaseType expResultType && expResultType.getTypeEnum().equals(TypeEnum.INT) &&
|
||||||
}
|
unaryResult.getType() instanceof BaseType unaryResultType && unaryResultType.getTypeEnum().equals(TypeEnum.INT)) {
|
||||||
|
return new TypeCheckResult(true, new BaseType(TypeEnum.BOOL));
|
||||||
|
} else {
|
||||||
|
errors.add(new TypeMismatchException("Both types must be Integer"));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case OR, AND:
|
||||||
|
if (expResult.getType() instanceof BaseType expResultType && expResultType.getTypeEnum().equals(TypeEnum.INT) &&
|
||||||
|
unaryResult.getType() instanceof BaseType unaryResultType && unaryResultType.getTypeEnum().equals(TypeEnum.INT)) {
|
||||||
|
return new TypeCheckResult(true, new BaseType(TypeEnum.BOOL));
|
||||||
|
} else {
|
||||||
|
errors.add(new TypeMismatchException("Both types must be Boolean"));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case EQUAL, NOT_EQUAL:
|
||||||
|
if (expResult.getType() instanceof BaseType expResultType && unaryResult.getType() instanceof BaseType unaryResultType
|
||||||
|
&& Objects.equals(expResultType, unaryResultType)) {
|
||||||
|
return new TypeCheckResult(true, new BaseType(TypeEnum.BOOL));
|
||||||
|
} else {
|
||||||
|
errors.add(new TypeMismatchException("Both types must be the same"));
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
}
|
||||||
public TypeCheckResult analyze(NonCalculationNode toCheck) {
|
return new TypeCheckResult(false, null);
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(UnaryNode unary) {
|
public TypeCheckResult analyze(UnaryNode unary) {
|
||||||
var valid = true;
|
var valid = true;
|
||||||
|
|
||||||
if (currentScope.contains(unary.identifier)) {
|
if (unary.identifier != null) {
|
||||||
return new TypeCheckResult(valid, currentScope.getLocalVar(unary.identifier));
|
if (currentScope.contains(unary.identifier)) {
|
||||||
} else if(currentFields.get(unary.identifier) != null) {
|
return new TypeCheckResult(valid, currentScope.getLocalVar(unary.identifier));
|
||||||
return new TypeCheckResult(valid, currentFields.get(unary.identifier));
|
} else if (currentFields.get(unary.identifier) != null) {
|
||||||
} else {
|
return new TypeCheckResult(valid, currentFields.get(unary.identifier));
|
||||||
errors.add(new NotDeclearedException("Var is not Decleared"));
|
} else if (unary.statement != null) {
|
||||||
|
var result = unary.statement.accept(this);
|
||||||
|
unary.setType(result.getType());
|
||||||
|
return result;
|
||||||
|
} else {
|
||||||
|
errors.add(new NotDeclaredException("Var is not Declared"));
|
||||||
|
}
|
||||||
|
} else if (unary.statement != null) {
|
||||||
|
var result = unary.statement.accept(this);
|
||||||
|
return new TypeCheckResult(result.isValid(), result.getType());
|
||||||
|
} else if (unary.value != null) {
|
||||||
|
var result = unary.value.accept(this);
|
||||||
|
return new TypeCheckResult(result.isValid(), result.getType());
|
||||||
|
} else if (unary.memberAccess != null) {
|
||||||
|
var result = unary.memberAccess.accept(this);
|
||||||
|
return new TypeCheckResult(result.isValid(), result.getType());
|
||||||
|
} else if (unary.expression != null) {
|
||||||
|
var result = unary.expression.accept(this);
|
||||||
|
return new TypeCheckResult(result.isValid(), result.getType());
|
||||||
}
|
}
|
||||||
return new TypeCheckResult(valid, null);
|
|
||||||
|
return new TypeCheckResult(false, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public TypeCheckResult analyze(MemberAccessNode memberAccessNode) {
|
||||||
|
|
||||||
|
ITypeNode currentType = null;
|
||||||
|
|
||||||
|
for (String s : memberAccessNode.identifiers) {
|
||||||
|
if (currentType == null) {
|
||||||
|
if (currentScope.getLocalVar(s) != null) {
|
||||||
|
currentType = currentScope.getLocalVar(s);
|
||||||
|
|
||||||
|
} else if (currentFields.get(s) != null) {
|
||||||
|
currentType = currentFields.get(s);
|
||||||
|
} else {
|
||||||
|
errors.add(new NotDeclaredException(s + "Not Declared"));
|
||||||
|
return new TypeCheckResult(false, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
if (currentType instanceof ReferenceType reference) {
|
||||||
|
var currentTypeClass = context.getClass(reference.getIdentifier());
|
||||||
|
|
||||||
|
var currentField = currentTypeClass.getField(s);
|
||||||
|
if (currentField.getAccessModifier().accessType == EnumAccessModifierNode.PUBLIC) {
|
||||||
|
currentType = currentField.getType();
|
||||||
|
} else {
|
||||||
|
errors.add(new NotVisibleException("This field is not visible"));
|
||||||
|
return new TypeCheckResult(false, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TypeCheckResult(true, currentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public TypeCheckResult analyze(TargetNode targetNode) {
|
||||||
|
|
||||||
|
if (targetNode.memberAccess != null) {
|
||||||
|
return targetNode.memberAccess.accept(this);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public TypeCheckResult analyze(ValueNode valueNode) {
|
||||||
|
|
||||||
|
switch (valueNode.valueType) {
|
||||||
|
case INT_VALUE -> {
|
||||||
|
return new TypeCheckResult(true, new BaseType(TypeEnum.INT));
|
||||||
|
}
|
||||||
|
case CHAR_VALUE -> {
|
||||||
|
return new TypeCheckResult(true, new BaseType(TypeEnum.CHAR));
|
||||||
|
}
|
||||||
|
case BOOLEAN_VALUE -> {
|
||||||
|
return new TypeCheckResult(true, new BaseType(TypeEnum.BOOL));
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
return new TypeCheckResult(false, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ITypeNode getTypeFromMethod(MethodCallNode toCheck, ReferenceType reference) {
|
||||||
|
var classContext = context.getClass(reference.getIdentifier());
|
||||||
|
|
||||||
|
if (classContext == null) {
|
||||||
|
errors.add(new NotDeclaredException(toCheck.target.identifier + "is not Defined"));
|
||||||
|
} else {
|
||||||
|
var methods = classContext.getMethods();
|
||||||
|
for (var method : methods) {
|
||||||
|
if (toCheck.identifier.equals(method.getIdentifier())) {
|
||||||
|
if (method.getParameters().size() == toCheck.parameters.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.parameters.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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
errors.add(new WrongOverloading("No Method found with this parameters"));
|
||||||
|
}
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@@ -2,6 +2,7 @@ package semantic;
|
|||||||
|
|
||||||
import ast.*;
|
import ast.*;
|
||||||
import ast.expressions.binaryexpressions.*;
|
import ast.expressions.binaryexpressions.*;
|
||||||
|
import ast.expressions.unaryexpressions.MemberAccessNode;
|
||||||
import ast.expressions.unaryexpressions.UnaryNode;
|
import ast.expressions.unaryexpressions.UnaryNode;
|
||||||
import ast.members.*;
|
import ast.members.*;
|
||||||
import ast.parameters.ParameterNode;
|
import ast.parameters.ParameterNode;
|
||||||
@@ -11,7 +12,9 @@ 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.MethodCallNode;
|
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
||||||
|
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
|
||||||
import ast.statements.*;
|
import ast.statements.*;
|
||||||
|
import ast.type.ValueNode;
|
||||||
import typechecker.TypeCheckResult;
|
import typechecker.TypeCheckResult;
|
||||||
|
|
||||||
public interface SemanticVisitor {
|
public interface SemanticVisitor {
|
||||||
@@ -38,8 +41,6 @@ public interface SemanticVisitor {
|
|||||||
|
|
||||||
TypeCheckResult analyze(ElseNode toCheck);
|
TypeCheckResult analyze(ElseNode toCheck);
|
||||||
|
|
||||||
//TypeCheckResult analyze(ForNode toCheck);
|
|
||||||
|
|
||||||
TypeCheckResult analyze(AssignNode toCheck);
|
TypeCheckResult analyze(AssignNode toCheck);
|
||||||
|
|
||||||
TypeCheckResult analyze(DecrementNode toCheck);
|
TypeCheckResult analyze(DecrementNode toCheck);
|
||||||
@@ -66,4 +67,10 @@ public interface SemanticVisitor {
|
|||||||
|
|
||||||
TypeCheckResult analyze(UnaryNode toCheck);
|
TypeCheckResult analyze(UnaryNode toCheck);
|
||||||
|
|
||||||
|
TypeCheckResult analyze(MemberAccessNode toCheck);
|
||||||
|
|
||||||
|
TypeCheckResult analyze(TargetNode toCheck);
|
||||||
|
|
||||||
|
TypeCheckResult analyze(ValueNode toCheck);
|
||||||
|
|
||||||
}
|
}
|
@@ -2,11 +2,15 @@ package semantic.context;
|
|||||||
|
|
||||||
import ast.ClassNode;
|
import ast.ClassNode;
|
||||||
import ast.members.FieldNode;
|
import ast.members.FieldNode;
|
||||||
|
import ast.members.MethodNode;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
|
||||||
public class ClassContext {
|
public class ClassContext {
|
||||||
|
|
||||||
private HashMap<String, FieldContext> fields;
|
private HashMap<String, FieldContext> fields;
|
||||||
|
private ArrayList<MethodNode> methods = new ArrayList<>();
|
||||||
|
|
||||||
public ClassContext(ClassNode classNode) {
|
public ClassContext(ClassNode classNode) {
|
||||||
|
|
||||||
@@ -15,6 +19,8 @@ public class ClassContext {
|
|||||||
classNode.members.forEach(member -> {
|
classNode.members.forEach(member -> {
|
||||||
if(member instanceof FieldNode fieldNode) {
|
if(member instanceof FieldNode fieldNode) {
|
||||||
fields.put(fieldNode.identifier, new FieldContext(fieldNode));
|
fields.put(fieldNode.identifier, new FieldContext(fieldNode));
|
||||||
|
}else if(member instanceof MethodNode methodNode) {
|
||||||
|
methods.add(methodNode);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -24,4 +30,8 @@ public class ClassContext {
|
|||||||
return fields.get(name);
|
return fields.get(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ArrayList<MethodNode> getMethods() {
|
||||||
|
return methods;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -21,4 +21,12 @@ public class Context {
|
|||||||
return classes.get(identifier);
|
return classes.get(identifier);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public HashMap<String, ClassContext> getClasses() {
|
||||||
|
return classes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean containsClass(String identifier) {
|
||||||
|
return classes.containsKey(identifier);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -18,4 +18,8 @@ public class FieldContext {
|
|||||||
return type;
|
return type;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public AccessModifierNode getAccessModifier() {
|
||||||
|
return accessModifier;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -0,0 +1,9 @@
|
|||||||
|
package semantic.exceptions;
|
||||||
|
|
||||||
|
public class AlreadyDeclaredException extends RuntimeException {
|
||||||
|
|
||||||
|
public AlreadyDeclaredException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@@ -1,4 +1,4 @@
|
|||||||
package semantic.exeptions;
|
package semantic.exceptions;
|
||||||
|
|
||||||
public class AlreadyDefinedException extends RuntimeException {
|
public class AlreadyDefinedException extends RuntimeException {
|
||||||
|
|
@@ -1,4 +1,4 @@
|
|||||||
package semantic.exeptions;
|
package semantic.exceptions;
|
||||||
|
|
||||||
public class MultipleReturnTypes extends RuntimeException {
|
public class MultipleReturnTypes extends RuntimeException {
|
||||||
|
|
@@ -0,0 +1,9 @@
|
|||||||
|
package semantic.exceptions;
|
||||||
|
|
||||||
|
public class NotDeclaredException extends RuntimeException {
|
||||||
|
|
||||||
|
public NotDeclaredException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@@ -0,0 +1,9 @@
|
|||||||
|
package semantic.exceptions;
|
||||||
|
|
||||||
|
public class NotVisibleException extends RuntimeException {
|
||||||
|
|
||||||
|
public NotVisibleException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@@ -1,4 +1,4 @@
|
|||||||
package semantic.exeptions;
|
package semantic.exceptions;
|
||||||
|
|
||||||
public class TypeMismatchException extends RuntimeException {
|
public class TypeMismatchException extends RuntimeException {
|
||||||
|
|
9
src/main/java/semantic/exceptions/UnknownException.java
Normal file
9
src/main/java/semantic/exceptions/UnknownException.java
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
package semantic.exceptions;
|
||||||
|
|
||||||
|
public class UnknownException extends RuntimeException {
|
||||||
|
|
||||||
|
public UnknownException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
9
src/main/java/semantic/exceptions/WrongOverloading.java
Normal file
9
src/main/java/semantic/exceptions/WrongOverloading.java
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
package semantic.exceptions;
|
||||||
|
|
||||||
|
public class WrongOverloading extends RuntimeException {
|
||||||
|
|
||||||
|
public WrongOverloading(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@@ -1,9 +0,0 @@
|
|||||||
package semantic.exeptions;
|
|
||||||
|
|
||||||
public class AlreadyDeclearedException extends RuntimeException {
|
|
||||||
|
|
||||||
public AlreadyDeclearedException(String message) {
|
|
||||||
super(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@@ -1,9 +0,0 @@
|
|||||||
package semantic.exeptions;
|
|
||||||
|
|
||||||
public class NotDeclearedException extends RuntimeException {
|
|
||||||
|
|
||||||
public NotDeclearedException(String message) {
|
|
||||||
super(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@@ -9,21 +9,37 @@ compile-javac:
|
|||||||
|
|
||||||
compile-raupenpiler:
|
compile-raupenpiler:
|
||||||
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
|
||||||
|
|
||||||
test: test-javac test-raupenpiler
|
test: compile-javac compile-raupenpiler test-javac test-raupenpiler
|
||||||
|
|
||||||
test-javac:
|
test-javac:
|
||||||
#compile-javac
|
# gleich wie bei raupenpiler, kann ich ohne funktionierenden Compiler nicht testen
|
||||||
#java -cp .\resources\output\javac CompilerInput
|
|
||||||
|
|
||||||
test-raupenpiler:
|
test-raupenpiler:
|
||||||
#java -cp .\resources\output\raupenpiler CompilerInput
|
# 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
|
||||||
|
rm -f ../main/resources/output/*.class
|
||||||
|
rm -f ../main/resources/output/*.jar
|
||||||
rm -f ./resources/output/javac/*.class
|
rm -f ./resources/output/javac/*.class
|
||||||
rm -f ./resources/output/raupenpiler/*.class
|
rm -f ./resources/output/raupenpiler/*.class
|
||||||
rm -f ./java/*.class
|
# clean logs
|
||||||
rm -f ../main/resources/output/*.class
|
|
||||||
rm -f ../main/resources/logs/*.log
|
rm -f ../main/resources/logs/*.log
|
||||||
|
# clean test/java/main folders from .class files for End-to-End tests
|
||||||
|
rm -f ./java/main/*.class
|
||||||
|
# clean javac output from combinedFeatureTests
|
||||||
|
rm -f ./resources/input/combinedFeatureTests/*.class
|
||||||
|
rm -f ./resources/input/singleFeatureTests/*.class
|
||||||
|
rm -f ./resources/input/typedAstFeatureTests/*.class
|
||||||
|
|
||||||
|
@@ -78,8 +78,8 @@ Compiled Classfile
|
|||||||
|
|
||||||
wenn beides erfolgreich
|
wenn beides erfolgreich
|
||||||
|
|
||||||
- Ergebnis vom eigenen Compiler mithilfe von main.TestCompilerOutput ausführen
|
- Ergebnis vom eigenen Compiler mithilfe von main.EndToEndTester ausführen
|
||||||
- (Ergebnis von javac mithilfe von main.TestCompilerOutput ausführen)
|
- (Ergebnis von javac mithilfe von main.EndToEndTester ausführen)
|
||||||
|
|
||||||
### Andis Tipps:
|
### Andis Tipps:
|
||||||
|
|
||||||
@@ -89,4 +89,5 @@ wenn beides erfolgreich
|
|||||||
- mvn package
|
- mvn package
|
||||||
- javac tester // tester compilen
|
- javac tester // tester compilen
|
||||||
- java tester // tester ausführen
|
- java tester // tester ausführen
|
||||||
- -> tester ist in unserem Fall main.TestCompilerOutput.java
|
- -> tester ist in unserem Fall main.EndToEndTester.java
|
||||||
|
- -> Hab ich alles umgesetzt
|
95
src/test/java/main/E2EReflectionsTest.java
Normal file
95
src/test/java/main/E2EReflectionsTest.java
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
package main;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import javax.tools.JavaCompiler;
|
||||||
|
import javax.tools.ToolProvider;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class E2EReflectionsTest {
|
||||||
|
@Test
|
||||||
|
public void AllFeaturesClassExampleTest(){
|
||||||
|
try {
|
||||||
|
Main.main(new String[]{"src/test/resources/input/combinedFeatureTests/AllFeaturesClassExample.java", "src/test/resources/output/raupenpiler"});
|
||||||
|
// Get the system Java compiler
|
||||||
|
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
|
||||||
|
// Assert that the compiler is available
|
||||||
|
assertNotNull(javac, "Java Compiler is not available");
|
||||||
|
javac.run(null, null, null, "src/test/resources/input/combinedFeatureTests/AllFeaturesClassExample.java");
|
||||||
|
|
||||||
|
Class<?> clazz = Class.forName("src.resources.input.combinedFeatureTests.AllFeaturesClassExample");
|
||||||
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
|
// Class<?> clazz = classLoader.loadClass("main.AllFeaturesClassExample");
|
||||||
|
|
||||||
|
// Class Name
|
||||||
|
assertEquals("main.AllFeaturesClassExample", clazz.getName());
|
||||||
|
|
||||||
|
// Constructors
|
||||||
|
Constructor<?>[] actualConstructors = clazz.getDeclaredConstructors();
|
||||||
|
assertTrue(actualConstructors.length > 0, "No constructors found");
|
||||||
|
|
||||||
|
Constructor<?> expectedConstructor = clazz.getConstructor(int.class, boolean.class, char.class);
|
||||||
|
|
||||||
|
boolean constructorFound = false;
|
||||||
|
for (Constructor<?> constructor : actualConstructors) {
|
||||||
|
if (constructor.equals(expectedConstructor)) {
|
||||||
|
constructorFound = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(constructorFound, "Expected constructor not found in actual constructors");
|
||||||
|
|
||||||
|
// Methods
|
||||||
|
Method[] actualMethodNames = clazz.getDeclaredMethods();
|
||||||
|
assertTrue(actualMethodNames.length > 0);
|
||||||
|
for (Method method : actualMethodNames) {
|
||||||
|
System.out.println("Method: " + method.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Method Names
|
||||||
|
String[] expectedMethodNames = {
|
||||||
|
"controlStructures",
|
||||||
|
"logicalOperations",
|
||||||
|
"add",
|
||||||
|
"subtract",
|
||||||
|
"multiply",
|
||||||
|
"divide",
|
||||||
|
"modulo",
|
||||||
|
"main"
|
||||||
|
};
|
||||||
|
|
||||||
|
for (Method method : actualMethodNames) {
|
||||||
|
assertTrue(Arrays.asList(expectedMethodNames).contains(method.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fields
|
||||||
|
Field[] actualFields = clazz.getDeclaredFields();
|
||||||
|
assertTrue(actualFields.length > 0, "No fields found");
|
||||||
|
|
||||||
|
Field expectedField = clazz.getDeclaredField("c");
|
||||||
|
assertEquals(expectedField.getType(), char.class);
|
||||||
|
|
||||||
|
boolean fieldFound = false;
|
||||||
|
for (Field field : actualFields) {
|
||||||
|
if (field.equals(expectedField)) {
|
||||||
|
fieldFound = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(fieldFound, "Expected field not found in actual fields");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
} catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@@ -1,6 +0,0 @@
|
|||||||
package main;
|
|
||||||
|
|
||||||
public class EmptyClassExample {
|
|
||||||
private class Inner {
|
|
||||||
}
|
|
||||||
} // -o für outout
|
|
@@ -3,18 +3,18 @@ package main;
|
|||||||
/**
|
/**
|
||||||
* This class is used to test the output of the compiler.
|
* This class is used to test the output of the compiler.
|
||||||
*
|
*
|
||||||
* <p>Im gleichen Ordner wie diese Datei (main.TestCompilerOutput.java) muss die selbst kompilierte CompilerInput.class Datei sein.
|
* <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) rein kopieren. (bis es eine bessere Lösung gibt)</p>
|
* <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>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 main.TestCompilerOutput.java Datei wird dann in <code> \src\test\java> </code> mit <code>javac .\main.TestCompilerOutput.java</code> kompiliert und mit <code>java main.TestCompilerOutput</code> ausgeführt.
|
* <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,
|
* 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>
|
* 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.
|
* <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>
|
* <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 TestCompilerOutput {
|
public class EndToEndTester {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
try {
|
try {
|
||||||
// Try to load the class named "CompilerInput"
|
// Try to load the class named "CompilerInput"
|
@@ -1,74 +0,0 @@
|
|||||||
package main;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
import org.antlr.v4.runtime.CharStream;
|
|
||||||
import org.antlr.v4.runtime.CharStreams;
|
|
||||||
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.Paths;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public class FailureTest {
|
|
||||||
private static final List<String> TEST_FILES = Arrays.asList(
|
|
||||||
"src/main/test/resources/input/failureTests/TestClass1.java",
|
|
||||||
"src/main/test/resources/input/failureTests/TestClass2.java",
|
|
||||||
"src/main/test/resources/input/failureTests/TestClass3.java",
|
|
||||||
"src/main/test/resources/input/failureTests/TestClass4.java",
|
|
||||||
"src/main/test/resources/input/failureTests/TestClass5.java",
|
|
||||||
"src/main/test/resources/input/failureTests/TestClass6.java",
|
|
||||||
"src/main/test/resources/input/failureTests/TestClass7.java",
|
|
||||||
"src/main/test/resources/input/failureTests/TestClass8.java",
|
|
||||||
"src/main/test/resources/input/failureTests/TestClass9.java",
|
|
||||||
"src/main/test/resources/input/failureTests/TestClass10.java",
|
|
||||||
"src/main/test/resources/input/failureTests/TestClass11.java"
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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 invalidJavaFilesTest() {
|
|
||||||
// Get the system Java compiler
|
|
||||||
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
|
|
||||||
|
|
||||||
// Assert that the compiler is available
|
|
||||||
assertNotNull(compiler, "Java Compiler is not available");
|
|
||||||
|
|
||||||
// Iterate over the test files
|
|
||||||
for (String fileName : TEST_FILES) {
|
|
||||||
// Create a File object for the current file
|
|
||||||
File file = new File(fileName);
|
|
||||||
|
|
||||||
// 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 = compiler.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 " + fileName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// schmeißt John Fehler, wenn namen doppelt sind?
|
|
||||||
// Input: ParseTree mit genanntem Fehler
|
|
||||||
// Output: Fehlermeldung
|
|
||||||
@Test
|
|
||||||
void typedASTTest() throws IOException {
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/main/test/resources/main/EmptyClassExample.java"));
|
|
||||||
Main.compileFile(codeCharStream, "src/main/test/resources/output");
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Error reading the file: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
104
src/test/java/main/InputFilesTest.java
Normal file
104
src/test/java/main/InputFilesTest.java
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
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 folder1 = new File("src/test/resources/input/combinedFeatureTests");
|
||||||
|
File folder2 = new File("src/test/resources/input/singleFeatureTests");
|
||||||
|
File folder3 = new File("src/test/resources/input/typedAstFeatureTests");
|
||||||
|
|
||||||
|
List<File> files = getJavaFilesFromDirectory(folder1);
|
||||||
|
files.addAll(getJavaFilesFromDirectory(folder2));
|
||||||
|
files.addAll(getJavaFilesFromDirectory(folder3));
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@@ -7,14 +7,14 @@ import org.antlr.v4.runtime.CharStreams;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* run: mvn test
|
* run every test: mvn test
|
||||||
|
* Nutzen dieser Klasse: Eigentlich nicht vorhanden, in der Main gibts nichts zu testen
|
||||||
*/
|
*/
|
||||||
public class MainTest {
|
public class MainTest {
|
||||||
@Test
|
@Test
|
||||||
void testEmptyClass() {
|
void test() {
|
||||||
CharStream codeCharStream = null;
|
CharStream codeCharStream = null;
|
||||||
try {
|
try {
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/main/test/resources/CompilerInput.java"));
|
codeCharStream = CharStreams.fromPath(Paths.get("src/main/test/resources/CompilerInput.java"));
|
||||||
|
145
src/test/java/main/ReflectionsTest.java
Normal file
145
src/test/java/main/ReflectionsTest.java
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
package main;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.antlr.v4.runtime.CharStream;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
|
||||||
|
public class ReflectionsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSimpleJavaLexerClass() throws ClassNotFoundException, NoSuchMethodException {
|
||||||
|
Class<?> clazz = Class.forName("parser.generated.SimpleJavaLexer");
|
||||||
|
|
||||||
|
// Class Name
|
||||||
|
assertEquals("parser.generated.SimpleJavaLexer", clazz.getName());
|
||||||
|
|
||||||
|
// Constructors
|
||||||
|
Constructor<?>[] actualConstructors = clazz.getDeclaredConstructors();
|
||||||
|
assertTrue(actualConstructors.length > 0, "No constructors found");
|
||||||
|
|
||||||
|
Constructor<?> expectedConstructor = clazz.getConstructor(CharStream.class);
|
||||||
|
|
||||||
|
boolean constructorFound = false;
|
||||||
|
for (Constructor<?> constructor : actualConstructors) {
|
||||||
|
if (constructor.equals(expectedConstructor)) {
|
||||||
|
constructorFound = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(constructorFound, "Expected constructor not found in actual constructors");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Methods
|
||||||
|
Method[] actualMethodNames = clazz.getDeclaredMethods();
|
||||||
|
assertTrue(actualMethodNames.length > 0);
|
||||||
|
Arrays.stream(actualMethodNames).forEach(method -> System.out.println("Method: " + method.getName()));
|
||||||
|
|
||||||
|
List<String> expectedMethodNames = Arrays.asList(
|
||||||
|
"getTokenNames",
|
||||||
|
"getVocabulary",
|
||||||
|
"getGrammarFileName",
|
||||||
|
"getRuleNames",
|
||||||
|
"getSerializedATN",
|
||||||
|
"getChannelNames",
|
||||||
|
"getModeNames",
|
||||||
|
"getATN",
|
||||||
|
"makeRuleNames",
|
||||||
|
"makeLiteralNames",
|
||||||
|
"makeSymbolicNames"
|
||||||
|
);
|
||||||
|
|
||||||
|
for (Method method : actualMethodNames) {
|
||||||
|
assertTrue(expectedMethodNames.contains(method.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (String expectedMethodName : expectedMethodNames) {
|
||||||
|
boolean methodFound = false;
|
||||||
|
for (Method method : actualMethodNames) {
|
||||||
|
if (method.getName().equals(expectedMethodName)) {
|
||||||
|
methodFound = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(methodFound, "Expected method " + expectedMethodName + " not found in actual methods");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Fields
|
||||||
|
Field[] actualFieldNames = clazz.getDeclaredFields();
|
||||||
|
assertTrue(actualFieldNames.length > 0);
|
||||||
|
Arrays.stream(actualFieldNames).forEach(field -> System.out.println("Field: " + field.getName()));
|
||||||
|
|
||||||
|
List<String> expectedFieldNames = Arrays.asList(
|
||||||
|
"_decisionToDFA",
|
||||||
|
"_sharedContextCache",
|
||||||
|
"channelNames",
|
||||||
|
"modeNames",
|
||||||
|
"ruleNames",
|
||||||
|
"_LITERAL_NAMES",
|
||||||
|
"_SYMBOLIC_NAMES",
|
||||||
|
"VOCABULARY",
|
||||||
|
"tokenNames",
|
||||||
|
"_serializedATN",
|
||||||
|
"_ATN"
|
||||||
|
);
|
||||||
|
|
||||||
|
for (Field field : actualFieldNames) {
|
||||||
|
assertTrue(expectedFieldNames.contains(field.getName()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSimpleJavaParserClass() throws ClassNotFoundException {
|
||||||
|
Class<?> clazz = Class.forName("parser.generated.SimpleJavaParser");
|
||||||
|
|
||||||
|
// Class Name
|
||||||
|
assertEquals("parser.generated.SimpleJavaParser", clazz.getName());
|
||||||
|
|
||||||
|
// Constructors
|
||||||
|
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
|
||||||
|
assertTrue(constructors.length > 0);
|
||||||
|
|
||||||
|
// Methods
|
||||||
|
Method[] methods = clazz.getDeclaredMethods();
|
||||||
|
assertTrue(methods.length > 0);
|
||||||
|
Arrays.stream(methods).forEach(method -> System.out.println("Method: " + method.getName()));
|
||||||
|
|
||||||
|
// Fields
|
||||||
|
Field[] fields = clazz.getDeclaredFields();
|
||||||
|
assertTrue(fields.length > 0);
|
||||||
|
Arrays.stream(fields).forEach(field -> System.out.println("Field: " + field.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testASTBuilderClass() throws ClassNotFoundException {
|
||||||
|
Class<?> clazz = Class.forName("parser.astBuilder.ASTBuilder");
|
||||||
|
|
||||||
|
// Class Name
|
||||||
|
assertEquals("parser.astBuilder.ASTBuilder", clazz.getName());
|
||||||
|
|
||||||
|
// Constructors
|
||||||
|
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
|
||||||
|
assertTrue(constructors.length > 0);
|
||||||
|
|
||||||
|
// Methods
|
||||||
|
Method[] methods = clazz.getDeclaredMethods();
|
||||||
|
assertTrue(methods.length > 0);
|
||||||
|
Arrays.stream(methods).forEach(method -> System.out.println("Method: " + method.getName()));
|
||||||
|
|
||||||
|
// Fields
|
||||||
|
Field[] fields = clazz.getDeclaredFields();
|
||||||
|
assertTrue(fields.length > 0);
|
||||||
|
Arrays.stream(fields).forEach(field -> System.out.println("Field: " + field.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Similarly, you can add tests for SemanticAnalyzer and ByteCodeGenerator
|
||||||
|
}
|
408
src/test/java/parser/AstBuilderTest.java
Normal file
408
src/test/java/parser/AstBuilderTest.java
Normal file
@@ -0,0 +1,408 @@
|
|||||||
|
package parser;
|
||||||
|
|
||||||
|
|
||||||
|
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.MemberNode;
|
||||||
|
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.IStatementNode;
|
||||||
|
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.ITypeNode;
|
||||||
|
import ast.type.type.TypeEnum;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||||
|
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.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import parser.astBuilder.ASTBuilder;
|
||||||
|
import parser.generated.SimpleJavaLexer;
|
||||||
|
import parser.generated.SimpleJavaParser;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.lang.reflect.Member;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@DisplayName("Untyped Abstract Syntax Tree")
|
||||||
|
class AstBuilderTest {
|
||||||
|
|
||||||
|
private final static String directoryPath = "src/test/resources/input/singleFeatureTests/";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Empty Class Test")
|
||||||
|
public void emptyClassTest() {
|
||||||
|
ClassNode emptyClass = Helper.generateEmptyClass("EmptyClass");
|
||||||
|
ProgramNode expected = new ProgramNode();
|
||||||
|
expected.addClass(emptyClass);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "EmptyClass.java");
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Multiple Empty Classes Test")
|
||||||
|
public void multipleEmptyClassesTest() {
|
||||||
|
ClassNode class1 = Helper.generateEmptyClass("MultipleClasses");
|
||||||
|
ClassNode class2 = Helper.generateEmptyClass("TestClass2");
|
||||||
|
ProgramNode expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
expected.addClass(class2);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "MultipleClasses.java");
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Empty Class Test with Constructor")
|
||||||
|
public void emptyClassWithConstructorTest() {
|
||||||
|
ClassNode class1 = Helper.generateEmptyClass("EmptyClassWithConstructor");
|
||||||
|
ProgramNode expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "EmptyClassWithConstructor.java");
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "Field.java");
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "FieldWithAccessModifier.java");
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "Comments.java");
|
||||||
|
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "ConstructorParameter.java");
|
||||||
|
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "ThisDot.java");
|
||||||
|
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "ConstructorThisDot.java");
|
||||||
|
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "VoidMethod.java");
|
||||||
|
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "ConstructorMethodCall.java");
|
||||||
|
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "ConstructorMethodCallParameters.java");
|
||||||
|
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "Char.java");
|
||||||
|
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Null Test")
|
||||||
|
public void nullTest() {
|
||||||
|
BlockNode blockCon = new BlockNode();
|
||||||
|
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
||||||
|
memberAccess.addIdentifier("a");
|
||||||
|
|
||||||
|
AssignableNode assignable = new AssignableNode(memberAccess);
|
||||||
|
|
||||||
|
blockCon.addStatement(new AssignNode(assignable, new UnaryNode(new ValueNode(EnumValueNode.NULL_VALUE, "null"))));
|
||||||
|
blockCon.addStatement(new ReturnNode(null));
|
||||||
|
ConstructorNode constructor = new ConstructorNode("public", "Null", blockCon);
|
||||||
|
|
||||||
|
ClassNode class1 = new ClassNode("public", "Null");
|
||||||
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
class1.addMember(constructor);
|
||||||
|
|
||||||
|
ProgramNode expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "Null.java");
|
||||||
|
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Self Reference Test")
|
||||||
|
public void selfReferneceTest() {
|
||||||
|
|
||||||
|
//assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Variable Compare Test")
|
||||||
|
public void variableCompareTest() {
|
||||||
|
|
||||||
|
//assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Variable Calculation Test")
|
||||||
|
public void variableCalculationTest() {
|
||||||
|
|
||||||
|
//assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Main Method Test")
|
||||||
|
public void mainMethodTest() {
|
||||||
|
|
||||||
|
//assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("While Test")
|
||||||
|
public void whileTest() {
|
||||||
|
|
||||||
|
//assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Do While Test")
|
||||||
|
public void doWhileTest() {
|
||||||
|
|
||||||
|
//assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("For Test")
|
||||||
|
public void forTest() {
|
||||||
|
|
||||||
|
//assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Noch nicht speziell Increment nur zum Development Testen per Debug
|
||||||
|
@Test
|
||||||
|
@DisplayName("Increment Test")
|
||||||
|
public void incrementTest() {
|
||||||
|
ClassNode classNode = Helper.generateEmptyClass("Increment");
|
||||||
|
classNode.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
|
ProgramNode expected = new ProgramNode();
|
||||||
|
expected.addClass(classNode);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "Increment.java");
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
47
src/test/java/parser/Helper.java
Normal file
47
src/test/java/parser/Helper.java
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package parser;
|
||||||
|
|
||||||
|
import ast.ASTNode;
|
||||||
|
import ast.ClassNode;
|
||||||
|
import ast.ProgramNode;
|
||||||
|
import ast.members.ConstructorNode;
|
||||||
|
import ast.members.MemberNode;
|
||||||
|
import ast.statements.BlockNode;
|
||||||
|
import ast.statements.ReturnNode;
|
||||||
|
import ast.type.AccessModifierNode;
|
||||||
|
import org.antlr.v4.runtime.CharStream;
|
||||||
|
import org.antlr.v4.runtime.CharStreams;
|
||||||
|
import org.antlr.v4.runtime.CommonTokenStream;
|
||||||
|
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 Helper {
|
||||||
|
public static ASTNode generateAST(String filePath) {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ClassNode generateEmptyClass(String className) {
|
||||||
|
BlockNode blockNode = new BlockNode();
|
||||||
|
blockNode.addStatement(new ReturnNode(null));
|
||||||
|
MemberNode constructor = new ConstructorNode("public",className, blockNode);
|
||||||
|
ClassNode classNode = new ClassNode("public", className);
|
||||||
|
classNode.addMember(constructor);
|
||||||
|
return classNode;
|
||||||
|
}
|
||||||
|
}
|
@@ -4,7 +4,6 @@ import org.antlr.v4.runtime.*;
|
|||||||
import org.antlr.v4.runtime.tree.ParseTree;
|
import org.antlr.v4.runtime.tree.ParseTree;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import parser.astBuilder.ASTBuilder;
|
|
||||||
import parser.generated.SimpleJavaLexer;
|
import parser.generated.SimpleJavaLexer;
|
||||||
import parser.generated.SimpleJavaParser;
|
import parser.generated.SimpleJavaParser;
|
||||||
|
|
||||||
@@ -13,41 +12,13 @@ import static org.junit.jupiter.api.Assertions.*;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
public class ParserTest {
|
public class ParserTest {
|
||||||
|
/*
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
public void init() { // noch nicht benötigt
|
public void init() { // noch nicht benötigt
|
||||||
String inputFilePath = "src/main/resources/input/CompilerInput.java";
|
String inputFilePath = "src/main/resources/input/CompilerInput.java";
|
||||||
String outputDirectoryPath = "src/main/resources/output";
|
String outputDirectoryPath = "src/main/resources/output";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 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<Token> actualTokens = tokenStream.getTokens();
|
|
||||||
List<String> expectedTokens = Arrays.asList("public", "class", "Name", "{", "}", "<EOF>");
|
|
||||||
List<String> expectedTokenTypes = Arrays.asList(null, null, "IDENTIFIER", null, null, "EOF");
|
|
||||||
|
|
||||||
// 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()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void parserTest() {
|
public void parserTest() {
|
||||||
@@ -63,38 +34,20 @@ public class ParserTest {
|
|||||||
ParseTree parseTree = parser.program(); // parse the input
|
ParseTree parseTree = parser.program(); // parse the input
|
||||||
|
|
||||||
//Variante 1 (geht)
|
//Variante 1 (geht)
|
||||||
|
String expectedParseTreeAsString = "(program (classDeclaration public class Name { }))";
|
||||||
String actualParseTreeAsString = parseTree.toStringTree(parser);
|
String actualParseTreeAsString = parseTree.toStringTree(parser);
|
||||||
String expectedParseTreeAsString = "(program (classDeclaration (accessType public) class Name { }))";
|
|
||||||
|
|
||||||
assertEquals(actualParseTreeAsString, expectedParseTreeAsString);
|
assertEquals(expectedParseTreeAsString, actualParseTreeAsString);
|
||||||
|
|
||||||
//Variante 2 (geht nicht)
|
// Variante 2 (geht nicht)
|
||||||
// - Sollte es gehen und es liegt am Parser? (keine Ahnung) -> Bitte Fehler (actual und expected) durchlesen
|
// - Sollte es gehen und es liegt am Parser? (keine Ahnung) -> Bitte Fehler (actual und expected) durchlesen
|
||||||
Map<String, Object> actualTreeStructure = buildTreeStructure(parseTree, parser);
|
// ist die Methode parseStringToTree() korrekt? -> (glaub nicht)
|
||||||
Map<String, Object> expectedTreeStructure = parseStringToTree(expectedParseTreeAsString);
|
Map<String, Object> expectedTreeStructure = parseStringToTree(expectedParseTreeAsString);
|
||||||
|
Map<String, Object> actualTreeStructure = buildTreeStructure(parseTree, parser);
|
||||||
|
|
||||||
assertEquals(actualTreeStructure, expectedTreeStructure);
|
// assertEquals(expectedTreeStructure, actualTreeStructure);
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void astBuilderTest() {
|
|
||||||
// TODO: Implement this test method
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/* AST builder -> AST */
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
|
||||||
// ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
|
||||||
|
|
||||||
//String actualASTasString = new ASTBuilder().visit(parseTree).toString();
|
|
||||||
|
|
||||||
// ProgramNode actualAST = new ASTBuilder().visit(parseTree);
|
|
||||||
// ProgramNode expectedAST = new ProgramNode();
|
|
||||||
// expectedAST.add(new ProgramNode.ClassNode("Name", new ProgramNode()));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Helpers Variante 2.1
|
// Helpers Variante 2.1
|
||||||
@@ -146,7 +99,7 @@ public class ParserTest {
|
|||||||
for (char ch : input.toCharArray()) {
|
for (char ch : input.toCharArray()) {
|
||||||
if (ch == '(') {
|
if (ch == '(') {
|
||||||
if (depth == 0) {
|
if (depth == 0) {
|
||||||
if (currentToken.length() > 0) {
|
if (!currentToken.isEmpty()) {
|
||||||
node.put("node", currentToken.toString().trim());
|
node.put("node", currentToken.toString().trim());
|
||||||
currentToken.setLength(0);
|
currentToken.setLength(0);
|
||||||
}
|
}
|
||||||
@@ -163,7 +116,7 @@ public class ParserTest {
|
|||||||
currentToken.append(ch);
|
currentToken.append(ch);
|
||||||
}
|
}
|
||||||
} else if (Character.isWhitespace(ch) && depth == 0) {
|
} else if (Character.isWhitespace(ch) && depth == 0) {
|
||||||
if (currentToken.length() > 0) {
|
if (!currentToken.isEmpty()) {
|
||||||
node.put("node", currentToken.toString().trim());
|
node.put("node", currentToken.toString().trim());
|
||||||
currentToken.setLength(0);
|
currentToken.setLength(0);
|
||||||
}
|
}
|
||||||
@@ -172,7 +125,7 @@ public class ParserTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (currentToken.length() > 0) {
|
if (!currentToken.isEmpty()) {
|
||||||
node.put("node", currentToken.toString().trim());
|
node.put("node", currentToken.toString().trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
45
src/test/java/parser/ScannerTest.java
Normal file
45
src/test/java/parser/ScannerTest.java
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
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()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
45
src/test/java/semantic/BeginnToTAST.java
Normal file
45
src/test/java/semantic/BeginnToTAST.java
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@@ -1,282 +0,0 @@
|
|||||||
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 org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import parser.astBuilder.ASTBuilder;
|
|
||||||
import parser.generated.SimpleJavaLexer;
|
|
||||||
import parser.generated.SimpleJavaParser;
|
|
||||||
import semantic.exeptions.AlreadyDeclearedException;
|
|
||||||
import semantic.exeptions.MultipleReturnTypes;
|
|
||||||
import semantic.exeptions.NotDeclearedException;
|
|
||||||
import semantic.exeptions.TypeMismatchException;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
|
|
||||||
public class EndToTAST {
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
public void setup(){
|
|
||||||
SemanticAnalyzer.clearAnalyzer();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void CorrectTest(){
|
|
||||||
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/semantic/endToTAST/CorrectTest.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);
|
|
||||||
|
|
||||||
ASTNode tast = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
|
||||||
|
|
||||||
|
|
||||||
assertEquals(SemanticAnalyzer.errors.size(), 0);
|
|
||||||
assertNotNull(tast);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void notDecleared() {
|
|
||||||
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/semantic/endToTAST/NotDecleared.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);
|
|
||||||
|
|
||||||
ASTNode tast = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
|
||||||
|
|
||||||
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
|
||||||
assertInstanceOf(NotDeclearedException.class, SemanticAnalyzer.errors.getFirst());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void typeMismatch(){
|
|
||||||
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/semantic/endToTAST/TypeMismatchIntBool.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();
|
|
||||||
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
|
||||||
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
|
||||||
|
|
||||||
ASTNode tast = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
|
||||||
|
|
||||||
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
|
||||||
assertInstanceOf(TypeMismatchException.class, SemanticAnalyzer.errors.getFirst());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void parameterAlreadyDecleared(){
|
|
||||||
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/semantic/endToTAST/ParameterAlreadyDecleared.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();
|
|
||||||
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
|
||||||
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
|
||||||
|
|
||||||
ASTNode tast = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
|
||||||
|
|
||||||
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
|
||||||
assertInstanceOf(AlreadyDeclearedException.class, SemanticAnalyzer.errors.getFirst());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void fieldAlreadyDecleared(){
|
|
||||||
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/semantic/endToTAST/FieldAlreadyDecleared.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();
|
|
||||||
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
|
||||||
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
|
||||||
|
|
||||||
ASTNode tast = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
|
||||||
|
|
||||||
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
|
||||||
assertInstanceOf(AlreadyDeclearedException.class, SemanticAnalyzer.errors.getFirst());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void typeMismatchRefType(){
|
|
||||||
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/semantic/endToTAST/TypeMismatchRefType.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();
|
|
||||||
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
|
||||||
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
|
||||||
|
|
||||||
ASTNode tast = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
|
||||||
|
|
||||||
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
|
||||||
assertInstanceOf(TypeMismatchException.class, SemanticAnalyzer.errors.getFirst());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void correctRetType(){
|
|
||||||
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/semantic/endToTAST/CorrectRetType.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();
|
|
||||||
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
|
||||||
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
|
||||||
|
|
||||||
ASTNode tast = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
|
||||||
|
|
||||||
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void retTypeMismatch(){
|
|
||||||
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/semantic/endToTAST/retTypeMismatch.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();
|
|
||||||
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
|
||||||
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
|
||||||
|
|
||||||
ASTNode tast = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
|
||||||
|
|
||||||
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
|
||||||
assertInstanceOf(TypeMismatchException.class, SemanticAnalyzer.errors.getFirst());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void multipleRetType(){
|
|
||||||
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/semantic/endToTAST/MultipleRetTypes.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();
|
|
||||||
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
|
||||||
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
|
||||||
|
|
||||||
ASTNode tast = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
|
||||||
|
|
||||||
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
|
||||||
assertInstanceOf(MultipleReturnTypes.class, SemanticAnalyzer.errors.getFirst());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void wrongTypeInIfClause(){
|
|
||||||
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/semantic/endToTAST/WrongIfClause.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();
|
|
||||||
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
|
||||||
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
|
||||||
|
|
||||||
ASTNode tast = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
|
||||||
|
|
||||||
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
243
src/test/java/semantic/EndToTypedAstTest.java
Normal file
243
src/test/java/semantic/EndToTypedAstTest.java
Normal file
@@ -0,0 +1,243 @@
|
|||||||
|
package semantic;
|
||||||
|
|
||||||
|
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 ast.ASTNode;
|
||||||
|
import ast.ProgramNode;
|
||||||
|
|
||||||
|
import parser.astBuilder.ASTBuilder;
|
||||||
|
import parser.generated.SimpleJavaLexer;
|
||||||
|
import parser.generated.SimpleJavaParser;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.net.URLClassLoader;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class EndToTypedAstTest {
|
||||||
|
private static final Map<String, Class<?>> exceptionMap = new HashMap<>();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testOnlyOneFile() {
|
||||||
|
SemanticAnalyzer.clearAnalyzer();
|
||||||
|
|
||||||
|
CharStream codeCharStream = null;
|
||||||
|
try {
|
||||||
|
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/input/typedAstFeatureTests/CorrectTest.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();
|
||||||
|
ASTBuilder astBuilder = new ASTBuilder();
|
||||||
|
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
||||||
|
|
||||||
|
var result = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void exceptionsTest() {
|
||||||
|
String directoryPath = "src/test/resources/input/typedAstExceptionsTests";
|
||||||
|
File folder = new File(directoryPath);
|
||||||
|
|
||||||
|
try {
|
||||||
|
loadCustomExceptions();
|
||||||
|
System.out.println("Custom exceptions loaded successfully.");
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to load custom exceptions", e);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if (folder.isDirectory()) {
|
||||||
|
File[] files = folder.listFiles((_, name) -> name.endsWith(".java"));
|
||||||
|
if (files != null) {
|
||||||
|
for (File file : files) {
|
||||||
|
String expectedException = extractExpectedException(file);
|
||||||
|
|
||||||
|
SemanticAnalyzer.clearAnalyzer();
|
||||||
|
CharStream codeCharStream;
|
||||||
|
try {
|
||||||
|
codeCharStream = CharStreams.fromPath(Paths.get(file.getPath()));
|
||||||
|
} 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();
|
||||||
|
|
||||||
|
ASTBuilder astBuilder = new ASTBuilder();
|
||||||
|
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
|
||||||
|
if (expectedException != null) {
|
||||||
|
System.out.println("Testing the file: " + file.getName());
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty(), "Expected an exception, but none was found.");
|
||||||
|
assertInstanceOf(getExceptionClass(expectedException), SemanticAnalyzer.errors.getFirst());
|
||||||
|
} else {
|
||||||
|
System.out.println("No expected exception specified.");
|
||||||
|
// If no expected exception is specified, you might want to add a different check
|
||||||
|
// e.g., assertTrue(SemanticAnalyzer.errors.isEmpty(), "No exceptions expected, but some were found.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
System.out.println("No files found in the directory.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
System.out.println("The provided path is not a directory.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void featureTest() {
|
||||||
|
String directoryPath = "src/test/resources/input/typedAstFeatureTests";
|
||||||
|
File folder = new File(directoryPath);
|
||||||
|
if (folder.isDirectory()) {
|
||||||
|
File[] files = folder.listFiles((_, name) -> name.endsWith(".java"));
|
||||||
|
if (files != null) {
|
||||||
|
for (File file : files) {
|
||||||
|
SemanticAnalyzer.clearAnalyzer();
|
||||||
|
CharStream codeCharStream;
|
||||||
|
try {
|
||||||
|
codeCharStream = CharStreams.fromPath(Paths.get(file.getPath()));
|
||||||
|
} 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();
|
||||||
|
|
||||||
|
ASTBuilder astBuilder = new ASTBuilder();
|
||||||
|
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
|
||||||
|
System.out.println("Testing the file: " + file.getName());
|
||||||
|
for(Exception runtimeException : SemanticAnalyzer.errors){
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
System.out.println("No files found in the directory.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
System.out.println("The provided path is not a directory.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// ------------------ Helpers ------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method is used to extract the expected exception from a given file.
|
||||||
|
* It reads the file line by line and uses a regular expression to match the expected exception annotation.
|
||||||
|
* The expected exception annotation should be in the format: "// @expected: ExceptionName".
|
||||||
|
* If the expected exception annotation is found, it returns the name of the expected exception.
|
||||||
|
* If the expected exception annotation is not found, it returns null.
|
||||||
|
*
|
||||||
|
* @param file The file from which the expected exception is to be extracted.
|
||||||
|
* @return The name of the expected exception, or null if the expected exception annotation is not found.
|
||||||
|
*/
|
||||||
|
private String extractExpectedException(File file) {
|
||||||
|
String annotationPattern = "//\\s*@expected:\\s*(\\S+)";
|
||||||
|
Pattern pattern = Pattern.compile(annotationPattern);
|
||||||
|
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
|
||||||
|
String line;
|
||||||
|
while ((line = reader.readLine()) != null) {
|
||||||
|
Matcher matcher = pattern.matcher(line);
|
||||||
|
if (matcher.find()) {
|
||||||
|
return matcher.group(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method is used to retrieve the Class object associated with a given exception name.
|
||||||
|
* It first prints the original exception name, then appends the package name to the exception name and prints it.
|
||||||
|
* It then retrieves the Class object from the exceptionMap using the fully qualified exception name.
|
||||||
|
* If the Class object is not found in the exceptionMap, it throws a RuntimeException.
|
||||||
|
*
|
||||||
|
* @param exceptionName The name of the exception for which the Class object is to be retrieved.
|
||||||
|
* @return The Class object associated with the given exception name.
|
||||||
|
* @throws RuntimeException If the Class object for the given exception name is not found in the exceptionMap.
|
||||||
|
*/
|
||||||
|
private Class<?> getExceptionClass(String exceptionName) {
|
||||||
|
System.out.println(exceptionName);
|
||||||
|
exceptionName = "semantic.exceptions." + exceptionName;
|
||||||
|
System.out.println(exceptionName);
|
||||||
|
Class<?> exceptionClass = exceptionMap.get(exceptionName);
|
||||||
|
if (exceptionClass == null) {
|
||||||
|
throw new RuntimeException("Exception class not found: " + exceptionName);
|
||||||
|
}
|
||||||
|
return exceptionClass;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method is used to load custom exceptions from a specified package.
|
||||||
|
* It first constructs the directory path from the package name and checks if the directory exists.
|
||||||
|
* If the directory does not exist, it throws an IllegalArgumentException.
|
||||||
|
* It then creates a URLClassLoader to load the classes from the directory.
|
||||||
|
* It iterates over all the files in the directory, and for each file, it constructs the class name and loads the class.
|
||||||
|
* If the loaded class is a subtype of Throwable, it adds the class to the exceptionMap.
|
||||||
|
*
|
||||||
|
* @throws Exception If any error occurs during class loading.
|
||||||
|
*/
|
||||||
|
private static void loadCustomExceptions() throws Exception {
|
||||||
|
final String packName = "semantic.exceptions";
|
||||||
|
final String dirForMyClasses = "src/main/java/%s".formatted(packName.replace(".", "/"));
|
||||||
|
File folder = new File(dirForMyClasses);
|
||||||
|
if (!folder.isDirectory()) {
|
||||||
|
throw new IllegalArgumentException("The provided path is not a directory.");
|
||||||
|
}
|
||||||
|
|
||||||
|
URL[] urls = {folder.toURI().toURL()};
|
||||||
|
URLClassLoader classLoader;
|
||||||
|
try {
|
||||||
|
classLoader = new URLClassLoader(urls);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to create class loader", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (File file : Objects.requireNonNull(folder.listFiles())) {
|
||||||
|
String className = packName + "." + file.getName().replaceAll("\\.(?:class|java)$", "");
|
||||||
|
System.out.printf("Loading custom exception: %s (=> %s)", file.getName(), className);
|
||||||
|
Class<?> cls = classLoader.loadClass(className);
|
||||||
|
|
||||||
|
if (Throwable.class.isAssignableFrom(cls)) { // Check if the class is a subtype of Throwable
|
||||||
|
exceptionMap.put(className, cls);
|
||||||
|
System.out.println("Loaded custom exception: " + className);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@@ -1,102 +0,0 @@
|
|||||||
package semantic;
|
|
||||||
|
|
||||||
import ast.*;
|
|
||||||
import ast.members.FieldNode;
|
|
||||||
import ast.members.MethodNode;
|
|
||||||
import ast.parameters.ParameterNode;
|
|
||||||
import ast.type.AccessModifierNode;
|
|
||||||
import ast.type.type.*;
|
|
||||||
|
|
||||||
public class Mocker {
|
|
||||||
|
|
||||||
public static ASTNode mockTwoSameFields(){
|
|
||||||
ProgramNode p = new ProgramNode();
|
|
||||||
|
|
||||||
ClassNode c = new ClassNode();
|
|
||||||
c.identifier = "testClass";
|
|
||||||
|
|
||||||
FieldNode f1 = new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a");
|
|
||||||
|
|
||||||
c.members.add(f1);
|
|
||||||
|
|
||||||
FieldNode f2 = new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a");
|
|
||||||
|
|
||||||
c.members.add(f2);
|
|
||||||
|
|
||||||
p.classes.add(c);
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static ASTNode mockSimpleMethod(){
|
|
||||||
ProgramNode p = new ProgramNode();
|
|
||||||
|
|
||||||
ClassNode c = new ClassNode();
|
|
||||||
|
|
||||||
MethodNode methodNode = new MethodNode();
|
|
||||||
|
|
||||||
//Parameter
|
|
||||||
ParameterNode parameterNode = new ParameterNode(new BaseType(TypeEnum.INT), "a");
|
|
||||||
|
|
||||||
methodNode.addParameter(parameterNode);
|
|
||||||
|
|
||||||
//Statements
|
|
||||||
|
|
||||||
//Block
|
|
||||||
methodNode.block = new ast.statements.BlockNode();
|
|
||||||
|
|
||||||
c.members.add(methodNode);
|
|
||||||
|
|
||||||
p.classes.add(c);
|
|
||||||
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static ASTNode mockTwoSameMethods(){
|
|
||||||
ProgramNode p = new ProgramNode();
|
|
||||||
|
|
||||||
ClassNode c = new ClassNode();
|
|
||||||
|
|
||||||
MethodNode methodNode = new MethodNode();
|
|
||||||
methodNode.block = new ast.statements.BlockNode();
|
|
||||||
methodNode.setType(new BaseType(TypeEnum.INT));
|
|
||||||
|
|
||||||
methodNode.setIdentifier("testMethod");
|
|
||||||
|
|
||||||
c.members.add(methodNode);
|
|
||||||
|
|
||||||
MethodNode methodNode1 = new MethodNode();
|
|
||||||
methodNode1.block = new ast.statements.BlockNode();
|
|
||||||
methodNode1.setType(new BaseType(TypeEnum.INT));
|
|
||||||
|
|
||||||
methodNode1.setIdentifier("testMethod");
|
|
||||||
|
|
||||||
c.members.add(methodNode1);
|
|
||||||
|
|
||||||
p.classes.add(c);
|
|
||||||
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static ASTNode mockTwoDifferentMethods(){
|
|
||||||
ProgramNode p = new ProgramNode();
|
|
||||||
|
|
||||||
ClassNode c = new ClassNode();
|
|
||||||
|
|
||||||
MethodNode methodNode = new MethodNode();
|
|
||||||
methodNode.block = new ast.statements.BlockNode();
|
|
||||||
methodNode.setIdentifier("testMethod");
|
|
||||||
|
|
||||||
c.members.add(methodNode);
|
|
||||||
|
|
||||||
MethodNode methodNode1 = new MethodNode();
|
|
||||||
methodNode1.block = new ast.statements.BlockNode();
|
|
||||||
methodNode1.setIdentifier("testMethod1");
|
|
||||||
|
|
||||||
c.members.add(methodNode1);
|
|
||||||
|
|
||||||
p.classes.add(c);
|
|
||||||
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@@ -1,114 +1,5 @@
|
|||||||
package semantic;
|
package semantic;
|
||||||
|
|
||||||
import ast.*;
|
|
||||||
import ast.members.FieldNode;
|
|
||||||
import ast.members.MemberNode;
|
|
||||||
import ast.members.MethodNode;
|
|
||||||
import ast.parameters.ParameterNode;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import semantic.exeptions.AlreadyDeclearedException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
|
|
||||||
public class SemanticTest {
|
public class SemanticTest {
|
||||||
|
|
||||||
|
}
|
||||||
// @Test
|
|
||||||
// public void alreadyDeclaredLocalFieldVar() {
|
|
||||||
// ProgramNode programNode = new ProgramNode();
|
|
||||||
// List<ClassNode> classList = new ArrayList<>();
|
|
||||||
// AccessTypeNode accessTypeNode = new AccessTypeNode(EnumAccessTypeNode.PUBLIC);
|
|
||||||
// ClassNode classNode = new ClassNode(accessTypeNode, "testClass");
|
|
||||||
//
|
|
||||||
// SemanticAnalyzer semanticAnalyzer = new SemanticAnalyzer();
|
|
||||||
// ASTNode tast = semanticAnalyzer.generateTast(ast);
|
|
||||||
//
|
|
||||||
// MemberNode memberNode2 = new FieldNode(accessTypeNode, new BaseTypeNode(EnumTypeNode.INT), "testVar");
|
|
||||||
// classNode.members.add(memberNode2);
|
|
||||||
//
|
|
||||||
// classList.add(classNode);
|
|
||||||
// programNode.classes = classList;
|
|
||||||
//
|
|
||||||
// ASTNode typedAst = SemanticAnalyzer.generateTast(programNode);
|
|
||||||
//
|
|
||||||
// assertEquals(1, SemanticAnalyzer.errors.size());
|
|
||||||
// assertInstanceOf(AlreadyDeclearedException.class, SemanticAnalyzer.errors.getFirst());
|
|
||||||
// assertNull(typedAst);
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// @Test
|
|
||||||
// public void shouldWorkWithNoError() {
|
|
||||||
// ProgramNode programNode = new ProgramNode();
|
|
||||||
// List<ClassNode> classList = new ArrayList<>();
|
|
||||||
// AccessTypeNode accessTypeNode = new AccessTypeNode(EnumAccessTypeNode.PUBLIC);
|
|
||||||
// ClassNode classNode = new ClassNode(accessTypeNode, "testClass");
|
|
||||||
//
|
|
||||||
// SemanticAnalyzer semanticAnalyzer = new SemanticAnalyzer();
|
|
||||||
// ASTNode tast = semanticAnalyzer.generateTast(ast);
|
|
||||||
//
|
|
||||||
// assertEquals(semanticAnalyzer.errors.size(), 0);
|
|
||||||
// assertNotNull(tast);
|
|
||||||
//
|
|
||||||
// MemberNode memberNode3 = getMemberNode(accessTypeNode);
|
|
||||||
// classNode.members.add(memberNode3);
|
|
||||||
//
|
|
||||||
// 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,25 +0,0 @@
|
|||||||
package resources;
|
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@@ -1,16 +0,0 @@
|
|||||||
public class CompilerInput {
|
|
||||||
|
|
||||||
public int a;
|
|
||||||
|
|
||||||
public static int testMethod(char x){
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
public class Test {
|
|
||||||
|
|
||||||
public static int testMethod(char x, int a){
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@@ -1,8 +0,0 @@
|
|||||||
package resources;
|
|
||||||
|
|
||||||
public class MoreFeaturesClassExample {
|
|
||||||
int hallo;
|
|
||||||
private class Inner {
|
|
||||||
int hallo2;
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,68 +1,69 @@
|
|||||||
package resources;
|
|
||||||
|
|
||||||
public class AllFeaturesClassExample {
|
public class AllFeaturesClassExample {
|
||||||
int a;
|
int a;
|
||||||
boolean b;
|
boolean b;
|
||||||
char c;
|
char c;
|
||||||
|
|
||||||
// Konstruktor
|
// Konstruktor
|
||||||
AllFeaturesClassExample(int a, boolean b, char c) {
|
public AllFeaturesClassExample(int a, boolean b, char c) {
|
||||||
this.a = a;
|
this.a = a;
|
||||||
this.b = b;
|
this.b = b;
|
||||||
this.c = c;
|
this.c = c;
|
||||||
}
|
}
|
||||||
private class InnerClass {
|
|
||||||
void innerMethod() {
|
|
||||||
System.out.println("Inner class method");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Methode zur Demonstration von Kontrollstrukturen
|
// Methode zur Demonstration von Kontrollstrukturen
|
||||||
void controlStructures() {
|
void controlStructures() {
|
||||||
// if-else Anweisung
|
// if-else Anweisung
|
||||||
if (a > 10) {
|
if (a > 10) {
|
||||||
System.out.println("a ist größer als 10");
|
|
||||||
} else {
|
} else {
|
||||||
System.out.println("a ist nicht größer als 10");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// while Schleife
|
// while Schleife
|
||||||
while (a > 0) {
|
while (a > 0) {
|
||||||
System.out.println("a ist " + a);
|
|
||||||
a--;
|
a--;
|
||||||
}
|
}
|
||||||
|
int c = 0;
|
||||||
// for Schleife
|
// for Schleife
|
||||||
for (int i = 0; i < 5; i++) {
|
for (int i = 0; i < 5; i++) {
|
||||||
System.out.println("for Schleife Iteration: " + i);
|
c++;
|
||||||
}
|
}
|
||||||
|
|
||||||
// switch Anweisung
|
|
||||||
switch (c) {
|
|
||||||
case 'a':
|
|
||||||
System.out.println("c ist ein 'a'");
|
|
||||||
break;
|
|
||||||
case 'b':
|
|
||||||
System.out.println("c ist ein 'b'");
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
System.out.println("c ist nicht 'a' oder 'b'");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Methode zur Arbeit mit logischen Operatoren
|
// Methode zur Arbeit mit logischen Operatoren
|
||||||
void logicalOperations() {
|
void logicalOperations() {
|
||||||
// Logische UND-Operation
|
// Logische UND-Operation
|
||||||
if (b && a > 5) {
|
if (b && a > 5) {
|
||||||
System.out.println("a ist größer als 5 und b ist wahr");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Logische ODER-Operation
|
// Logische ODER-Operation
|
||||||
if (b || a < 5) {
|
if (b || a < 5) {
|
||||||
System.out.println("b ist wahr oder a ist kleiner als 5");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int add(int a, int b) {
|
||||||
|
return a + b;
|
||||||
|
}
|
||||||
|
|
||||||
|
int subtract(int a, int b) {
|
||||||
|
return a - b;
|
||||||
|
}
|
||||||
|
|
||||||
|
int multiply(int a, int b) {
|
||||||
|
return a * b;
|
||||||
|
}
|
||||||
|
|
||||||
|
int divide(int a, int b) {
|
||||||
|
return a / b;
|
||||||
|
}
|
||||||
|
|
||||||
|
int modulo(int a, int b) {
|
||||||
|
return a % b;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean greaterThan(int a, int b) {
|
||||||
|
return a > b;
|
||||||
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
AllFeaturesClassExample obj = new AllFeaturesClassExample(12, true, 'a');
|
AllFeaturesClassExample obj = new AllFeaturesClassExample(12, true, 'a');
|
||||||
obj.controlStructures();
|
obj.controlStructures();
|
@@ -1,5 +1,3 @@
|
|||||||
package resources.featureTests;
|
|
||||||
|
|
||||||
public class BooleanOperations {
|
public class BooleanOperations {
|
||||||
boolean flag;
|
boolean flag;
|
||||||
|
|
@@ -1,5 +1,3 @@
|
|||||||
package resources.featureTests;
|
|
||||||
|
|
||||||
public class CharManipulation {
|
public class CharManipulation {
|
||||||
char letter;
|
char letter;
|
||||||
|
|
@@ -1,5 +1,3 @@
|
|||||||
package resources.featureTests;
|
|
||||||
|
|
||||||
public class ConditionalStatements {
|
public class ConditionalStatements {
|
||||||
int number;
|
int number;
|
||||||
|
|
@@ -0,0 +1,2 @@
|
|||||||
|
public class EmptyClassExample {
|
||||||
|
}
|
@@ -1,5 +1,3 @@
|
|||||||
package resources.featureTests;
|
|
||||||
|
|
||||||
public class LoopExamples {
|
public class LoopExamples {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
// For loop example
|
// For loop example
|
@@ -1,5 +1,3 @@
|
|||||||
package resources.featureTests;
|
|
||||||
|
|
||||||
public class MethodOverloading {
|
public class MethodOverloading {
|
||||||
public int add(int a, int b) {
|
public int add(int a, int b) {
|
||||||
return a + b;
|
return a + b;
|
5
src/test/resources/input/johnsTests/FieldTests.java
Normal file
5
src/test/resources/input/johnsTests/FieldTests.java
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
public class Test{
|
||||||
|
|
||||||
|
int a = 10;
|
||||||
|
|
||||||
|
}
|
12
src/test/resources/input/singleFeatureTests/Char.java
Normal file
12
src/test/resources/input/singleFeatureTests/Char.java
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
class Char {
|
||||||
|
|
||||||
|
char a;
|
||||||
|
|
||||||
|
public Char(char a){
|
||||||
|
this.a = testMethod(a);
|
||||||
|
}
|
||||||
|
|
||||||
|
char testMethod(char a){
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user