Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bytecodeGenerics

This commit is contained in:
AluAli 2020-10-16 15:37:53 +02:00
commit 61f35f8f8b
591 changed files with 44238 additions and 24807 deletions

9
.gitignore vendored
View File

@ -19,4 +19,13 @@ bin
.DS_Store .DS_Store
.project .project
.settings/ .settings/
/target/
#
manually/
logFiles/**
!logFiles/.gitkeep
src/main/java/de/dhbwstuttgart/parser/antlr/
src/main/java/de/dhbwstuttgart/sat/asp/parser/antlr/

25
doc/Generics/generics.tex Normal file
View File

@ -0,0 +1,25 @@
\documentclass{article}
\begin{document}
\section{Generics sind notwendig}
Generics können nicht ignoriert werden.
Folgender Fall ist Typisierbar:
\begin{program}
<T> T m1(T x){
return m2(x);
}
m2(x){
m1(1);
m2("Test");
return m1(x);
}
\end{program}
Beim weglassen des Generics T wäre es aber nicht mehr möglich.
Dann erhält jeder Constraint, welcher in Verbindung mit der Methode m1 steht
den selben TPH.
\end{document}

View File

@ -112,7 +112,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.literal.Literal</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Literal</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.literal.BoolLiteral</li> <li>de.dhbwstuttgart.syntaxtree.statement.literal.BoolLiteral</li>
@ -253,7 +253,7 @@ extends <a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html"
</tr> </tr>
</table> </table>
<ul class="blockList"> <ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.literal.Literal"> <li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.Literal">
<!-- --> <!-- -->
</a> </a>
<h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3> <h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3>

View File

@ -112,7 +112,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.literal.Literal</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Literal</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.literal.CharLiteral</li> <li>de.dhbwstuttgart.syntaxtree.statement.literal.CharLiteral</li>
@ -253,7 +253,7 @@ extends <a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html"
</tr> </tr>
</table> </table>
<ul class="blockList"> <ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.literal.Literal"> <li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.Literal">
<!-- --> <!-- -->
</a> </a>
<h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3> <h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3>

View File

@ -112,7 +112,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.literal.Literal</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Literal</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.literal.DoubleLiteral</li> <li>de.dhbwstuttgart.syntaxtree.statement.literal.DoubleLiteral</li>
@ -263,7 +263,7 @@ extends <a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html"
</tr> </tr>
</table> </table>
<ul class="blockList"> <ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.literal.Literal"> <li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.Literal">
<!-- --> <!-- -->
</a> </a>
<h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3> <h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3>

View File

@ -112,7 +112,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.literal.Literal</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Literal</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.literal.FloatLiteral</li> <li>de.dhbwstuttgart.syntaxtree.statement.literal.FloatLiteral</li>
@ -263,7 +263,7 @@ extends <a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html"
</tr> </tr>
</table> </table>
<ul class="blockList"> <ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.literal.Literal"> <li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.Literal">
<!-- --> <!-- -->
</a> </a>
<h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3> <h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3>

View File

@ -112,7 +112,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.literal.Literal</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Literal</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.literal.NumberLiteral</li> <li>de.dhbwstuttgart.syntaxtree.statement.literal.NumberLiteral</li>
@ -263,7 +263,7 @@ extends <a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html"
</tr> </tr>
</table> </table>
<ul class="blockList"> <ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.literal.Literal"> <li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.Literal">
<!-- --> <!-- -->
</a> </a>
<h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3> <h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3>

View File

@ -112,7 +112,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.literal.Literal</li> <li>de.dhbwstuttgart.syntaxtree.statement.Literal</li>
</ul> </ul>
</li> </li>
</ul> </ul>

View File

@ -112,7 +112,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.literal.Literal</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Literal</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.LongLiteral</li> <li>de.dhbwstuttgart.syntaxtree.statement.LongLiteral</li>
@ -263,7 +263,7 @@ extends <a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html"
</tr> </tr>
</table> </table>
<ul class="blockList"> <ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.literal.Literal"> <li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.Literal">
<!-- --> <!-- -->
</a> </a>
<h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3> <h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3>

View File

@ -115,7 +115,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.NegativeExpr</li> <li>de.dhbwstuttgart.syntaxtree.statement.javaInternal.NegativeExpr</li>
</ul> </ul>
</li> </li>
</ul> </ul>

View File

@ -115,7 +115,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.NotExpr</li> <li>de.dhbwstuttgart.syntaxtree.statement.javaInternal.NotExpr</li>
</ul> </ul>
</li> </li>
</ul> </ul>

View File

@ -112,7 +112,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.literal.Literal</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Literal</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.literal.Null</li> <li>de.dhbwstuttgart.syntaxtree.statement.literal.Null</li>
@ -245,7 +245,7 @@ extends <a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html"
</tr> </tr>
</table> </table>
<ul class="blockList"> <ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.literal.Literal"> <li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.Literal">
<!-- --> <!-- -->
</a> </a>
<h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3> <h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3>

View File

@ -115,7 +115,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.PositivExpr</li> <li>de.dhbwstuttgart.syntaxtree.statement.javaInternal.PositivExpr</li>
</ul> </ul>
</li> </li>
</ul> </ul>

View File

@ -115,7 +115,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.PostDecExpr</li> <li>de.dhbwstuttgart.syntaxtree.statement.javaInternal.PostDecExpr</li>
</ul> </ul>
</li> </li>
</ul> </ul>

View File

@ -115,7 +115,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.PostIncExpr</li> <li>de.dhbwstuttgart.syntaxtree.statement.javaInternal.PostIncExpr</li>
</ul> </ul>
</li> </li>
</ul> </ul>

View File

@ -115,7 +115,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.PreDecExpr</li> <li>de.dhbwstuttgart.syntaxtree.statement.javaInternal.PreDecExpr</li>
</ul> </ul>
</li> </li>
</ul> </ul>

View File

@ -115,7 +115,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/UnaryExpr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.UnaryExpr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.PreIncExpr</li> <li>de.dhbwstuttgart.syntaxtree.statement.javaInternal.PreIncExpr</li>
</ul> </ul>
</li> </li>
</ul> </ul>

View File

@ -112,7 +112,7 @@ var activeTableTab = "activeTableTab";
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Expr.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Expr</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.literal.Literal</a></li> <li><a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">de.dhbwstuttgart.syntaxtree.statement.Literal</a></li>
<li> <li>
<ul class="inheritance"> <ul class="inheritance">
<li>de.dhbwstuttgart.syntaxtree.statement.literal.StringLiteral</li> <li>de.dhbwstuttgart.syntaxtree.statement.literal.StringLiteral</li>
@ -253,7 +253,7 @@ extends <a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html"
</tr> </tr>
</table> </table>
<ul class="blockList"> <ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.literal.Literal"> <li class="blockList"><a name="methods.inherited.from.class.de.dhbwstuttgart.syntaxtree.statement.Literal">
<!-- --> <!-- -->
</a> </a>
<h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3> <h3>Methods inherited from class&nbsp;de.dhbwstuttgart.syntaxtree.statement.<a href="../../../../de/dhbwstuttgart/syntaxtree/statement/Literal.html" title="class in de.dhbwstuttgart.syntaxtree.statement">Literal</a></h3>

View File

@ -3,7 +3,7 @@
<html lang="de"> <html lang="de">
<head> <head>
<!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 --> <!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 -->
<title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.literal.Literal</title> <title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.Literal</title>
<meta name="date" content="2015-05-12"> <meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../script.js"></script>
@ -70,7 +70,7 @@
</a></div> </a></div>
<!-- ========= END OF TOP NAVBAR ========= --> <!-- ========= END OF TOP NAVBAR ========= -->
<div class="header"> <div class="header">
<h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.literal.Literal" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.Literal</h2> <h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.Literal" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.Literal</h2>
</div> </div>
<div class="classUseContainer"> <div class="classUseContainer">
<ul class="blockList"> <ul class="blockList">

View File

@ -3,7 +3,7 @@
<html lang="de"> <html lang="de">
<head> <head>
<!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 --> <!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 -->
<title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.NegativeExpr</title> <title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.NegativeExpr</title>
<meta name="date" content="2015-05-12"> <meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../script.js"></script>
@ -70,9 +70,9 @@
</a></div> </a></div>
<!-- ========= END OF TOP NAVBAR ========= --> <!-- ========= END OF TOP NAVBAR ========= -->
<div class="header"> <div class="header">
<h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.NegativeExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.NegativeExpr</h2> <h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.NegativeExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.NegativeExpr</h2>
</div> </div>
<div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.NegativeExpr</div> <div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.javaInternal.NegativeExpr</div>
<!-- ======= START OF BOTTOM NAVBAR ====== --> <!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom"> <div class="bottomNav"><a name="navbar.bottom">
<!-- --> <!-- -->

View File

@ -3,7 +3,7 @@
<html lang="de"> <html lang="de">
<head> <head>
<!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 --> <!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 -->
<title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.NotExpr</title> <title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.NotExpr</title>
<meta name="date" content="2015-05-12"> <meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../script.js"></script>
@ -70,9 +70,9 @@
</a></div> </a></div>
<!-- ========= END OF TOP NAVBAR ========= --> <!-- ========= END OF TOP NAVBAR ========= -->
<div class="header"> <div class="header">
<h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.NotExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.NotExpr</h2> <h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.NotExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.NotExpr</h2>
</div> </div>
<div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.NotExpr</div> <div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.javaInternal.NotExpr</div>
<!-- ======= START OF BOTTOM NAVBAR ====== --> <!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom"> <div class="bottomNav"><a name="navbar.bottom">
<!-- --> <!-- -->

View File

@ -3,7 +3,7 @@
<html lang="de"> <html lang="de">
<head> <head>
<!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 --> <!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 -->
<title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.PositivExpr</title> <title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.PositivExpr</title>
<meta name="date" content="2015-05-12"> <meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../script.js"></script>
@ -70,9 +70,9 @@
</a></div> </a></div>
<!-- ========= END OF TOP NAVBAR ========= --> <!-- ========= END OF TOP NAVBAR ========= -->
<div class="header"> <div class="header">
<h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.PositivExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.PositivExpr</h2> <h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.PositivExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.PositivExpr</h2>
</div> </div>
<div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.PositivExpr</div> <div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.javaInternal.PositivExpr</div>
<!-- ======= START OF BOTTOM NAVBAR ====== --> <!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom"> <div class="bottomNav"><a name="navbar.bottom">
<!-- --> <!-- -->

View File

@ -3,7 +3,7 @@
<html lang="de"> <html lang="de">
<head> <head>
<!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 --> <!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 -->
<title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.PostDecExpr</title> <title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.PostDecExpr</title>
<meta name="date" content="2015-05-12"> <meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../script.js"></script>
@ -70,9 +70,9 @@
</a></div> </a></div>
<!-- ========= END OF TOP NAVBAR ========= --> <!-- ========= END OF TOP NAVBAR ========= -->
<div class="header"> <div class="header">
<h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.PostDecExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.PostDecExpr</h2> <h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.PostDecExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.PostDecExpr</h2>
</div> </div>
<div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.PostDecExpr</div> <div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.javaInternal.PostDecExpr</div>
<!-- ======= START OF BOTTOM NAVBAR ====== --> <!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom"> <div class="bottomNav"><a name="navbar.bottom">
<!-- --> <!-- -->

View File

@ -3,7 +3,7 @@
<html lang="de"> <html lang="de">
<head> <head>
<!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 --> <!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 -->
<title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.PostIncExpr</title> <title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.PostIncExpr</title>
<meta name="date" content="2015-05-12"> <meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../script.js"></script>
@ -70,9 +70,9 @@
</a></div> </a></div>
<!-- ========= END OF TOP NAVBAR ========= --> <!-- ========= END OF TOP NAVBAR ========= -->
<div class="header"> <div class="header">
<h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.PostIncExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.PostIncExpr</h2> <h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.PostIncExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.PostIncExpr</h2>
</div> </div>
<div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.PostIncExpr</div> <div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.javaInternal.PostIncExpr</div>
<!-- ======= START OF BOTTOM NAVBAR ====== --> <!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom"> <div class="bottomNav"><a name="navbar.bottom">
<!-- --> <!-- -->

View File

@ -3,7 +3,7 @@
<html lang="de"> <html lang="de">
<head> <head>
<!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 --> <!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 -->
<title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.PreDecExpr</title> <title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.PreDecExpr</title>
<meta name="date" content="2015-05-12"> <meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../script.js"></script>
@ -70,9 +70,9 @@
</a></div> </a></div>
<!-- ========= END OF TOP NAVBAR ========= --> <!-- ========= END OF TOP NAVBAR ========= -->
<div class="header"> <div class="header">
<h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.PreDecExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.PreDecExpr</h2> <h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.PreDecExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.PreDecExpr</h2>
</div> </div>
<div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.PreDecExpr</div> <div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.javaInternal.PreDecExpr</div>
<!-- ======= START OF BOTTOM NAVBAR ====== --> <!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom"> <div class="bottomNav"><a name="navbar.bottom">
<!-- --> <!-- -->

View File

@ -3,7 +3,7 @@
<html lang="de"> <html lang="de">
<head> <head>
<!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 --> <!-- Generated by javadoc (1.8.0_05) on Tue May 12 19:56:24 CEST 2015 -->
<title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.PreIncExpr</title> <title>Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.PreIncExpr</title>
<meta name="date" content="2015-05-12"> <meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../script.js"></script>
@ -70,9 +70,9 @@
</a></div> </a></div>
<!-- ========= END OF TOP NAVBAR ========= --> <!-- ========= END OF TOP NAVBAR ========= -->
<div class="header"> <div class="header">
<h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.PreIncExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.PreIncExpr</h2> <h2 title="Uses of Class de.dhbwstuttgart.syntaxtree.statement.javaInternal.PreIncExpr" class="title">Uses of Class<br>de.dhbwstuttgart.syntaxtree.statement.PreIncExpr</h2>
</div> </div>
<div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.PreIncExpr</div> <div class="classUseContainer">No usage of de.dhbwstuttgart.syntaxtree.statement.javaInternal.PreIncExpr</div>
<!-- ======= START OF BOTTOM NAVBAR ====== --> <!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom"> <div class="bottomNav"><a name="navbar.bottom">
<!-- --> <!-- -->

BIN
doc/PluginBau.pdf Normal file

Binary file not shown.

24
doc/parser.md Normal file
View File

@ -0,0 +1,24 @@
# Dateien
* sämtliche Datein im Ordner de.dhbwstuttgart.parser gehören zum Parser
* Auch zu beachten: pom.xml
* Ein Teil der pom.xml instruiert maven zur Kompilierung der Java8.g4 Datei
* VORSICHT! Wird nicht zwangsläufig von der IDE ausgeführt
* siehe Kapitel "Grammatik -> Parser"
## Unterordner antlr
* Java8.g4
* die eigentliche Java Grammatik
* hier wurden Anpassungen vorgenommen, damit sie auch typloses Java annimmt
* alle anderen Dateien in diesem Ordner sind vom ANTLR-Parsergenerator autogeneriert
## Unterordner SyntaxTreeGenerator
* SyntaxTreeGenerator
* TODO
# Grammatik -> Parser
* Die Antlr-Grammatik (Java8.g4) wandelt
* Folgende Stellen sind relevant
* TODO

0
logFiles/.gitkeep Normal file
View File

107
pom.xml
View File

@ -1,12 +1,12 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd"> http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>de.dhbwstuttgart</groupId> <groupId>de.dhbwstuttgart</groupId>
<artifactId>JavaTXcompiler</artifactId> <artifactId>JavaTXcompiler</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<version>0.1</version> <version>0.1</version>
<name>JavaTXcompiler</name> <name>JavaTXcompiler</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
@ -14,43 +14,72 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.0</version> <version>4.11</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.antlr</groupId> <groupId>org.antlr</groupId>
<artifactId>antlr4</artifactId> <artifactId>antlr4</artifactId>
<version>4.7</version> <version>4.8-1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>19.0</version> <version>22.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.reflections</groupId> <groupId>org.reflections</groupId>
<artifactId>reflections</artifactId> <artifactId>reflections</artifactId>
<version>0.9.11</version> <version>0.9.11</version>
</dependency> </dependency>
<dependency> <!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<dependency>
<groupId>org.ow2.asm</groupId> <groupId>org.ow2.asm</groupId>
<artifactId>asm-all</artifactId> <artifactId>asm</artifactId>
<version>[4.0.0,)</version> <version>7.0</version>
</dependency> </dependency>
<!-- <dependency> <groupId>org.ow2.asm</groupId> <artifactId>asm-all</artifactId>
<version>[4.0.0,)</version> </dependency> -->
<!-- <dependency> <groupId>org.bitbucket.mstrobel</groupId> <artifactId>procyon-reflection</artifactId>
<version>[0.5.32,)</version> </dependency> -->
</dependencies> </dependencies>
<build> <build>
<directory>target</directory> <directory>target</directory>
<outputDirectory>target/classes</outputDirectory> <outputDirectory>target/classes</outputDirectory>
<finalName>${artifactId}-${version}</finalName> <finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>target/test-classes</testOutputDirectory> <testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src/</sourceDirectory>
<testSourceDirectory>test/</testSourceDirectory>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<!-- plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<verbose>true</verbose>
<fork>true</fork>
<executable>/home/michael/programs/jdk/jdk8u232-b09/bin/javac</executable>
<compilerVersion>1.8</compilerVersion>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin -->
<plugin> <plugin>
<groupId>org.antlr</groupId> <groupId>org.antlr</groupId>
<artifactId>antlr4-maven-plugin</artifactId> <artifactId>antlr4-maven-plugin</artifactId>
<version>4.7</version> <version>4.8-1</version>
<executions> <executions>
<execution> <execution>
<id>antlr</id> <id>antlr</id>
@ -58,8 +87,8 @@
<goal>antlr4</goal> <goal>antlr4</goal>
</goals> </goals>
<configuration> <configuration>
<sourceDirectory>src/de/dhbwstuttgart/parser/antlr/</sourceDirectory> <sourceDirectory>src/main/antlr4/java8</sourceDirectory>
<outputDirectory>src/de/dhbwstuttgart/parser/antlr/</outputDirectory> <outputDirectory>${project.basedir}/src/main/java/de/dhbwstuttgart/parser/antlr</outputDirectory>
<arguments> <arguments>
<argument>-package</argument> <argument>-package</argument>
<argument>de.dhbwstuttgart.parser.antlr</argument> <argument>de.dhbwstuttgart.parser.antlr</argument>
@ -68,10 +97,48 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<mainClass>de.dhbwstuttgart.core.ConsoleInterface</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
<repositories>
<repository>
<id>maven-repository</id>
<url>file:///${project.basedir}/target</url>
</repository>
</repositories>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<tycho.version>0.23.0</tycho.version>
<mainClass>de.dhbwstuttgart.core.ConsoleInterface</mainClass>
</properties> </properties>
<distributionManagement>
<repository>
<id>maven-repository</id>
<name>MyCo Internal Repository</name>
<url>file:///${project.basedir}/maven-repository/</url>
</repository>
</distributionManagement>
</project> </project>

View File

@ -1,24 +0,0 @@
#!/bin/bash
# A basic script to compile the necessary packages and their subpackages to work with the parser.
# Messages are logged to stderr.
>&2 echo "Building de.dhbwstuttgart.typecheck..."
javac -d ../bin ./de/dhbwstuttgart/typecheck/*.java
>&2 echo "Building de.dhbwstuttgart.syntaxtree..."
javac -d ../bin ./de/dhbwstuttgart/syntaxtree/*.java
>&2 echo "Building de.dhbwstuttgart.syntaxtree.factory..."
javac -d ../bin ./de/dhbwstuttgart/syntaxtree/factory/*.java
>&2 echo "Building de.dhbwstuttgart.syntaxtree.operator..."
javac -d ../bin ./de/dhbwstuttgart/syntaxtree/operator/*.java
>&2 echo "Building de.dhbwstuttgart.syntaxtree.statement..."
javac -d ../bin ./de/dhbwstuttgart/syntaxtree/statement/*.java
>&2 echo "Building de.dhbwstuttgart.syntaxtree.statement.literal..."
javac -d ../bin ./de/dhbwstuttgart/syntaxtree/statement/literal/*.java
>&2 echo "Building de.dhbwstuttgart.syntaxtree.type..."
javac -d ../bin ./de/dhbwstuttgart/syntaxtree/type/*.java
>&2 echo "Building de.dhbwstuttgart.parser..."
javac -d ../bin ./de/dhbwstuttgart/parser/*.java
>&2 echo "Building de.dhbwstuttgart.parser.SyntaxTreeGenerator..."
javac -d ../bin ./de/dhbwstuttgart/parser/SyntaxTreeGenerator/*.java
>&2 echo "Building de.dhbwstuttgart.parser.antlr..."
javac -d ../bin ./de/dhbwstuttgart/parser/antlr/*.java
echo "Done. Now its your turn to debug:)."

Binary file not shown.

View File

@ -1,386 +0,0 @@
package de.dhbwstuttgart.bytecode;
import java.awt.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.statement.ArgumentList;
import de.dhbwstuttgart.syntaxtree.statement.Assign;
import de.dhbwstuttgart.syntaxtree.statement.AssignToField;
import de.dhbwstuttgart.syntaxtree.statement.Binary;
import de.dhbwstuttgart.syntaxtree.statement.Block;
import de.dhbwstuttgart.syntaxtree.statement.CastExpr;
import de.dhbwstuttgart.syntaxtree.statement.DoStmt;
import de.dhbwstuttgart.syntaxtree.statement.EmptyStmt;
import de.dhbwstuttgart.syntaxtree.statement.FieldVar;
import de.dhbwstuttgart.syntaxtree.statement.ForStmt;
import de.dhbwstuttgart.syntaxtree.statement.IfStmt;
import de.dhbwstuttgart.syntaxtree.statement.InstanceOf;
import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression;
import de.dhbwstuttgart.syntaxtree.statement.LocalVar;
import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl;
import de.dhbwstuttgart.syntaxtree.statement.MethodCall;
import de.dhbwstuttgart.syntaxtree.statement.NewArray;
import de.dhbwstuttgart.syntaxtree.statement.NewClass;
import de.dhbwstuttgart.syntaxtree.statement.Receiver;
import de.dhbwstuttgart.syntaxtree.statement.Return;
import de.dhbwstuttgart.syntaxtree.statement.ReturnVoid;
import de.dhbwstuttgart.syntaxtree.statement.StaticClassName;
import de.dhbwstuttgart.syntaxtree.statement.Super;
import de.dhbwstuttgart.syntaxtree.statement.SuperCall;
import de.dhbwstuttgart.syntaxtree.statement.This;
import de.dhbwstuttgart.syntaxtree.statement.UnaryPlus;
import de.dhbwstuttgart.syntaxtree.statement.WhileStmt;
import de.dhbwstuttgart.syntaxtree.statement.literal.Literal;
import de.dhbwstuttgart.syntaxtree.statement.literal.Null;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
public class BytecodeGen implements ASTVisitor {
ClassWriter cw =new ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS);
// String methDesc;
String type;
String className;
// stores parameter, local vars and the next index on the local variable table, which use for aload_i, astore_i,...
HashMap<String, Integer> paramsAndLocals;// = new HashMap<>();
byte[] bytecode;
HashMap<String,byte[]> classFiles;
public BytecodeGen(HashMap<String,byte[]> classFiles) {
this.classFiles = classFiles;
paramsAndLocals = new HashMap<>();
}
@Override
public void visit(SourceFile sourceFile) {
for(ClassOrInterface cl : sourceFile.getClasses()) {
BytecodeGen classGen = new BytecodeGen(classFiles);
cl.accept(classGen);
classGen.writeClass(cl.getClassName().toString());
}
}
private void writeClass(String name) {
bytecode = cw.toByteArray();
classFiles.put(name, bytecode);
}
public HashMap<String,byte[]> getClassFiles() {
return classFiles;
}
@Override
public void visit(ClassOrInterface classOrInterface) {
className = classOrInterface.getClassName().toString();
// access flages??
cw.visit(Opcodes.V1_8, classOrInterface.getModifiers()+Opcodes.ACC_SUPER, classOrInterface.getClassName().toString()
, null, classOrInterface.getSuperClass().toString(), null);
// for each field in the class
for(Field f : classOrInterface.getFieldDecl()) {
System.out.println("get Fields");
System.out.println(f.getName());
f.accept(this);
}
for(Constructor c : classOrInterface.getConstructors()) {
c.accept(this);
}
for(Method m : classOrInterface.getMethods()) {
m.accept(this);
}
cw.visitSource(classOrInterface.getClassName().toString()+".jav", null);
}
@Override
public void visit(Constructor field) {
Descriptor desc = new Descriptor(field);
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", desc.getDesc(), null, null);
mv.visitCode();
System.out.println("-----Constructor-----");
BytecodeGenMethod gen = new BytecodeGenMethod(className,field, mv,paramsAndLocals,desc.getDesc(),cw);
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
@Override
public void visit(Method method) {
method.getParameterList().accept(this);
Descriptor methDesc = new Descriptor(method);
System.out.println("-----Method-----");
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), methDesc.getDesc(), null, null);
mv.visitCode();
BytecodeGenMethod gen = new BytecodeGenMethod(className,method, mv,paramsAndLocals,methDesc.getDesc(),cw);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
@Override
public void visit(ParameterList formalParameters) {
Iterator<FormalParameter> itr = formalParameters.iterator();
int i = 1;
while(itr.hasNext()) {
FormalParameter fp = itr.next();
paramsAndLocals.put(fp.getName(), i);
fp.accept(this);
i++;
}
}
@Override
public void visit(FormalParameter formalParameter) {
formalParameter.getType().accept(this);
}
@Override
public void visit(RefType refType) {
type = "L"+refType.toString()+";";
}
@Override
public void visit(SuperWildcardType superWildcardType) {
// TODO Auto-generated method stub
}
@Override
public void visit(TypePlaceholder typePlaceholder) {
// TODO Auto-generated method stub
}
@Override
public void visit(ExtendsWildcardType extendsWildcardType) {
// TODO Auto-generated method stub
}
@Override
public void visit(GenericRefType genericRefType) {
// TODO Auto-generated method stub
}
// ??
@Override
public void visit(FieldVar fieldVar) {
System.out.println("in fieldvar");
// cw.newField(fieldVar.receiver.toString(), fieldVar.fieldVarName.toString(), fieldVar.getType().toString());
FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE, fieldVar.fieldVarName, "L"+fieldVar.getType()+";", null, null);
fv.visitEnd();
}
// access flages?? modifiers
@Override
public void visit(Field field) {
System.out.println("in field");
FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE, field.getName(), "L"+field.getType().toString().replace(".", "/")+";", null, null);
fv.visitEnd();
}
@Override
public void visit(LambdaExpression lambdaExpression) {
// TODO Auto-generated method stub
}
@Override
public void visit(Assign assign) {
// TODO Auto-generated method stub
}
@Override
public void visit(Binary binary) {
// TODO Auto-generated method stub
}
@Override
public void visit(Block block) {
// TODO Auto-generated method stub
}
@Override
public void visit(CastExpr castExpr) {
// TODO Auto-generated method stub
}
@Override
public void visit(EmptyStmt emptyStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(ForStmt forStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(IfStmt ifStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(InstanceOf instanceOf) {
// TODO Auto-generated method stub
}
@Override
public void visit(LocalVar localVar) {
// TODO Auto-generated method stub
}
@Override
public void visit(LocalVarDecl localVarDecl) {
// TODO Auto-generated method stub
}
@Override
public void visit(MethodCall methodCall) {
// TODO Auto-generated method stub
}
@Override
public void visit(NewClass methodCall) {
// TODO Auto-generated method stub
}
@Override
public void visit(NewArray newArray) {
// TODO Auto-generated method stub
}
@Override
public void visit(Receiver receiver) {
// TODO Auto-generated method stub
}
@Override
public void visit(Return aReturn) {
// TODO Auto-generated method stub
}
@Override
public void visit(ReturnVoid aReturn) {
// TODO Auto-generated method stub
}
@Override
public void visit(StaticClassName staticClassName) {
// TODO Auto-generated method stub
}
@Override
public void visit(Super aSuper) {
// TODO Auto-generated method stub
}
@Override
public void visit(This aThis) {
// TODO Auto-generated method stub
}
@Override
public void visit(UnaryPlus unaryPlus) {
// TODO Auto-generated method stub
}
@Override
public void visit(WhileStmt whileStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(DoStmt whileStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(Null aNull) {
// TODO Auto-generated method stub
}
// ???
@Override
public void visit(Literal literal) {
// TODO Auto-generated method stub
}
@Override
public void visit(ArgumentList argumentList) {
// TODO Auto-generated method stub
}
@Override
public void visit(GenericTypeVar genericTypeVar) {
// TODO Auto-generated method stub
}
@Override
public void visit(GenericDeclarationList genericTypeVars) {
// TODO Auto-generated method stub
}
@Override
public void visit(AssignToField assignLeftSide) {
// TODO Auto-generated method stub
}
@Override
public void visit(AssignToLocal assignLeftSide) {
// TODO Auto-generated method stub
}
@Override
public void visit(SuperCall superCall) {
// TODO Auto-generated method stub
}
}

View File

@ -1,360 +0,0 @@
package de.dhbwstuttgart.bytecode;
import java.io.PrintStream;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Handle;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.statement.ArgumentList;
import de.dhbwstuttgart.syntaxtree.statement.Assign;
import de.dhbwstuttgart.syntaxtree.statement.AssignToField;
import de.dhbwstuttgart.syntaxtree.statement.Binary;
import de.dhbwstuttgart.syntaxtree.statement.Block;
import de.dhbwstuttgart.syntaxtree.statement.CastExpr;
import de.dhbwstuttgart.syntaxtree.statement.DoStmt;
import de.dhbwstuttgart.syntaxtree.statement.EmptyStmt;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
import de.dhbwstuttgart.syntaxtree.statement.FieldVar;
import de.dhbwstuttgart.syntaxtree.statement.ForStmt;
import de.dhbwstuttgart.syntaxtree.statement.IfStmt;
import de.dhbwstuttgart.syntaxtree.statement.InstanceOf;
import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression;
import de.dhbwstuttgart.syntaxtree.statement.LocalVar;
import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl;
import de.dhbwstuttgart.syntaxtree.statement.MethodCall;
import de.dhbwstuttgart.syntaxtree.statement.NewArray;
import de.dhbwstuttgart.syntaxtree.statement.NewClass;
import de.dhbwstuttgart.syntaxtree.statement.Receiver;
import de.dhbwstuttgart.syntaxtree.statement.Return;
import de.dhbwstuttgart.syntaxtree.statement.ReturnVoid;
import de.dhbwstuttgart.syntaxtree.statement.Statement;
import de.dhbwstuttgart.syntaxtree.statement.StaticClassName;
import de.dhbwstuttgart.syntaxtree.statement.Super;
import de.dhbwstuttgart.syntaxtree.statement.SuperCall;
import de.dhbwstuttgart.syntaxtree.statement.This;
import de.dhbwstuttgart.syntaxtree.statement.UnaryPlus;
import de.dhbwstuttgart.syntaxtree.statement.WhileStmt;
import de.dhbwstuttgart.syntaxtree.statement.literal.Literal;
import de.dhbwstuttgart.syntaxtree.statement.literal.Null;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
public class BytecodeGenMethod implements StatementVisitor{
private Method m;
private MethodVisitor mv;
private HashMap<String, Integer> paramsAndLocals = new HashMap<>();
private String desc;
private String className;
private int lamCounter;
private ClassWriter cw;
//for tests **
private String fieldName;
private String fieldDesc;
private Expression rightSideTemp;
private String where;
public BytecodeGenMethod(String className, Method m, MethodVisitor mv, HashMap<String, Integer> paramsAndLocals,
String desc, ClassWriter cw) {
this.where = "NORMAL METHOD";
this.className = className;
this.m = m;
this.mv = mv;
this.paramsAndLocals = paramsAndLocals;
this.desc = desc;
this.cw = cw;
this.lamCounter = -1;
this.m.block.accept(this);
}
public BytecodeGenMethod(LambdaExpression lambdaExpression, MethodVisitor mv,
HashMap<String, Integer> paramsAndLocals, String desc) {
System.out.println("++++++IN LAMBDA -------");
this.where = "&&&&&&&& LAMBDA METHOD";
this.mv = mv;
this.paramsAndLocals = paramsAndLocals;
this.desc = desc;
this.lamCounter = -1;
lambdaExpression.methodBody.accept(this);
}
@Override
public void visit(Block block) {
for(Statement stmt : block.getStatements()) {
System.out.println(where);
System.out.println("Stmt : " + stmt.toString());
stmt.accept(this);
System.out.println("--------------------------\n");
}
}
@Override
public void visit(SuperCall superCall) {
superCall.receiver.accept(this);
superCall.arglist.accept(this);
// mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", superCall.name, desc,false);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), superCall.name, desc,false);
}
// ??
@Override
public void visit(LocalVar localVar) {
System.out.println("in Local Var");
}
// ??
@Override
public void visit(LocalVarDecl localVarDecl) {
// Integer i;
paramsAndLocals.put(localVarDecl.getName(), paramsAndLocals.size()+1);
System.out.println("In localVarDecl");
}
@Override
public void visit(Assign assign) {
System.out.println("Assign : \nright = "+assign.rightSide + "\nLeft = " + assign.lefSide);
if(assign.lefSide.getClass().equals(AssignToField.class)) {
// load_0, ldc or .. then putfield
this.rightSideTemp = assign.rightSide;
assign.lefSide.accept(this);
}else {
assign.rightSide.accept(this);
assign.lefSide.accept(this);
}
}
@Override
public void visit(Binary binary) {
System.out.println("++ In Binary: ");
}
@Override
public void visit(LambdaExpression lambdaExpression) {
System.out.println("\n++ In Lambda: ");
this.lamCounter++;
//Call site, which, when invoked, returns an instance of the functional interface to which
//the lambda is being converted
MethodType mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class,
MethodType.class, MethodType.class, MethodHandle.class, MethodType.class);
Handle bootstrap = new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory",
"metafactory", mt.toMethodDescriptorString(), false);
String methodName = "lambda$new$" + this.lamCounter;
// Type erasure
Type arg1 = Type.getMethodType("()V");
// real Type
Type arg3 = Type.getMethodType("()V");
Handle arg2 = new Handle(Opcodes.H_INVOKESTATIC, this.className, methodName,
arg3.toString(),false);
mv.visitInvokeDynamicInsn("run", "()Ljava/lang/Runnable;", bootstrap,
arg1, arg2,arg3);
MethodVisitor mvLambdaBody = cw.visitMethod(Opcodes.ACC_PRIVATE+ Opcodes.ACC_STATIC + Opcodes.ACC_SYNTHETIC,
methodName, arg3.toString(), null, null);
// new BytecodeGenLambda(lambdaExpression, mvLambdaBody);
new BytecodeGenMethod(lambdaExpression, mvLambdaBody, new HashMap<>(), arg3.toString());
mvLambdaBody.visitMaxs(0, 0);
mvLambdaBody.visitEnd();
}
@Override
public void visit(CastExpr castExpr) {
// TODO Auto-generated method stub
}
@Override
public void visit(EmptyStmt emptyStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(FieldVar fieldVar) {
System.out.println("in fieldVar " + fieldVar.fieldVarName + " ** receiver: "+fieldVar.receiver);
fieldName = fieldVar.fieldVarName;
fieldDesc = fieldVar.getType().toString();
fieldVar.receiver.accept(this);
// test (if)
if(!fieldVar.receiver.getClass().equals(StaticClassName.class)) {
mv.visitFieldInsn(Opcodes.GETFIELD,fieldVar.getType().toString(),fieldName ,fieldDesc);
}
// mv.visitFieldInsn(Opcodes.GETSTATIC, fieldVar.receiver.getType().toString().replace(".", "/"),
// fieldVar.fieldVarName, fieldVar.getType().toString());
}
@Override
public void visit(ForStmt forStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(IfStmt ifStmt) {
System.out.println("++ IF-Statment: ");
}
@Override
public void visit(InstanceOf instanceOf) {
// TODO Auto-generated method stub
}
@Override
public void visit(MethodCall methodCall) {
System.out.println(" In Methodcall: (" +methodCall.name+")" );
System.out.println(" Method-Receiver: "+methodCall.receiver.expr);
methodCall.receiver.accept(this);
methodCall.arglist.accept(this);
Descriptor mDesc = new Descriptor(methodCall.arglist, methodCall.getType());
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, methodCall.receiver.expr.getType().toString(),
methodCall.name, mDesc.getDesc(), false);
// test
if(!methodCall.getType().toString().equals("V")) {
mv.visitInsn(Opcodes.POP);
}
}
@Override
public void visit(NewClass methodCall) {
System.out.println("In NewClass: ");
System.out.println("name: " + methodCall.name + " *** " + "Receiver: " + methodCall.receiver);
mv.visitTypeInsn(Opcodes.NEW, methodCall.name.replace(".", "/"));
mv.visitInsn(Opcodes.DUP);
// creates Descriptor
methodCall.arglist.accept(this);
String d = "(";
for(Expression e : methodCall.arglist.getArguments()) {
d = d + "L"+e.getType().toString().replace(".", "/") + ";";
}
d += ")V";
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, methodCall.name.replace(".", "/"), "<init>", d, false);
}
@Override
public void visit(NewArray newArray) {
// TODO Auto-generated method stub
}
@Override
public void visit(Receiver receiver) {
System.out.println(" in Receiver");
System.out.println(" expr : " + receiver.expr);
receiver.expr.accept(this);
}
@Override
public void visit(Return aReturn) {
mv.visitInsn(Opcodes.ARETURN);
}
@Override
public void visit(ReturnVoid aReturn) {
mv.visitInsn(Opcodes.RETURN);
}
@Override
public void visit(StaticClassName staticClassName) {
System.out.println("In StaticClassName: ");
// mv.visitMethodInsn(Opcodes.INVOKESTATIC, staticClassName.getType().toString().replace(".", "/"),
// staticClassName.toString(), staticClassName.getType().toString(), false);
mv.visitFieldInsn(Opcodes.GETSTATIC, staticClassName.getType().toString().replace(".", "/"),
fieldName, fieldDesc);
}
@Override
public void visit(Super aSuper) {
System.out.println(">> In Super: ");
}
@Override
public void visit(This aThis) {
System.out.println("-> IN This");
mv.visitVarInsn(Opcodes.ALOAD, 0);
}
@Override
public void visit(UnaryPlus unaryPlus) {
System.out.println("++ In UnaryPlus: ");
}
@Override
public void visit(WhileStmt whileStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(DoStmt whileStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(Null aNull) {
mv.visitInsn(Opcodes.ACONST_NULL);
}
@Override
public void visit(Literal literal) {
// value?
mv.visitLdcInsn(literal.getType().toString());
}
@Override
public void visit(ArgumentList argumentList) {
for(Expression al : argumentList.getArguments()) {
al.accept(this);
}
}
@Override
public void visit(AssignToField assignLeftSide) {
// Loads the an object reference from the local variable
// array slot onto the top of the operand stack.
assignLeftSide.field.receiver.accept(this);
this.rightSideTemp.accept(this);
mv.visitFieldInsn(Opcodes.PUTFIELD, assignLeftSide.field.receiver.getType().toString(),
assignLeftSide.field.fieldVarName, assignLeftSide.field.getType().toString());
}
@Override
public void visit(AssignToLocal assignLeftSide) {
paramsAndLocals.put(assignLeftSide.localVar.name, paramsAndLocals.size()+1);
mv.visitVarInsn(Opcodes.ASTORE, paramsAndLocals.size());
}
}

View File

@ -1,14 +0,0 @@
package de.dhbwstuttgart.bytecode;
public class ClassFile {
String name;
byte[] bytecode;
public ClassFile(String name, byte[] bytecode) {
this.name = name;
this.bytecode = bytecode;
}
}

View File

@ -1,54 +0,0 @@
package de.dhbwstuttgart.bytecode;
import java.awt.List;
import java.util.Iterator;
import de.dhbwstuttgart.syntaxtree.Constructor;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.statement.ArgumentList;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
public class Descriptor {
String desc;
public Descriptor(Method method) {
desc = "(";
Iterator<FormalParameter> itr = method.getParameterList().iterator();
while(itr.hasNext()) {
FormalParameter fp = itr.next();
desc = desc + "L"+fp.getType().toString().replace(".", "/") + ";";
}
if(method.getReturnType().toString().equals("void")){
desc = desc + ")V";
}else {
desc = desc + ")" + "L"+method.getReturnType().toString().replace(".", "/")+";";
}
}
public Descriptor(Constructor constructor) {
desc = "(";
Iterator<FormalParameter> itr = constructor.getParameterList().iterator();
while(itr.hasNext()) {
FormalParameter fp = itr.next();
desc = desc + "L"+fp.getType().toString().replace(".", "/") + ";";
}
desc = desc + ")V";
}
public Descriptor(ArgumentList argList, RefTypeOrTPHOrWildcardOrGeneric returnType) {
desc = "(";
for(Expression e : argList.getArguments()) {
desc = desc + "L"+e.getType().toString().replace(".", "/") + ";";
}
desc = desc + ")"+returnType.toString();
}
public String getDesc() {
return this.desc;
}
}

View File

@ -1,150 +0,0 @@
package de.dhbwstuttgart.bytecode;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
public class Test {
private static final String rootDirectory = System.getProperty("user.dir") + "/bin/de/dhbwstuttgart/bytecode/";
protected static ClassLoader getClassLoader() throws Exception {
File file = new File(rootDirectory);
URL url = file.toURI().toURL();
URL[] urls = new URL[] { url };
System.out.println(urls[0]);
return new URLClassLoader(urls);
}
public static void main(String[] args) {
// Test Lambda
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, "TestClass", null, "java/lang/Object", null);
cw.visitSource("TestClass.java", null);
// Create Constructor
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
// mv.visitMethodInsn(INVOKEDYNAMIC, "#0", "run", "()Ljava/lang/Runnable");
//Call site, which, when invoked, returns an instance of the functional interface to which
//the lambda is being converted
MethodType mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class,
MethodType.class, MethodType.class, MethodHandle.class, MethodType.class);
Handle bootstrap = new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory",
mt.toMethodDescriptorString());
Handle arg2 = new Handle(Opcodes.H_INVOKESTATIC, "TestClass", "lambda$0", "()V");
mv.visitInvokeDynamicInsn("run", "()Ljava/lang/Runnable;", bootstrap,
Type.getMethodType("()V"), arg2,
Type.getMethodType("()V"));
mv.visitVarInsn(Opcodes.ASTORE, 1);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/lang/Runnable", "run", "()V");
mv.visitInsn(Opcodes.RETURN);
// creates bridge method, contains lambdas body
MethodVisitor mvl = cw.visitMethod(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_SYNTHETIC, "lambda$0",
"()V", null, null);
mvl.visitCode();
mvl.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
mvl.visitLdcInsn("lambda");
mvl.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
mvl.visitInsn(Opcodes.RETURN);
mvl.visitMaxs(2, 0);
mvl.visitEnd();
mv.visitMaxs(1, 2);
mv.visitEnd();
cw.visitInnerClass("java/lang/invoke/MethodHandles$Lookup", "java/lang/invoke/MethodHandles", "Lookup",
Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL);
cw.visitEnd();
byte[] b = cw.toByteArray();
// Test if statement
/*
* ClassWriter cw = new
* ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS);
*
* cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC+Opcodes.ACC_SUPER, "TestIf", null,
* "java/lang/Object", null); MethodVisitor mv =
* cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "(Ljava/lang/Boolean;)V", null,
* null); mv.visitCode();
*
* // Label l0 = new Label(); // mv.visitLabel(l0);
*
* mv.visitVarInsn(Opcodes.ALOAD, 0);
*
* mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>",
* "()V");
*
* // Label l1 = new Label(); // mv.visitLabel(l1);
* mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
* "java/lang/Boolean", "booleanValue", "()Z");
*
* Label label = new Label(); mv.visitJumpInsn(Opcodes.IFEQ, label);
*
* mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out",
* "Ljava/io/PrintStream;"); mv.visitLdcInsn("1");
* mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println",
* "(Ljava/lang/String;)V");
*
* Label endLabel = new Label(); mv.visitJumpInsn(Opcodes.GOTO, endLabel);
*
* mv.visitLabel(label); mv.visitFieldInsn(Opcodes.GETSTATIC,
* "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("0");
* mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println",
* "(Ljava/lang/String;)V");
*
*
*
* mv.visitLabel(endLabel); mv.visitInsn(Opcodes.RETURN);
*
* // Label l2 = new Label(); // mv.visitLabel(l2);
*
* // mv.visitLocalVariable("this", "LTestIf;", null, l0, l2, 0); //
* mv.visitLocalVariable("b", "Ljava/lang/Boolean;", null, l0, l2, 1);
* mv.visitMaxs(2, 2); mv.visitEnd();
*
* cw.visitEnd(); byte[] b = cw.toByteArray();
*/
FileOutputStream output;
try {
output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/TestClass.class"));
output.write(b);
output.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -1,8 +0,0 @@
package de.dhbwstuttgart.bytecode;
public class TestClass {
public TestClass() {
Runnable lam = () -> System.out.println("lambda");
lam.run();
}
}

View File

@ -1,59 +0,0 @@
package de.dhbwstuttgart.bytecode;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
public class TestFields {
private static final String rootDirectory = System.getProperty("user.dir") + "/bin/de/dhbwstuttgart/bytecode/";
public static void main(String[] args) {
// TODO Auto-generated method stub
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS);
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, "TetsF", null, "java/lang/Object", null);
cw.visitSource("TetsF.java", null);
FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE, "z", Type.INT_TYPE.getDescriptor(), null, null);
fv.visitEnd();
FieldVisitor fvS = cw.visitField(Opcodes.ACC_PUBLIC, "s", "Ljava/lang/String;", null, null);
fvS.visitEnd();
// Create Constructor
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitLdcInsn("");
mv.visitFieldInsn(Opcodes.PUTFIELD, "TetsF", "s", "Ljava/lang/String;");
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(2, 1);
mv.visitEnd();
byte[] b = cw.toByteArray();
FileOutputStream output;
try {
output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/TetsF.class"));
output.write(b);
output.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -1,11 +0,0 @@
package de.dhbwstuttgart.bytecode;
public class TestIf {
public TestIf(Boolean b) {
if(b) {
System.out.println("1");
}else {
System.out.println("0");
}
}
}

View File

@ -1,18 +0,0 @@
package de.dhbwstuttgart.bytecode;
public class TestMeth {
private int z;
public String s;
public TestMeth(int temp) {
this.z = temp;
}
public void m1(int a, int b) {
int y = m2(1,2,3,4);
}
public int m2(int a, int b, int x, int y) {
Integer c = 55;
Integer g;
return a+b+y+c;
}
}

View File

@ -1,6 +0,0 @@
package de.dhbwstuttgart.bytecode;
public class TetsF {
private int z;
public String s = "";
}

View File

@ -1,16 +0,0 @@
package de.dhbwstuttgart.core;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
public class ConsoleInterface {
private static final String directory = System.getProperty("user.dir");
public static void main(String[] args) throws IOException, ClassNotFoundException {
List<File> input = Arrays.asList(args).stream().map((s -> new File(s))).collect(Collectors.toList());
JavaTXCompiler compiler = new JavaTXCompiler(input);
compiler.typeInference();
}
}

View File

@ -1,103 +0,0 @@
package de.dhbwstuttgart.core;
import de.dhbwstuttgart.environment.CompilationEnvironment;
import de.dhbwstuttgart.parser.JavaTXParser;
import de.dhbwstuttgart.parser.scope.GenericsRegistry;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.SyntaxTreeGenerator;
import de.dhbwstuttgart.parser.antlr.Java8Parser.CompilationUnitContext;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.typeAlgo.TYPE;
import de.dhbwstuttgart.typeinference.unify.TypeUnify;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
public class JavaTXCompiler {
final CompilationEnvironment environment;
public final Map<File, SourceFile> sourceFiles = new HashMap<>();
public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException {
this(Arrays.asList(sourceFile));
}
public JavaTXCompiler(List<File> sources) throws IOException, ClassNotFoundException {
environment = new CompilationEnvironment(sources);
for(File s : sources){
sourceFiles.put(s,parse(s));
}
}
public List<ResultSet> typeInference() throws ClassNotFoundException {
List<ClassOrInterface> allClasses = new ArrayList<>();//environment.getAllAvailableClasses();
for(SourceFile sf : sourceFiles.values()){
allClasses.addAll(sf.getClasses());
}
List<ClassOrInterface> importedClasses = new ArrayList<>();
//Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC
for(File forSourceFile : sourceFiles.keySet())
for(JavaClassName name : sourceFiles.get(forSourceFile).getImports()){
ClassOrInterface importedClass = ASTFactory.createClass(
ClassLoader.getSystemClassLoader().loadClass(name.toString()));
importedClasses.add(importedClass);
}
allClasses.addAll(importedClasses);
FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses);
final ConstraintSet<Pair> cons = new TYPE(sourceFiles.values(), allClasses).getConstraints();
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons);
TypeUnify unify = new TypeUnify();
Set<Set<UnifyPair>> results = new HashSet<>();
for(List<Constraint<UnifyPair>> xCons : unifyCons.cartesianProduct()){
Set<UnifyPair> xConsSet = new HashSet<>();
for(Constraint<UnifyPair> constraint : xCons){
xConsSet.addAll(constraint);
}
//System.out.println(xConsSet);
Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
//System.out.println("RESULT: " + result);
results.addAll(result);
}
return results.stream().map((unifyPairs ->
new ResultSet(UnifyTypeFactory.convert(unifyPairs, generateTPHMap(cons))))).collect(Collectors.toList());
}
private Map<String, TypePlaceholder> generateTPHMap(ConstraintSet<Pair> constraints){
HashMap<String, TypePlaceholder> ret = new HashMap<>();
constraints.map((Pair p)->{
if(p.TA1 instanceof TypePlaceholder){
ret.put(((TypePlaceholder)p.TA1).getName(), (TypePlaceholder) p.TA1);
}
if(p.TA2 instanceof TypePlaceholder){
ret.put(((TypePlaceholder)p.TA2).getName(), (TypePlaceholder) p.TA2);
}
return null;
});
return ret;
}
private SourceFile parse(File sourceFile) throws IOException, java.lang.ClassNotFoundException {
CompilationUnitContext tree = JavaTXParser.parse(sourceFile);
SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(sourceFile), new GenericsRegistry(null));
SourceFile ret = generator.convert(tree);
return ret;
}
}

View File

@ -1,63 +0,0 @@
package de.dhbwstuttgart.environment;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
import de.dhbwstuttgart.exceptions.DebugException;
import de.dhbwstuttgart.parser.JavaTXParser;
import de.dhbwstuttgart.parser.antlr.Java8Parser.CompilationUnitContext;
import de.dhbwstuttgart.parser.scope.GatherNames;
import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
/**
* Stellt die Java-Environment dar und speichert alle Binarys, Librarys und Sourcefiles im zu kompilierenden Projekt
* Sie erstellt anhand dieser Informationen die JavaClassNameRegistry
*
* TODO: Zur Initialisierung der CompilationEnvironment sollten alle SourceFiles mit ANTLR geparst werden und alle Klassen Generics und Typen herausgefunden werden
*/
public class CompilationEnvironment {
private final List<URL> librarys;
private final List<File> sourceFiles;
/**
* Imitiert die Environment beim Aufruf des JavaCompilers auf einer Menge von java-Dateien
* Die Environment enth<EFBFBD>lt automatisch die Java Standard Library
* @param sourceFiles die zu kompilierenden Dateien
*/
public CompilationEnvironment(List<File> sourceFiles) {
String bootClassPath = System.getProperty("sun.boot.class.path");
librarys = new ArrayList<>();
for(String path : bootClassPath.split(File.pathSeparator)) {
try {
librarys.add(new URL("file:"+path));
} catch (MalformedURLException e) {
new DebugException("Fehler im Classpath auf diesem System");
}
}
this.sourceFiles = sourceFiles;
}
public JavaClassRegistry getRegistry(File forSourceFile) throws ClassNotFoundException, IOException {
List<String> allNames;
CompilationUnitContext tree = JavaTXParser.parse(forSourceFile);
allNames = GatherNames.getNames(tree, new PackageCrawler(librarys));
return new JavaClassRegistry(allNames);
}
}

View File

@ -1,22 +0,0 @@
package de.dhbwstuttgart.parser.scope;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.GenericContext;
public class GenericTypeName extends JavaClassName {
private final static String DELIMITER = "%";
private final JavaClassName parentClass;
private final String methodName;
public GenericTypeName(GenericContext genericContext, String name) {
super(name);
this.parentClass = genericContext.parentClass;
this.methodName = genericContext.parentMethod;
}
public String getUniqueIdentifier() {
return parentClass.toString()
+ DELIMITER + methodName
+ DELIMITER + super.toString();
}
}

View File

@ -1,34 +0,0 @@
package de.dhbwstuttgart.syntaxtree;
import org.antlr.v4.runtime.Token;
import java.util.*;
/**
* Stellt eine Deklarations-Liste von Generischen Variablen dar.
* Kann vor Methoden und Klassen auftauchen. (<....>)
* @author janulrich
*
*/
public class GenericDeclarationList extends SyntaxTreeNode implements Iterable<GenericTypeVar>{
private Token offsetOfLastElement;
private List<GenericTypeVar> gtvs = new ArrayList<>();
public GenericDeclarationList(List<GenericTypeVar> values, Token endOffset) {
super(endOffset);
gtvs = values;
this.offsetOfLastElement = endOffset;
}
@Override
public Iterator<GenericTypeVar> iterator() {
return gtvs.iterator();
}
@Override
public void accept(ASTVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -1,27 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation;
// neu von Felix
public class Binary extends Expression
{
public enum Operator{
ADD,
SUB,
MUL,
AND, OR, DIV
}
public Binary(Expression expr1, Expression expr2, Operator op){
super(null, null);
}
@Override
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -1,14 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import org.antlr.v4.runtime.Token;
public abstract class BinaryExpr extends Expression
{
public BinaryExpr(Token offset)
{
super(null,null);
}
}

View File

@ -1,18 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import java.util.Hashtable;
import java.util.Iterator;
import org.antlr.v4.runtime.Token;
public class NegativeExpr extends UnaryExpr
{
public NegativeExpr(Token offset)
{
super(offset);
}
private UnaryMinus neg;
public Expression expr;
}

View File

@ -1,14 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import org.antlr.v4.runtime.Token;
public class NotExpr extends UnaryExpr
{
public NotExpr(Token offset)
{
super(offset);
}
private UnaryNot not;
public Expression expr;
}

View File

@ -1,15 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import org.antlr.v4.runtime.Token;
public class PositivExpr extends UnaryExpr
{
public PositivExpr(Token offset)
{
super(offset);
}
protected UnaryPlus plus;
public Expression expr;
}

View File

@ -1,17 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import java.util.Hashtable;
import java.util.Iterator;
import de.dhbwstuttgart.parser.antlr.Java8Parser;
public class PostDecExpr extends PostIncExpr
{
public PostDecExpr(Expression expr) {
super(expr);
}
}

View File

@ -1,15 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation;
import de.dhbwstuttgart.exceptions.NotImplementedException;
public class PostIncExpr extends UnaryExpr
{
public PostIncExpr(Expression expr) {
super(null);
}
}

View File

@ -1,17 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import java.util.Hashtable;
import java.util.Iterator;
import org.antlr.v4.runtime.Token;
public class PreDecExpr extends UnaryExpr
{
public PreDecExpr(Token offset)
{
super(offset);
}
}

View File

@ -1,12 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import org.antlr.v4.runtime.Token;
public class PreIncExpr extends UnaryExpr
{
public PreIncExpr(Token offset)
{
super(offset);
}
}

View File

@ -1,26 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation;
public class Receiver extends Expression
{
public Expression expr;
/**
* Autor: ¯Â¿Â½rg ¯Â¿Â½uerle
* @param expr
*/
public Receiver(Expression expr)
{
super(expr.getType(), expr.getOffset());
this.expr = expr;
}
@Override
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -1,28 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.Void;
import org.antlr.v4.runtime.Token;
import de.dhbwstuttgart.syntaxtree.SyntaxTreeNode;
import java.util.ArrayList;
public class SuperCall extends MethodCall
{
public SuperCall(Token offset){
this(new ArgumentList(new ArrayList<Expression>(), offset),offset);
}
public SuperCall(ArgumentList argumentList, Token offset){
super(new Void(offset), new Receiver(new This(offset)), "<init>", argumentList, offset);
}
@Override
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -1,14 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import org.antlr.v4.runtime.Token;
public abstract class UnaryExpr extends MethodCall
{
public Expression expr;
public UnaryExpr(Token offset)
{
super(null,null,null,null,null);
}
}

View File

@ -1,12 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import de.dhbwstuttgart.syntaxtree.SyntaxTreeNode;
public class UnaryMinus extends UnaryPlus
{
public UnaryMinus(Expression expression) {
super(expression);
}
}

View File

@ -1,7 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
public class UnaryNot
{
}

View File

@ -1,20 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation;
import de.dhbwstuttgart.exceptions.NotImplementedException;
public class UnaryPlus extends Expression
{
public UnaryPlus(Expression expression){
super(expression.getType(),expression.getOffset());
}
@Override
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -1,26 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement.literal;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import org.antlr.v4.runtime.Token;
public class BoolLiteral extends Literal
{
private boolean value;
public BoolLiteral(RefTypeOrTPHOrWildcardOrGeneric type, boolean value, Token offset)
{
super(type,offset);
this.value = value;
}
@Override
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -1,21 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement.literal;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import org.antlr.v4.runtime.Token;
public class CharLiteral extends Literal
{
private char value;
public CharLiteral(RefTypeOrTPHOrWildcardOrGeneric type, char value, Token offset)
{
super(type,offset);
this.value = value;
}
@Override
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -1,19 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement.literal;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import org.antlr.v4.runtime.Token;
public abstract class Literal extends Expression
{
public Literal(RefTypeOrTPHOrWildcardOrGeneric type, Token offset) {
super(type, offset);
}
public ConstraintSet getConstraints(TypeInferenceBlockInformation info){
return new ConstraintSet();
}
}

View File

@ -1,22 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement.literal;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import org.antlr.v4.runtime.Token;
public class NumberLiteral extends Literal
{
private Number value;
public NumberLiteral(RefTypeOrTPHOrWildcardOrGeneric type, Number value, Token offset)
{
super(type,offset);
this.value = value;
}
@Override
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -1,23 +0,0 @@
package de.dhbwstuttgart.syntaxtree.statement.literal;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import org.antlr.v4.runtime.Token;
public class StringLiteral extends Literal
{
private String value;
public StringLiteral(RefType type, String value, Token offset)
{
super(type,offset);
this.value = value;
}
@Override
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -1,41 +0,0 @@
package de.dhbwstuttgart.syntaxtree.type;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import java.util.List;
/**
* @see Spezifikation "Complete Typeinference in Java 8" von Martin Plümicke
* "interface FunN<R,T1, T2, ... ,TN> { R apply(T1 arg1, T2 arg2, ... , TN argN); }"
* @author A10023 - Andreas Stadelmeier
*
* Bemerkung:
* FunN ist ein RefType. Der RefType ist nicht mit einem FunNInterface verbunden.
*
*/
public class FunN extends RefType {
/**
* @author Andreas Stadelmeier, a10023
* BenÃtigt ¼r den Typinferenzalgorithmus ¼r Java 8
* Generiert einen RefType auf eine FunN<R,T1,...,TN> - Klasse.
* @param params
* @return
*/
public FunN(List<RefTypeOrTPHOrWildcardOrGeneric> params) {
super(new JavaClassName("Fun"+params.size()), params, new NullToken());
}
/**
* Spezieller Konstruktor um eine FunN ohne Returntype zu generieren
protected FunN(List<? extends Type> list){
super("",0);
if(list==null)throw new NullPointerException();
setT(list);
this.name = new JavaClassName("Fun"+list.size());//getName();
}
*/
}

View File

@ -1,36 +0,0 @@
package de.dhbwstuttgart.typedeployment;
import org.antlr.v4.runtime.Token;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TypeInsert {
/**
* point wird hauptsächlich zur Anzeige einer Annotation im Eclipse-plugin benutzt.
*/
public final TypeInsertPoint point;
Set<TypeInsertPoint> inserts;
public TypeInsert(TypeInsertPoint point, Set<TypeInsertPoint> additionalPoints){
this.point = point;
inserts = additionalPoints;
}
public String insert(String intoSource){
List<TypeInsertPoint> offsets = new ArrayList<>();
String ret = point.insert(intoSource, offsets);
offsets.add(point);
for(TypeInsertPoint insertPoint : inserts){
ret = insertPoint.insert(ret, offsets);
offsets.add(insertPoint);
}
return ret;
}
public String getInsertString(){
return point.getInsertString();
}
}

View File

@ -1,142 +0,0 @@
package de.dhbwstuttgart.typedeployment;
import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.typeinference.result.*;
import org.antlr.v4.runtime.Token;
import java.util.*;
/**
* TODO:
* Falls in Feldern Generics entstehen, dann werden diese als Klassenparameter eingesetzt
* Für die Instanzierung von Klassen kann man dann beispielsweise nur noch den Diamond-Operator verwenden
*
* Es müssen zu einem TPH alle in Beziehung stehenden Constraints gefunden werden
*
* Anmekung: Es wird nur ein RefType gleichzeitug eingesetzt.
* Steht dieser mit anderen Typen in Verbindung, so müssen diese nicht eingesetzt werden
* im Result set können nur TPHs mit <. Beziehung stehen
* Steht ein Typ A über TPHs mit anderen Typen B in Verbindung, so lassen sich diese auch im nächsten Durchgang
* inferieren, wenn A bereits eingesetzt wurde. Es werden dann eben zusätzliche Generics entstehen
*/
public class TypeInsertFactory {
public static Set<TypeInsert> createTypeInsertPoints(SourceFile forSourcefile, ResultSet withResults){
return new TypeInsertPlacer().getTypeInserts(forSourcefile, withResults);
}
public static TypeInsert createInsertPoints(RefTypeOrTPHOrWildcardOrGeneric type, Token offset, ClassOrInterface cl, Method m,
ResultSet resultSet) {
Set<TypeInsertPoint> ret = new HashSet<>();
ResolvedType resolvedType = resultSet.resolveType(type);
TypeInsertPoint insertPoint = new TypeInsertPoint(offset,
new TypeToInsertString(resolvedType.resolvedType).insert);
return new TypeInsert(insertPoint, new HashSet<>(Arrays.asList(createGenericInsert(resolvedType.additionalGenerics, cl, m))));
}
private static TypeInsertPoint createGenericInsert(Set<GenericInsertPair> toInsert, ClassOrInterface cl, Method m){
//Momentan wird Methode ignoriert. Parameter werden immer als Klassenparameter angefügt:
//Offset zum Einstzen bestimmen:
Token offset;
String insert = "";
String end;
if(cl.getGenerics().iterator().hasNext()){
//offset = cl.getGenerics().iterator().next().getOffset();
offset = cl.getGenerics().getOffset();
end=",";
}else{
offset = cl.getGenerics().getOffset();
insert += "<";
end = ">";
}
//Alle einzusetzenden Generics und deren Bounds bestimmen:
HashMap<TypePlaceholder, HashSet<TypePlaceholder>> genericsAndBounds = new HashMap<>();
for(GenericInsertPair p : toInsert){
if(!genericsAndBounds.containsKey(p.TA1)){
genericsAndBounds.put((TypePlaceholder) p.TA1, new HashSet<>());
}
if(p.TA2 != null){
genericsAndBounds.get(p.TA1).add((TypePlaceholder) p.TA2);
if(!genericsAndBounds.containsKey(p.TA2)){
genericsAndBounds.put((TypePlaceholder) p.TA2, new HashSet<>());
}
}
}
//String zum Einsetzen (Generics mit bounds) generieren:
Iterator<TypePlaceholder> it = genericsAndBounds.keySet().iterator();
if(! it.hasNext())return new TypeInsertPoint(offset, "");
while(it.hasNext()){
TypePlaceholder tph = it.next();
insert += tph.getName();
Set<TypePlaceholder> bounds = genericsAndBounds.get(tph);
if(bounds.size() > 0){
insert += " extends ";
Iterator<TypePlaceholder> boundIt = bounds.iterator();
while(boundIt.hasNext()){
TypePlaceholder bound = boundIt.next();
insert += bound.getName();
if(boundIt.hasNext())insert += " & ";
}
}
if(it.hasNext())insert+=",";
}
return new TypeInsertPoint(offset, insert + end);
}
}
class TypeToInsertString implements ResultSetVisitor{
String insert = "";
TypeToInsertString(RefTypeOrTPHOrWildcardOrGeneric type){
type.accept(this);
}
@Override
public void visit(PairTPHsmallerTPH p) {
}
@Override
public void visit(PairTPHequalRefType p) {
}
@Override
public void visit(RefType resolved) {
insert = resolved.getName().toString();
if(resolved.getParaList().size() > 0){
insert += "<";
Iterator<RefTypeOrTPHOrWildcardOrGeneric> iterator = resolved.getParaList().iterator();
while(iterator.hasNext()){
RefTypeOrTPHOrWildcardOrGeneric typeParam = iterator.next();
insert += new TypeToInsertString(typeParam).insert;
if(iterator.hasNext())insert += ", ";
}
insert += ">";
}
}
@Override
public void visit(GenericRefType genericRefType) {
insert += genericRefType.getName();
}
@Override
public void visit(SuperWildcardType superWildcardType) {
insert += "? super " + new TypeToInsertString(superWildcardType.getInnerType()).insert;
}
@Override
public void visit(TypePlaceholder typePlaceholder) {
insert += typePlaceholder.getName();
}
@Override
public void visit(ExtendsWildcardType extendsWildcardType) {
insert += "? extends " + new TypeToInsertString(extendsWildcardType.getInnerType()).insert;
}
}

View File

@ -1,28 +0,0 @@
package de.dhbwstuttgart.typedeployment;
import org.antlr.v4.runtime.Token;
import java.util.List;
import java.util.stream.Collectors;
public class TypeInsertPoint {
public final Token point;
private String insertString;
public TypeInsertPoint(Token point, String toInsert){
this.point = point;
this.insertString = (toInsert.endsWith(" ")) ? toInsert : toInsert + " " ;
}
public String insert(String intoSource, List<TypeInsertPoint> additionalOffset){
int offset = additionalOffset.stream().filter((token ->
//token.point.getLine() != point.getLine() && token.point.getCharPositionInLine() <= point.getCharPositionInLine()))
token.point.getStartIndex() <= point.getStartIndex()))
.mapToInt((typeInsertPoint -> typeInsertPoint.insertString.length())).sum();
return new StringBuilder(intoSource).insert(point.getStartIndex()+offset, insertString).toString();
}
public String getInsertString() {
return insertString;
}
}

View File

@ -1,24 +0,0 @@
package de.dhbwstuttgart.typeinference.assumptions;
import de.dhbwstuttgart.syntaxtree.TypeScope;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
public class FieldAssumption extends Assumption{
private RefTypeOrTPHOrWildcardOrGeneric receiverType;
private RefTypeOrTPHOrWildcardOrGeneric type;
public FieldAssumption(RefTypeOrTPHOrWildcardOrGeneric receiverType,
RefTypeOrTPHOrWildcardOrGeneric type, TypeScope scope){
super(scope);
this.type = type;
this.receiverType = receiverType;
}
public RefTypeOrTPHOrWildcardOrGeneric getReceiverType() {
return receiverType;
}
public RefTypeOrTPHOrWildcardOrGeneric getType() {
return type;
}
}

View File

@ -1,36 +0,0 @@
package de.dhbwstuttgart.typeinference.assumptions;
import de.dhbwstuttgart.syntaxtree.ParameterList;
import de.dhbwstuttgart.syntaxtree.TypeScope;
import de.dhbwstuttgart.syntaxtree.statement.Assign;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import java.util.List;
import java.util.stream.Collectors;
public class MethodAssumption extends Assumption{
private RefType receiver;
private RefTypeOrTPHOrWildcardOrGeneric retType;
List<RefTypeOrTPHOrWildcardOrGeneric> params;
public MethodAssumption(RefType receiver, RefTypeOrTPHOrWildcardOrGeneric retType,
List<RefTypeOrTPHOrWildcardOrGeneric> params, TypeScope scope){
super(scope);
this.receiver = receiver;
this.retType = retType;
this.params = params;
}
public RefType getReceiverType() {
return receiver;
}
public RefTypeOrTPHOrWildcardOrGeneric getReturnType() {
return retType;
}
public List<RefTypeOrTPHOrWildcardOrGeneric> getArgTypes() {
return params;
}
}

View File

@ -1,10 +0,0 @@
package de.dhbwstuttgart.typeinference.constraints;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Constraint<A> extends HashSet<A> {
}

View File

@ -1,55 +0,0 @@
package de.dhbwstuttgart.typeinference.constraints;
import de.dhbwstuttgart.typeinference.unify.GuavaSetOperations;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ConstraintSet<A> {
Constraint<A> undConstraints = new Constraint<>();
List<Set<Constraint<A>>> oderConstraints = new ArrayList<>();
public void addUndConstraint(A p){
undConstraints.add(p);
}
public void addOderConstraint(Set<Constraint<A>> methodConstraints) {
oderConstraints.add(methodConstraints);
}
public void addAll(ConstraintSet constraints) {
this.undConstraints.addAll(constraints.undConstraints);
this.oderConstraints.addAll(constraints.oderConstraints);
}
@Override
public String toString(){
return cartesianProduct().toString();
}
public Set<List<Constraint<A>>> cartesianProduct(){
Set<Constraint<A>> toAdd = new HashSet<>();
toAdd.add(undConstraints);
List<Set<Constraint<A>>> allConstraints = new ArrayList<>();
allConstraints.add(toAdd);
allConstraints.addAll(oderConstraints);
return new GuavaSetOperations().cartesianProduct(allConstraints);
}
public <B> ConstraintSet<B> map(Function<? super A,? extends B> o) {
ConstraintSet<B> ret = new ConstraintSet<>();
ret.undConstraints = undConstraints.stream().map(o).collect(Collectors.toCollection(Constraint<B>::new));
List<Set<Constraint<B>>> newOder = new ArrayList<>();
for(Set<Constraint<A>> oderConstraint : oderConstraints){
newOder.add(
oderConstraint.parallelStream().map((Constraint<A> as) ->
as.stream().map(o).collect(Collectors.toCollection(Constraint<B>::new))).collect(Collectors.toSet())
);
}
ret.oderConstraints = newOder;
return ret;
}
}

View File

@ -1,58 +0,0 @@
package de.dhbwstuttgart.typeinference.constraints;
import de.dhbwstuttgart.exceptions.DebugException;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.TypeScope;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ConstraintsFactory {
public static Pair createPair(RefTypeOrTPHOrWildcardOrGeneric t1, RefTypeOrTPHOrWildcardOrGeneric t2,
PairOperator equalsdot, TypeScope currentScope, TypeScope additionalScope,
GenericsResolver resolver){
//Check whether Generics are in the same class and resolve all other generics:
return new Pair(checkGeneric(t1, currentScope, additionalScope,resolver),
checkGeneric(t2, currentScope,additionalScope, resolver), equalsdot);
}
public static Pair createPair(RefTypeOrTPHOrWildcardOrGeneric t1,
RefTypeOrTPHOrWildcardOrGeneric t2, TypeScope currentScope, TypeScope additionalScope,
GenericsResolver resolver){
return createPair(t1,t2,PairOperator.SMALLERDOT, currentScope, additionalScope, resolver);
}
private static RefTypeOrTPHOrWildcardOrGeneric checkGeneric(RefTypeOrTPHOrWildcardOrGeneric type,
TypeScope currentScope, TypeScope additionalScope,
GenericsResolver resolver){
if(type instanceof GenericRefType){
//TODO: Für Generics müssen auch noch Constraints generiert werden
for(GenericTypeVar genericTypeVar : currentScope.getGenerics()){
if(genericTypeVar.getName().toString().equals(((GenericRefType)type).getName().toString())){
return new RefType(((GenericRefType)type).getName(),type.getOffset());
}
}
//Nicht in den Generics in diesem Kontext enthalten:
TypePlaceholder ret = null;
for(GenericTypeVar genericTypeVar : additionalScope.getGenerics()){
if(genericTypeVar.getName().equals(((GenericRefType)type).getName())){
ret = resolver.resolve(genericTypeVar);
}
}
if(ret == null)
throw new DebugException("Der Generic " + ((GenericRefType) type).getName() + " kommt in keine TypeScope vor!");
return ret;
}else{
return type;
}
}
}

View File

@ -1,26 +0,0 @@
package de.dhbwstuttgart.typeinference.result;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
/**
* Paare, welche das Unifikationsergebnis darstellen
*/
public abstract class ResultPair {
private final RefTypeOrTPHOrWildcardOrGeneric left;
private final RefTypeOrTPHOrWildcardOrGeneric right;
public abstract void accept(ResultSetVisitor visitor);
public ResultPair(RefTypeOrTPHOrWildcardOrGeneric left, RefTypeOrTPHOrWildcardOrGeneric right){
this.left = left;
this.right = right;
}
public RefTypeOrTPHOrWildcardOrGeneric getLeft() {
return left;
}
public RefTypeOrTPHOrWildcardOrGeneric getRight() {
return right;
}
}

View File

@ -1,382 +0,0 @@
package de.dhbwstuttgart.typeinference.typeAlgo;
//import com.sun.org.apache.xpath.internal.Arg;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.exceptions.TypeinferenceException;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.statement.*;
import de.dhbwstuttgart.syntaxtree.statement.literal.Literal;
import de.dhbwstuttgart.syntaxtree.statement.literal.Null;
import de.dhbwstuttgart.syntaxtree.type.FunN;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.assumptions.FieldAssumption;
import de.dhbwstuttgart.typeinference.assumptions.MethodAssumption;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
import de.dhbwstuttgart.typeinference.constraints.*;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import java.util.*;
import java.util.stream.Collectors;
public class TYPEStmt implements StatementVisitor{
private final TypeInferenceBlockInformation info;
private final ConstraintSet constraintsSet = new ConstraintSet();
public TYPEStmt(TypeInferenceBlockInformation info){
this.info = info;
}
public ConstraintSet getConstraints() {
return constraintsSet;
}
private static GenericsResolver getResolverInstance(){
Map<GenericTypeVar, TypePlaceholder> map = new HashMap<>();
return generic -> {
if(map.containsKey(generic))return map.get(generic);
TypePlaceholder ret = TypePlaceholder.fresh(generic.getOffset());
map.put(generic, ret);
return ret;
};
}
private static TypeScope createTypeScope(ClassOrInterface cl, Method method) {
return null;
}
@Override
public void visit(ArgumentList arglist) {
for(int i = 0;i<arglist.getArguments().size();i++){
arglist.getArguments().get(i).accept(this);
}
}
@Override
public void visit(LambdaExpression lambdaExpression) {
TypePlaceholder tphRetType = TypePlaceholder.fresh(new NullToken());
List<RefTypeOrTPHOrWildcardOrGeneric> lambdaParams = lambdaExpression.params.getFormalparalist().stream().map((formalParameter -> formalParameter.getType())).collect(Collectors.toList());
//lambdaParams.add(tphRetType);
lambdaParams.add(0,tphRetType);
constraintsSet.addUndConstraint(
ConstraintsFactory.createPair(lambdaExpression.getType(),
new FunN(lambdaParams),PairOperator.EQUALSDOT,info.getCurrentTypeScope(), createNullTypeScope(), getResolverInstance()));
constraintsSet.addUndConstraint(
ConstraintsFactory.createPair(lambdaExpression.getReturnType(),
tphRetType,info.getCurrentTypeScope(), createNullTypeScope(), getResolverInstance()));
//Constraints des Bodys generieren:
TYPEStmt lambdaScope = new TYPEStmt(new TypeInferenceBlockInformation(info, lambdaExpression));
lambdaExpression.methodBody.accept(lambdaScope);
constraintsSet.addAll(lambdaScope.getConstraints());
}
@Override
public void visit(Assign assign) {
assign.lefSide.accept(this);
assign.rightSide.accept(this);
constraintsSet.addUndConstraint(ConstraintsFactory.createPair(
assign.rightSide.getType(), assign.lefSide.getType(), PairOperator.SMALLERDOT, info.getCurrentTypeScope(), createNullTypeScope(), getResolverInstance()));
}
@Override
public void visit(Binary binary) {
throw new NotImplementedException();
}
@Override
public void visit(Block block) {
for(Statement stmt : block.getStatements()){
stmt.accept(this);
}
}
@Override
public void visit(CastExpr castExpr) {
throw new NotImplementedException();
}
@Override
public void visit(EmptyStmt emptyStmt) {
//Nothing :)
}
@Override
public void visit(FieldVar fieldVar) {
fieldVar.receiver.accept(this);
Set<Constraint> oderConstraints = new HashSet<>();
for(FieldAssumption fieldAssumption : info.getFields(fieldVar.fieldVarName)){
Constraint constraint = new Constraint();
GenericsResolver resolver = getResolverInstance();
constraint.add(ConstraintsFactory.createPair(
fieldVar.receiver.getType(),fieldAssumption.getReceiverType(), info.getCurrentTypeScope(), fieldAssumption.getTypeScope(), resolver));
constraint.add(ConstraintsFactory.createPair(
fieldVar.getType(),fieldAssumption.getType(), info.getCurrentTypeScope(), fieldAssumption.getTypeScope(), resolver));
oderConstraints.add(constraint);
}
if(oderConstraints.size() == 0)
throw new TypeinferenceException("Kein Feld "+fieldVar.fieldVarName+ " gefunden", fieldVar.getOffset());
constraintsSet.addOderConstraint(oderConstraints);
}
@Override
public void visit(ForStmt forStmt) {
throw new NotImplementedException();
}
@Override
public void visit(IfStmt ifStmt) {
throw new NotImplementedException();
}
@Override
public void visit(InstanceOf instanceOf) {
throw new NotImplementedException();
}
@Override
public void visit(LocalVar localVar) {
// Es werden nur bei Feldvariablen Constraints generiert. Lokale Variablen sind eindeutig
}
@Override
public void visit(LocalVarDecl localVarDecl) {
//Hier ist nichts zu tun. Allen lokalen Variablen bekommen beim parsen schon den korrekten Typ
}
@Override
public void visit(MethodCall methodCall) {
methodCall.receiver.accept(this);
//Overloading:
Set<Constraint> methodConstraints = new HashSet<>();
for(MethodAssumption m : this.getMethods(methodCall.name, methodCall.arglist, info)){
GenericsResolver resolver = getResolverInstance();
TypeScope additionalScope = m.getTypeScope();
methodConstraints.add(generateConstraint(methodCall, m, info, getResolverInstance()));
}
if(methodConstraints.size()<1){
throw new TypeinferenceException("Methode "+methodCall.name+" ist nicht vorhanden!",methodCall.getOffset());
}
constraintsSet.addOderConstraint(methodConstraints);
}
@Override
public void visit(NewClass methodCall) {
//Overloading:
Set<Constraint> methodConstraints = new HashSet<>();
for(MethodAssumption m : this.getConstructors(info, (RefType) methodCall.getType(), methodCall.getArgumentList())){
methodConstraints.add(generateConstructorConstraint(methodCall, m, info, getResolverInstance()));
}
if(methodConstraints.size()<1){
throw new TypeinferenceException("Konstruktor in Klasse "+methodCall.getType().toString()+" ist nicht vorhanden!",methodCall.getOffset());
}
constraintsSet.addOderConstraint(methodConstraints);
}
@Override
public void visit(NewArray newArray) {
throw new NotImplementedException();
}
@Override
public void visit(Receiver receiver) {
receiver.expr.accept(this);
}
@Override
public void visit(Return returnExpr) {
returnExpr.retexpr.accept(this);
constraintsSet.addUndConstraint(ConstraintsFactory.createPair(
returnExpr.getType(),info.getCurrentTypeScope().getReturnType(), PairOperator.EQUALSDOT,
info.getCurrentTypeScope(), createNullTypeScope(), getResolverInstance()));
}
@Override
public void visit(ReturnVoid aReturn) {
visit((Return) aReturn);
}
@Override
public void visit(StaticClassName staticClassName) {
//Hier entstehen keine Constraints
}
@Override
public void visit(Super aSuper) {
throw new NotImplementedException();
}
@Override
public void visit(This aThis) {
constraintsSet.addUndConstraint(ConstraintsFactory.createPair(
aThis.getType(), info.getCurrentClass().getType(), PairOperator.EQUALSDOT, info.getCurrentTypeScope(),
createNullTypeScope(), getResolverInstance()));
}
private static TypeScope createNullTypeScope() {
return new TypeScope() {
@Override
public Iterable<? extends GenericTypeVar> getGenerics() {
return new ArrayList<>();
}
@Override
public RefTypeOrTPHOrWildcardOrGeneric getReturnType() {
return null;
}
};
}
@Override
public void visit(UnaryPlus unaryPlus) {
throw new NotImplementedException();
}
@Override
public void visit(WhileStmt whileStmt) {
throw new NotImplementedException();
}
@Override
public void visit(DoStmt whileStmt) {
throw new NotImplementedException();
}
@Override
public void visit(Null aNull) {
throw new NotImplementedException();
}
@Override
public void visit(Literal literal) {
//Hier gibt es nichts zu tun
//throw new NotImplementedException();
}
@Override
public void visit(AssignToField assignLeftSide) {
//Hier ist kein Code nötig. Es werden keine extra Constraints generiert
}
@Override
public void visit(AssignToLocal assignLeftSide) {
//Hier ist kein Code nötig. Es werden keine extra Constraints generiert
}
@Override
public void visit(SuperCall superCall) {
//TODO: Für einen super-Call werden keine Constraints erzeugt bisher
}
/*
METHOD CALL Section:
*/
protected Constraint<Pair> generateConstraint(MethodCall forMethod, MethodAssumption assumption,
TypeInferenceBlockInformation info, GenericsResolver resolver){
Constraint methodConstraint = new Constraint();
methodConstraint.add(ConstraintsFactory.createPair(forMethod.receiver.getType(), assumption.getReceiverType(),
PairOperator.SMALLERDOT, info.getCurrentTypeScope(), assumption.getTypeScope(), resolver));
methodConstraint.add(ConstraintsFactory.createPair(assumption.getReturnType(), forMethod.getType(),
PairOperator.EQUALSDOT, info.getCurrentTypeScope(), assumption.getTypeScope(), resolver));
methodConstraint.addAll(generateParameterConstraints(forMethod, assumption, info, resolver));
return methodConstraint;
}
protected Set<Pair> generateParameterConstraints(MethodCall foMethod, MethodAssumption assumption,
TypeInferenceBlockInformation info, GenericsResolver resolver) {
Set<Pair> ret = new HashSet<>();
for(int i = 0;i<foMethod.arglist.getArguments().size();i++){
foMethod.arglist.getArguments().get(i).accept(this);
ret.add(ConstraintsFactory.createPair(foMethod.arglist.getArguments().get(i).getType(),
assumption.getArgTypes().get(i), PairOperator.SMALLERDOT, info.getCurrentTypeScope(), assumption.getTypeScope(), resolver));
}
return ret;
}
public static List<MethodAssumption> getMethods(String name, int numArgs, TypeInferenceBlockInformation info) {
List<MethodAssumption> ret = new ArrayList<>();
if(name.equals("apply")){
List<RefTypeOrTPHOrWildcardOrGeneric> funNParams = new ArrayList<>();
for(int i = 0; i< numArgs + 1 ; i++){
funNParams.add(TypePlaceholder.fresh(new NullToken()));
}
ret.add(new MethodAssumption(new FunN(funNParams), funNParams.get(0), funNParams.subList(1, funNParams.size()),
new TypeScope() {
@Override
public Iterable<? extends GenericTypeVar> getGenerics() {
throw new NotImplementedException();
}
@Override
public RefTypeOrTPHOrWildcardOrGeneric getReturnType() {
throw new NotImplementedException();
}
}));
}
for(ClassOrInterface cl : info.getAvailableClasses()){
for(Method m : cl.getMethods()){
if(m.getName().equals(name) &&
m.getParameterList().getFormalparalist().size() == numArgs){
RefTypeOrTPHOrWildcardOrGeneric retType = info.checkGTV(m.getType());
ret.add(new MethodAssumption(cl.getType(), retType, convertParams(m.getParameterList(),info),
createTypeScope(cl, m)));
}
}
}
return ret;
}
public static List<MethodAssumption> getMethods(String name, ArgumentList arglist, TypeInferenceBlockInformation info) {
return getMethods(name, arglist.getArguments().size(), info);
}
protected static List<RefTypeOrTPHOrWildcardOrGeneric> convertParams(ParameterList parameterList, TypeInferenceBlockInformation info){
//TODO: Hier müssen die Parameter mit den TPHs in den GEnerics des Receivers verknüpft werden
/*
BEispiel:
auto test = new List<String>();
test.add("hallo");
Hier kriegt der Receiver ja den COnstraint TPH REceiver <. List<TPH A>
Dann mus bei dem Parameter der COnstraint entstehen: TPH A <. String
*/
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
for(FormalParameter fp : parameterList.getFormalparalist()){
params.add(info.checkGTV(fp.getType()));
}
return params;
}
public List<MethodAssumption> getConstructors(TypeInferenceBlockInformation info, RefType ofType, ArgumentList argList){
List<MethodAssumption> ret = new ArrayList<>();
for(ClassOrInterface cl : info.getAvailableClasses()){
if(cl.getClassName().equals(ofType.getName())){
for(Method m : cl.getConstructors()){
if(m.getParameterList().getFormalparalist().size() == argList.getArguments().size()){
ret.add(new MethodAssumption(cl.getType(), ofType, convertParams(m.getParameterList(),
info), createTypeScope(cl, m)));
}
}
}
}
return ret;
}
protected Constraint<Pair> generateConstructorConstraint(NewClass forConstructor, MethodAssumption assumption,
TypeInferenceBlockInformation info, GenericsResolver resolver){
Constraint methodConstraint = new Constraint();
methodConstraint.add(ConstraintsFactory.createPair(assumption.getReturnType(), forConstructor.getType(),
PairOperator.SMALLERDOT, info.getCurrentTypeScope(), assumption.getTypeScope(), resolver));
methodConstraint.addAll(generateParameterConstraints(forConstructor, assumption, info, resolver));
return methodConstraint;
}
}

View File

@ -1,24 +0,0 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.Set;
import java.util.concurrent.ForkJoinPool;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
public class TypeUnify {
public Set<Set<UnifyPair>> unify(Set<UnifyPair> eq, IFiniteClosure fc) {
TypeUnifyTask unifyTask = new TypeUnifyTask(eq, fc, true);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(unifyTask);
Set<Set<UnifyPair>> res = unifyTask.join();
return res;
}
public Set<Set<UnifyPair>> unifySequential(Set<UnifyPair> eq, IFiniteClosure fc) {
TypeUnifyTask unifyTask = new TypeUnifyTask(eq, fc, false);
Set<Set<UnifyPair>> res = unifyTask.compute();
return res;
}
}

View File

@ -1,634 +0,0 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet;
import de.dhbwstuttgart.typeinference.unify.interfaces.ISetOperations;
import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify;
import de.dhbwstuttgart.typeinference.unify.model.ExtendsType;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.SuperType;
import de.dhbwstuttgart.typeinference.unify.model.TypeParams;
import de.dhbwstuttgart.typeinference.unify.model.Unifier;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
/**
* Implementation of the type unification algorithm
* @author Florian Steurer
*/
public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
private static final long serialVersionUID = 1L;
/**
* The implementation of setOps that will be used during the unification
*/
protected ISetOperations setOps = new GuavaSetOperations();
/**
* The implementation of the standard unify that will be used during the unification
*/
protected IUnify stdUnify = new MartelliMontanariUnify();
/**
* The implementation of the rules that will be used during the unification.
*/
protected IRuleSet rules = new RuleSet();
protected Set<UnifyPair> eq;
protected IFiniteClosure fc;
protected boolean parallel;
public TypeUnifyTask(Set<UnifyPair> eq, IFiniteClosure fc, boolean parallel) {
this.eq = eq;
this.fc = fc;
this.parallel = parallel;
}
@Override
protected Set<Set<UnifyPair>> compute() {
return unify(eq, fc, parallel);
}
/**
* Computes all principal type unifiers for a set of constraints.
* @param eq The set of constraints
* @param fc The finite closure
* @return The set of all principal type unifiers
*/
protected Set<Set<UnifyPair>> unify(Set<UnifyPair> eq, IFiniteClosure fc, boolean parallel) {
/*
* Step 1: Repeated application of reduce, adapt, erase, swap
*/
Set<UnifyPair> eq0 = applyTypeUnificationRules(eq, fc);
/*
* Step 2 and 3: Create a subset eq1s of pairs where both sides are TPH and eq2s of the other pairs
*/
Set<UnifyPair> eq1s = new HashSet<>();
Set<UnifyPair> eq2s = new HashSet<>();
splitEq(eq0, eq1s, eq2s);
/*
* Step 4: Create possible typings
*
* "Manche Autoren identifizieren die Paare (a, (b,c)) und ((a,b),c)
* mit dem geordneten Tripel (a,b,c), wodurch das kartesische Produkt auch assoziativ wird." - Wikipedia
*/
// There are up to 10 toplevel set. 8 of 10 are the result of the
// cartesian product of the sets created by pattern matching.
List<Set<Set<UnifyPair>>> topLevelSets = new ArrayList<>();
if(eq1s.size() != 0) { // Do not add empty sets or the cartesian product will always be empty.
Set<Set<UnifyPair>> wrap = new HashSet<>();
wrap.add(eq1s);
topLevelSets.add(wrap); // Add Eq1'
}
// Add the set of [a =. Theta | (a=. Theta) in Eq2']
Set<UnifyPair> bufferSet = eq2s.stream()
.filter(x -> x.getPairOp() == PairOperator.EQUALSDOT && x.getLhsType() instanceof PlaceholderType)
.collect(Collectors.toSet());
if(bufferSet.size() != 0) { // Do not add empty sets or the cartesian product will always be empty.
Set<Set<UnifyPair>> wrap = new HashSet<>();
wrap.add(bufferSet);
topLevelSets.add(wrap);
eq2s.removeAll(bufferSet);
}
// Sets that originate from pair pattern matching
// Sets of the "second level"
Set<UnifyPair> undefinedPairs = new HashSet<>();
Set<Set<Set<Set<UnifyPair>>>> secondLevelSets = calculatePairSets(eq2s, fc, undefinedPairs);
//PL 2017-09-20: Im calculatePairSets wird möglicherweise O .< java.lang.Integer
//nicht ausgewertet Faculty Beispiel im 1. Schritt
//PL 2017-10-03 geloest, muesste noch mit FCs mit kleineren
//Typen getestet werden.
// If pairs occured that did not match one of the cartesian product cases,
// those pairs are contradictory and the unification is impossible.
if(!undefinedPairs.isEmpty())
return new HashSet<>();
/* Up to here, no cartesian products are calculated.
* filters for pairs and sets can be applied here */
// Sub cartesian products of the second level (pattern matched) sets
// "the big (x)"
for(Set<Set<Set<UnifyPair>>> secondLevelSet : secondLevelSets) {
List<Set<Set<UnifyPair>>> secondLevelSetList = new ArrayList<>(secondLevelSet);
Set<List<Set<UnifyPair>>> cartResult = setOps.cartesianProduct(secondLevelSetList);
// Flatten and add to top level sets
Set<Set<UnifyPair>> flat = new HashSet<>();
for(List<Set<UnifyPair>> s : cartResult) {
Set<UnifyPair> flat1 = new HashSet<>();
for(Set<UnifyPair> s1 : s)
flat1.addAll(s1);
flat.add(flat1);
}
topLevelSets.add(flat);
}
// Cartesian product over all (up to 10) top level sets
Set<Set<Set<UnifyPair>>> eqPrimeSet = setOps.cartesianProduct(topLevelSets)
.stream().map(x -> new HashSet<>(x))
.collect(Collectors.toCollection(HashSet::new));
Set<Set<UnifyPair>> eqPrimePrimeSet = new HashSet<>();
Set<TypeUnifyTask> forks = new HashSet<>();
for(Set<Set<UnifyPair>> setToFlatten : eqPrimeSet) {
// Flatten the cartesian product
Set<UnifyPair> eqPrime = new HashSet<>();
setToFlatten.stream().forEach(x -> eqPrime.addAll(x));
/*
* Step 5: Substitution
*/
Optional<Set<UnifyPair>> eqPrimePrime = rules.subst(eqPrime);
/*
* Step 6 a) Restart (fork) for pairs where subst was applied
*/
if(parallel) {
if //(eqPrime.equals(eq)) //PL 2017-09-29 auskommentiert und durch
(!eqPrimePrime.isPresent()) //PL 2071-09-29 dies ersetzt
//Begruendung: Wenn in der Substitution keine Veraenderung
//(!eqPrimePrime.isPresent()) erfolgt ist, ist das Ergebnis erzielt.
eqPrimePrimeSet.add(eqPrime);
else if(eqPrimePrime.isPresent()) {
TypeUnifyTask fork = new TypeUnifyTask(eqPrimePrime.get(), fc, true);
forks.add(fork);
fork.fork();
}
else {
TypeUnifyTask fork = new TypeUnifyTask(eqPrime, fc, true);
forks.add(fork);
fork.fork();
}
}
else { // sequentiell (Step 6b is included)
if //(eqPrime.equals(eq)) //PL 2017-09-29 auskommentiert und durch
(!eqPrimePrime.isPresent()) //PL 2071-09-29 dies ersetzt
//Begruendung: Wenn in der Substitution keine Veraenderung
//(!eqPrimePrime.isPresent()) erfolgt ist, ist das Ergebnis erzielt.
eqPrimePrimeSet.add(eqPrime);
else if(eqPrimePrime.isPresent())
eqPrimePrimeSet.addAll(unify(eqPrimePrime.get(), fc, false));
else
eqPrimePrimeSet.addAll(unify(eqPrime, fc, false));
}
}
/*
* Step 6 b) Build the union over everything.
*/
if(parallel)
for(TypeUnifyTask fork : forks)
eqPrimePrimeSet.addAll(fork.join());
/*
* Step 7: Filter empty sets;
*/
return eqPrimePrimeSet.stream().filter(x -> isSolvedForm(x)).collect(Collectors.toCollection(HashSet::new));
}
/**
* Checks whether a set of pairs is in solved form.
* @param eqPrimePrime The set of pair
* @return True if in solved form, false otherwise.
*/
protected boolean isSolvedForm(Set<UnifyPair> eqPrimePrime) {
for(UnifyPair pair : eqPrimePrime) {
UnifyType lhsType = pair.getLhsType();
UnifyType rhsType = pair.getRhsType();
if(!(lhsType instanceof PlaceholderType))
return false;
// If operator is not equals, both sides must be placeholders
if(pair.getPairOp() != PairOperator.EQUALSDOT && !(rhsType instanceof PlaceholderType))
return false;
}
return true;
}
/**
* Repeatedly applies type unification rules to a set of equations.
* This is step one of the unification algorithm.
* @return The set of pairs that results from repeated application of the inference rules.
*/
protected Set<UnifyPair> applyTypeUnificationRules(Set<UnifyPair> eq, IFiniteClosure fc) {
/*
* Rule Application Strategy:
*
* 1. Swap all pairs and erase all erasable pairs
* 2. Apply all possible rules to a single pair, then move it to the result set.
* Iterating over pairs first, then iterating over rules prevents the application
* of rules to a "finished" pair over and over.
* 2.1 Apply all rules repeatedly except for erase rules. If
* the application of a rule creates new pairs, check immediately
* against the erase rules.
*/
LinkedHashSet<UnifyPair> targetSet = new LinkedHashSet<UnifyPair>();
LinkedList<UnifyPair> eqQueue = new LinkedList<>();
/*
* Swap all pairs and erase all erasable pairs
*/
eq.forEach(x -> swapAddOrErase(x, fc, eqQueue));
/*
* Apply rules until the queue is empty
*/
while(!eqQueue.isEmpty()) {
UnifyPair pair = eqQueue.pollFirst();
// ReduceUp, ReduceLow, ReduceUpLow
Optional<UnifyPair> opt = rules.reduceUpLow(pair);
opt = opt.isPresent() ? opt : rules.reduceLow(pair);
opt = opt.isPresent() ? opt : rules.reduceUp(pair);
opt = opt.isPresent() ? opt : rules.reduceWildcardLow(pair);
opt = opt.isPresent() ? opt : rules.reduceWildcardLowRight(pair);
opt = opt.isPresent() ? opt : rules.reduceWildcardUp(pair);
opt = opt.isPresent() ? opt : rules.reduceWildcardUpRight(pair);
opt = opt.isPresent() ? opt : rules.reduceWildcardLowUp(pair);
opt = opt.isPresent() ? opt : rules.reduceWildcardUpLow(pair);
opt = opt.isPresent() ? opt : rules.reduceWildcardLeft(pair);
// Reduce TPH
opt = opt.isPresent() ? opt : rules.reduceTph(pair);
// One of the rules has been applied
if(opt.isPresent()) {
swapAddOrErase(opt.get(), fc, eqQueue);
continue;
}
// Reduce1, Reduce2, ReduceExt, ReduceSup, ReduceEq
Optional<Set<UnifyPair>> optSet = rules.reduce1(pair, fc);
optSet = optSet.isPresent() ? optSet : rules.reduce2(pair);
optSet = optSet.isPresent() ? optSet : rules.reduceExt(pair, fc);
optSet = optSet.isPresent() ? optSet : rules.reduceSup(pair, fc);
optSet = optSet.isPresent() ? optSet : rules.reduceEq(pair);
// ReduceTphExt, ReduceTphSup
optSet = optSet.isPresent() ? optSet : rules.reduceTphExt(pair);
optSet = optSet.isPresent() ? optSet : rules.reduceTphSup(pair);
// FunN Rules
optSet = optSet.isPresent() ? optSet : rules.reduceFunN(pair);
optSet = optSet.isPresent() ? optSet : rules.greaterFunN(pair);
optSet = optSet.isPresent() ? optSet : rules.smallerFunN(pair);
// One of the rules has been applied
if(optSet.isPresent()) {
optSet.get().forEach(x -> swapAddOrErase(x, fc, eqQueue));
continue;
}
// Adapt, AdaptExt, AdaptSup
opt = rules.adapt(pair, fc);
opt = opt.isPresent() ? opt : rules.adaptExt(pair, fc);
opt = opt.isPresent() ? opt : rules.adaptSup(pair, fc);
// One of the rules has been applied
if(opt.isPresent()) {
swapAddOrErase(opt.get(), fc, eqQueue);
continue;
}
// None of the rules has been applied
targetSet.add(pair);
}
return targetSet;
}
/**
* Applies the rule swap to a pair if possible. Then adds the pair to the set if no erase rule applies.
* If an erase rule applies, the pair is not added (erased).
* @param pair The pair to swap and add or erase.
* @param collection The collection to which the pairs are added.
*/
protected void swapAddOrErase(UnifyPair pair, IFiniteClosure fc, Collection<UnifyPair> collection) {
Optional<UnifyPair> opt = rules.swap(pair);
UnifyPair pair2 = opt.isPresent() ? opt.get() : pair;
if(rules.erase1(pair2, fc) || rules.erase3(pair2) || rules.erase2(pair2, fc))
return;
collection.add(pair2);
}
/**
* Splits the equation eq into a set eq1s where both terms are type variables,
* and a set eq2s where one of both terms is not a type variable.
* @param eq Set of pairs to be splitted.
* @param eq1s Subset of eq where both terms are type variables.
* @param eq2s eq/eq1s.
*/
protected void splitEq(Set<UnifyPair> eq, Set<UnifyPair> eq1s, Set<UnifyPair> eq2s) {
for(UnifyPair pair : eq)
if(pair.getLhsType() instanceof PlaceholderType && pair.getRhsType() instanceof PlaceholderType)
eq1s.add(pair);
else
eq2s.add(pair);
}
/**
* Creates sets of pairs specified in the fourth step. Does not calculate cartesian products.
* @param undefined All pairs that did not match one of the 8 cases are added to this set.
* @return The set of the eight cases (without empty sets). Each case is a set, containing sets generated
* from the pairs that matched the case. Each generated set contains singleton sets or sets with few elements
* (as in case 1 where sigma is added to the innermost set).
*/
protected Set<Set<Set<Set<UnifyPair>>>> calculatePairSets(Set<UnifyPair> eq2s, IFiniteClosure fc, Set<UnifyPair> undefined) {
List<Set<Set<Set<UnifyPair>>>> result = new ArrayList<>(8);
// Init all 8 cases
for(int i = 0; i < 8; i++)
result.add(new HashSet<>());
for(UnifyPair pair : eq2s) {
PairOperator pairOp = pair.getPairOp();
UnifyType lhsType = pair.getLhsType();
UnifyType rhsType = pair.getRhsType();
// Case 1: (a <. Theta')
if(pairOp == PairOperator.SMALLERDOT && lhsType instanceof PlaceholderType)
result.get(0).add(unifyCase1((PlaceholderType) pair.getLhsType(), pair.getRhsType(), fc));
// Case 2: (a <.? ? ext Theta')
else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof ExtendsType)
result.get(1).add(unifyCase2((PlaceholderType) pair.getLhsType(), (ExtendsType) pair.getRhsType(), fc));
// Case 3: (a <.? ? sup Theta')
else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof SuperType)
result.get(2).add(unifyCase3((PlaceholderType) lhsType, (SuperType) rhsType, fc));
// Case 4 was replaced by an inference rule
// Case 4: (a <.? Theta')
//else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType)
// result.get(3).add(unifyCase4((PlaceholderType) lhsType, rhsType, fc));
// Case 5: (Theta <. a)
else if(pairOp == PairOperator.SMALLERDOT && rhsType instanceof PlaceholderType)
result.get(4).add(unifyCase5(lhsType, (PlaceholderType) rhsType, fc));
// Case 6 was replaced by an inference rule.
// Case 6: (? ext Theta <.? a)
//else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof ExtendsType && rhsType instanceof PlaceholderType)
// result.get(5).add(unifyCase6((ExtendsType) lhsType, (PlaceholderType) rhsType, fc));
// Case 7 was replaced by an inference rule
// Case 7: (? sup Theta <.? a)
//else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof SuperType && rhsType instanceof PlaceholderType)
// result.get(6).add(unifyCase7((SuperType) lhsType, (PlaceholderType) rhsType, fc));
// Case 8: (Theta <.? a)
else if(pairOp == PairOperator.SMALLERDOTWC && rhsType instanceof PlaceholderType)
result.get(7).add(unifyCase8(lhsType, (PlaceholderType) rhsType, fc));
// Case unknown: If a pair fits no other case, then the type unification has failed.
// Through application of the rules, every pair should have one of the above forms.
// Pairs that do not have one of the aboves form are contradictory.
else {
// If a pair is not defined, the unificiation will fail, so the loop can be stopped here.
undefined.add(pair);
break;
}
}
// Filter empty sets or sets that only contain an empty set.
return result.stream().map(x -> x.stream().filter(y -> y.size() > 0).collect(Collectors.toCollection(HashSet::new)))
.filter(x -> x.size() > 0).collect(Collectors.toCollection(HashSet::new));
}
/**
* Cartesian product Case 1: (a <. Theta')
*/
protected Set<Set<UnifyPair>> unifyCase1(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) {
Set<Set<UnifyPair>> result = new HashSet<>();
boolean allGen = thetaPrime.getTypeParams().size() > 0;
for(UnifyType t : thetaPrime.getTypeParams())
if(!(t instanceof PlaceholderType) || !((PlaceholderType) t).isGenerated()) {
allGen = false;
break;
}
Set<UnifyType> cs = fc.getAllTypesByName(thetaPrime.getName());
cs.add(thetaPrime);
for(UnifyType c : cs) {
Set<UnifyType> thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new));
thetaQs.add(thetaPrime); //PL 2017-10-03: War auskommentiert habe ich wieder einkommentiert,
//da children offensichtlich ein echtes kleiner und kein kleinergleich ist
Set<UnifyType> thetaQPrimes = new HashSet<>();
TypeParams cParams = c.getTypeParams();
if(cParams.size() == 0)
thetaQPrimes.add(c);
else {
ArrayList<Set<UnifyType>> candidateParams = new ArrayList<>();
for(UnifyType param : cParams)
candidateParams.add(fc.grArg(param));
for(TypeParams tp : permuteParams(candidateParams))
thetaQPrimes.add(c.setTypeParams(tp));
}
for(UnifyType tqp : thetaQPrimes) {
Optional<Unifier> opt = stdUnify.unify(tqp, thetaPrime);
if (!opt.isPresent())
continue;
Unifier unifier = opt.get();
unifier.swapPlaceholderSubstitutions(thetaPrime.getTypeParams());
Set<UnifyPair> substitutionSet = new HashSet<>();
for (Entry<PlaceholderType, UnifyType> sigma : unifier)
substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT));
List<UnifyType> freshTphs = new ArrayList<>();
for (UnifyType tq : thetaQs) {
Set<UnifyType> smaller = fc.smaller(unifier.apply(tq));
for(UnifyType theta : smaller) {
Set<UnifyPair> resultPrime = new HashSet<>();
for(int i = 0; !allGen && i < theta.getTypeParams().size(); i++) {
if(freshTphs.size()-1 < i)
freshTphs.add(PlaceholderType.freshPlaceholder());
resultPrime.add(new UnifyPair(freshTphs.get(i), theta.getTypeParams().get(i), PairOperator.SMALLERDOTWC));
}
if(allGen)
resultPrime.add(new UnifyPair(a, theta, PairOperator.EQUALSDOT));
else
resultPrime.add(new UnifyPair(a, theta.setTypeParams(new TypeParams(freshTphs.toArray(new UnifyType[0]))), PairOperator.EQUALSDOT));
resultPrime.addAll(substitutionSet);
result.add(resultPrime);
}
}
}
}
return result;
}
/**
* Cartesian Product Case 2: (a <.? ? ext Theta')
*/
private Set<Set<UnifyPair>> unifyCase2(PlaceholderType a, ExtendsType extThetaPrime, IFiniteClosure fc) {
Set<Set<UnifyPair>> result = new HashSet<>();
UnifyType aPrime = PlaceholderType.freshPlaceholder();
UnifyType extAPrime = new ExtendsType(aPrime);
UnifyType thetaPrime = extThetaPrime.getExtendedType();
Set<UnifyPair> resultPrime = new HashSet<>();
resultPrime.add(new UnifyPair(a, thetaPrime, PairOperator.SMALLERDOT));
result.add(resultPrime);
resultPrime = new HashSet<>();
resultPrime.add(new UnifyPair(a, extAPrime, PairOperator.EQUALSDOT));
resultPrime.add(new UnifyPair(aPrime, thetaPrime, PairOperator.SMALLERDOT));
result.add(resultPrime);
return result;
}
/**
* Cartesian Product Case 3: (a <.? ? sup Theta')
*/
private Set<Set<UnifyPair>> unifyCase3(PlaceholderType a, SuperType subThetaPrime, IFiniteClosure fc) {
Set<Set<UnifyPair>> result = new HashSet<>();
UnifyType aPrime = PlaceholderType.freshPlaceholder();
UnifyType supAPrime = new SuperType(aPrime);
UnifyType thetaPrime = subThetaPrime.getSuperedType();
Set<UnifyPair> resultPrime = new HashSet<>();
resultPrime.add(new UnifyPair(thetaPrime, a, PairOperator.SMALLERDOT));
result.add(resultPrime);
resultPrime = new HashSet<>();
resultPrime.add(new UnifyPair(a, supAPrime, PairOperator.EQUALSDOT));
resultPrime.add(new UnifyPair(thetaPrime, aPrime, PairOperator.SMALLERDOT));
result.add(resultPrime);
return result;
}
/**
* Cartesian Product Case 5: (Theta <. a)
*/
private Set<Set<UnifyPair>> unifyCase5(UnifyType theta, PlaceholderType a, IFiniteClosure fc) {
Set<Set<UnifyPair>> result = new HashSet<>();
boolean allGen = theta.getTypeParams().size() > 0;
for(UnifyType t : theta.getTypeParams())
if(!(t instanceof PlaceholderType) || !((PlaceholderType) t).isGenerated()) {
allGen = false;
break;
}
for(UnifyType thetaS : fc.greater(theta)) {
Set<UnifyPair> resultPrime = new HashSet<>();
UnifyType[] freshTphs = new UnifyType[thetaS.getTypeParams().size()];
for(int i = 0; !allGen && i < freshTphs.length; i++) {
freshTphs[i] = PlaceholderType.freshPlaceholder();
resultPrime.add(new UnifyPair(thetaS.getTypeParams().get(i), freshTphs[i], PairOperator.SMALLERDOTWC));
}
if(allGen)
resultPrime.add(new UnifyPair(a, thetaS, PairOperator.EQUALSDOT));
else
resultPrime.add(new UnifyPair(a, thetaS.setTypeParams(new TypeParams(freshTphs)), PairOperator.EQUALSDOT));
result.add(resultPrime);
}
return result;
}
/**
* Cartesian Product Case 8: (Theta <.? a)
*/
private Set<Set<UnifyPair>> unifyCase8(UnifyType theta, PlaceholderType a, IFiniteClosure fc) {
Set<Set<UnifyPair>> result = new HashSet<>();
//for(UnifyType thetaS : fc.grArg(theta)) {
Set<UnifyPair> resultPrime = new HashSet<>();
resultPrime.add(new UnifyPair(a, theta, PairOperator.EQUALSDOT));
result.add(resultPrime);
UnifyType freshTph = PlaceholderType.freshPlaceholder();
resultPrime = new HashSet<>();
resultPrime.add(new UnifyPair(a, new ExtendsType(freshTph), PairOperator.EQUALSDOT));
resultPrime.add(new UnifyPair(theta, freshTph, PairOperator.SMALLERDOT));
result.add(resultPrime);
resultPrime = new HashSet<>();
resultPrime.add(new UnifyPair(a, new SuperType(freshTph), PairOperator.EQUALSDOT));
resultPrime.add(new UnifyPair(freshTph, theta, PairOperator.SMALLERDOT));
result.add(resultPrime);
//}
return result;
}
/**
* Takes a set of candidates for each position and computes all possible permutations.
* @param candidates The length of the list determines the number of type params. Each set
* contains the candidates for the corresponding position.
*/
protected Set<TypeParams> permuteParams(ArrayList<Set<UnifyType>> candidates) {
Set<TypeParams> result = new HashSet<>();
permuteParams(candidates, 0, result, new UnifyType[candidates.size()]);
return result;
}
/**
* Takes a set of candidates for each position and computes all possible permutations.
* @param candidates The length of the list determines the number of type params. Each set
* contains the candidates for the corresponding position.
* @param idx Idx for the current permutatiton.
* @param result Set of all permutations found so far
* @param current The permutation of type params that is currently explored
*/
private void permuteParams(ArrayList<Set<UnifyType>> candidates, int idx, Set<TypeParams> result, UnifyType[] current) {
if(candidates.size() == idx) {
result.add(new TypeParams(Arrays.copyOf(current, current.length)));
return;
}
Set<UnifyType> localCandidates = candidates.get(idx);
for(UnifyType t : localCandidates) {
current[idx] = t;
permuteParams(candidates, idx+1, result, current);
}
}
}

View File

@ -1,413 +0,0 @@
package de.dhbwstuttgart.typeinference.unify.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.dhbwstuttgart.typeinference.unify.MartelliMontanariUnify;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify;
/**
* The finite closure for the type unification
* @author Florian Steurer
*/
public class FiniteClosure implements IFiniteClosure {
/**
* A map that maps every type to the node in the inheritance graph that contains that type.
*/
private HashMap<UnifyType, Node<UnifyType>> inheritanceGraph;
/**
* A map that maps every typename to the nodes of the inheritance graph that contain a type with that name.
*/
private HashMap<String, Set<Node<UnifyType>>> strInheritanceGraph;
/**
* The initial pairs of that define the inheritance tree
*/
private Set<UnifyPair> pairs;
/**
* Creates a new instance using the inheritance tree defined in the pairs.
*/
public FiniteClosure(Set<UnifyPair> pairs) {
this.pairs = new HashSet<>(pairs);
inheritanceGraph = new HashMap<UnifyType, Node<UnifyType>>();
// Build the transitive closure of the inheritance tree
for(UnifyPair pair : pairs) {
if(pair.getPairOp() != PairOperator.SMALLER)
continue;
// Add nodes if not already in the graph
if(!inheritanceGraph.containsKey(pair.getLhsType()))
inheritanceGraph.put(pair.getLhsType(), new Node<UnifyType>(pair.getLhsType()));
if(!inheritanceGraph.containsKey(pair.getRhsType()))
inheritanceGraph.put(pair.getRhsType(), new Node<UnifyType>(pair.getRhsType()));
Node<UnifyType> childNode = inheritanceGraph.get(pair.getLhsType());
Node<UnifyType> parentNode = inheritanceGraph.get(pair.getRhsType());
// Add edge
parentNode.addDescendant(childNode);
// Add edges to build the transitive closure
parentNode.getPredecessors().stream().forEach(x -> x.addDescendant(childNode));
childNode.getDescendants().stream().forEach(x -> x.addPredecessor(parentNode));
}
// Build the alternative representation with strings as keys
strInheritanceGraph = new HashMap<>();
for(UnifyType key : inheritanceGraph.keySet()) {
if(!strInheritanceGraph.containsKey(key.getName()))
strInheritanceGraph.put(key.getName(), new HashSet<>());
strInheritanceGraph.get(key.getName()).add(inheritanceGraph.get(key));
}
}
/**
* Returns all types of the finite closure that are subtypes of the argument.
* @return The set of subtypes of the argument.
*/
@Override
public Set<UnifyType> smaller(UnifyType type) {
if(type instanceof FunNType)
return computeSmallerFunN((FunNType) type);
Set<UnifyType> ts = new HashSet<>();
ts.add(type);
return computeSmaller(ts);
}
/**
* Computes the smaller functions for every type except FunNTypes.
*/
private Set<UnifyType> computeSmaller(Set<UnifyType> types) {
HashSet<UnifyType> result = new HashSet<>();
IUnify unify = new MartelliMontanariUnify();
for(UnifyType t : types) {
// if T = T' then T <* T'
result.add(t);
// if C<...> <* C<...> then ... (third case in definition of <*)
if(t.getTypeParams().size() > 0) {
ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>();
for (int i = 0; i < t.getTypeParams().size(); i++)
paramCandidates.add(smArg(t.getTypeParams().get(i)));
permuteParams(paramCandidates).forEach(x -> result.add(t.setTypeParams(x)));
}
if(!strInheritanceGraph.containsKey(t.getName()))
continue;
// if T <* T' then sigma(T) <* sigma(T')
Set<Node<UnifyType>> candidates = strInheritanceGraph.get(t.getName());
for(Node<UnifyType> candidate : candidates) {
UnifyType theta2 = candidate.getContent();
Optional<Unifier> optSigma = unify.unify(theta2, t);
if(!optSigma.isPresent())
continue;
Unifier sigma = optSigma.get();
sigma.swapPlaceholderSubstitutions(t.getTypeParams());
Set<UnifyType> theta1Set = candidate.getContentOfDescendants();
for(UnifyType theta1 : theta1Set)
result.add(theta1.apply(sigma));
}
}
if(result.equals(types))
return result;
return computeSmaller(result);
}
/**
* Computes the smaller-Function for FunNTypes.
*/
private Set<UnifyType> computeSmallerFunN(FunNType type) {
Set<UnifyType> result = new HashSet<>();
// if T = T' then T <=* T'
result.add(type);
// Because real function types are implicitly variant
// it is enough to permute the params with the values of greater / smaller.
ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>();
paramCandidates.add(smaller(type.getTypeParams().get(0)));
for (int i = 1; i < type.getTypeParams().size(); i++)
paramCandidates.add(greater(type.getTypeParams().get(i)));
permuteParams(paramCandidates).forEach(x -> result.add(type.setTypeParams(x)));
return result;
}
/**
* Returns all types of the finite closure that are supertypes of the argument.
* @return The set of supertypes of the argument.
*/
@Override
public Set<UnifyType> greater(UnifyType type) {
if(type instanceof FunNType)
return computeGreaterFunN((FunNType) type);
Set<UnifyType> ts = new HashSet<>();
ts.add(type);
return computeGreater(ts);
}
/**
* Computes the greater function for all types except function types.
*/
protected Set<UnifyType> computeGreater(Set<UnifyType> types) {
HashSet<UnifyType> result = new HashSet<>();
IUnify unify = new MartelliMontanariUnify();
for(UnifyType t : types) {
// if T = T' then T <=* T'
result.add(t);
// if C<...> <* C<...> then ... (third case in definition of <*)
if(t.getTypeParams().size() > 0) {
ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>();
for (int i = 0; i < t.getTypeParams().size(); i++)
paramCandidates.add(grArg(t.getTypeParams().get(i)));
permuteParams(paramCandidates).forEach(x -> result.add(t.setTypeParams(x)));
}
if(!strInheritanceGraph.containsKey(t.getName()))
continue;
// if T <* T' then sigma(T) <* sigma(T')
Set<Node<UnifyType>> candidates = strInheritanceGraph.get(t.getName());
for(Node<UnifyType> candidate : candidates) {
UnifyType theta1 = candidate.getContent();
Optional<Unifier> optSigma = unify.unify(theta1, t);
if(!optSigma.isPresent())
continue;
Unifier sigma = optSigma.get();
sigma.swapPlaceholderSubstitutionsReverse(theta1.getTypeParams());
Set<UnifyType> theta2Set = candidate.getContentOfPredecessors();
for(UnifyType theta2 : theta2Set)
result.add(theta2.apply(sigma));
}
}
if(result.equals(types))
return result;
return computeGreater(result);
}
/**
* Computes the greater function for FunN-Types
*/
protected Set<UnifyType> computeGreaterFunN(FunNType type) {
Set<UnifyType> result = new HashSet<>();
// if T = T' then T <=* T'
result.add(type);
// Because real function types are implicitly variant
// it is enough to permute the params with the values of greater / smaller.
ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>();
paramCandidates.add(greater(type.getTypeParams().get(0)));
for (int i = 1; i < type.getTypeParams().size(); i++)
paramCandidates.add(smaller(type.getTypeParams().get(i)));
permuteParams(paramCandidates).forEach(x -> result.add(type.setTypeParams(x)));
return result;
}
@Override
public Set<UnifyType> grArg(UnifyType type) {
return type.grArg(this);
}
@Override
public Set<UnifyType> grArg(ReferenceType type) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
smaller(type).forEach(x -> result.add(new SuperType(x)));
greater(type).forEach(x -> result.add(new ExtendsType(x)));
return result;
}
@Override
public Set<UnifyType> grArg(FunNType type) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
smaller(type).forEach(x -> result.add(new SuperType(x)));
greater(type).forEach(x -> result.add(new ExtendsType(x)));
return result;
}
@Override
public Set<UnifyType> grArg(ExtendsType type) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
UnifyType t = type.getExtendedType();
greater(t).forEach(x -> result.add(new ExtendsType(x)));
return result;
}
@Override
public Set<UnifyType> grArg(SuperType type) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
UnifyType t = type.getSuperedType();
smaller(t).forEach(x -> result.add(new SuperType(x)));
return result;
}
@Override
public Set<UnifyType> grArg(PlaceholderType type) {
HashSet<UnifyType> result = new HashSet<>();
result.add(type);
return result;
}
@Override
public Set<UnifyType> smArg(UnifyType type) {
return type.smArg(this);
}
@Override
public Set<UnifyType> smArg(ReferenceType type) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
return result;
}
@Override
public Set<UnifyType> smArg(FunNType type) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
return result;
}
@Override
public Set<UnifyType> smArg(ExtendsType type) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
UnifyType t = type.getExtendedType();
result.add(t);
smaller(t).forEach(x -> {
result.add(new ExtendsType(x));
result.add(x);
});
return result;
}
@Override
public Set<UnifyType> smArg(SuperType type) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
UnifyType t = type.getSuperedType();
result.add(t);
greater(t).forEach(x -> {
result.add(new SuperType(x));
result.add(x);
});
return result;
}
@Override
public Set<UnifyType> smArg(PlaceholderType type) {
HashSet<UnifyType> result = new HashSet<>();
result.add(type);
return result;
}
@Override
public Set<UnifyType> getAllTypesByName(String typeName) {
if(!strInheritanceGraph.containsKey(typeName))
return new HashSet<>();
return strInheritanceGraph.get(typeName).stream().map(x -> x.getContent()).collect(Collectors.toCollection(HashSet::new));
}
@Override
public Optional<UnifyType> getLeftHandedType(String typeName) {
if(!strInheritanceGraph.containsKey(typeName))
return Optional.empty();
for(UnifyPair pair : pairs)
if(pair.getLhsType().getName().equals(typeName))
return Optional.of(pair.getLhsType());
return Optional.empty();
}
@Override
public Set<UnifyType> getAncestors(UnifyType t) {
if(!inheritanceGraph.containsKey(t))
return new HashSet<>();
Set<UnifyType> result = inheritanceGraph.get(t).getContentOfPredecessors();
result.add(t);
return result;
}
@Override
public Set<UnifyType> getChildren(UnifyType t) {
if(!inheritanceGraph.containsKey(t))
return new HashSet<>();
Set<UnifyType> result = inheritanceGraph.get(t).getContentOfDescendants();
result.add(t);
return result;
}
/**
* Takes a set of candidates for each position and computes all possible permutations.
* @param candidates The length of the list determines the number of type params. Each set
* contains the candidates for the corresponding position.
*/
protected Set<TypeParams> permuteParams(ArrayList<Set<UnifyType>> candidates) {
Set<TypeParams> result = new HashSet<>();
permuteParams(candidates, 0, result, new UnifyType[candidates.size()]);
return result;
}
/**
* Takes a set of candidates for each position and computes all possible permutations.
* @param candidates The length of the list determines the number of type params. Each set
* contains the candidates for the corresponding position.
* @param idx Idx for the current permutatiton.
* @param result Set of all permutations found so far
* @param current The permutation of type params that is currently explored
*/
protected void permuteParams(ArrayList<Set<UnifyType>> candidates, int idx, Set<TypeParams> result, UnifyType[] current) {
if(candidates.size() == idx) {
result.add(new TypeParams(Arrays.copyOf(current, current.length)));
return;
}
Set<UnifyType> localCandidates = candidates.get(idx);
for(UnifyType t : localCandidates) {
current[idx] = t;
permuteParams(candidates, idx+1, result, current);
}
}
@Override
public String toString(){
return this.inheritanceGraph.toString();
}
}

View File

@ -1,101 +0,0 @@
package de.dhbwstuttgart.typeinference.unify.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* A pair which contains two types and an operator, e.q. (Integer <. a).
* @author Florian Steurer
*/
public class UnifyPair {
/**
* The type on the left hand side of the pair.
*/
private final UnifyType lhs;
/**
* The type on the right hand side of the pair.
*/
private final UnifyType rhs;
/**
* The operator that determines the relation between the left and right hand side type.
*/
private PairOperator pairOp;
private final int hashCode;
/**
* Creates a new instance of the pair.
* @param lhs The type on the left hand side of the pair.
* @param rhs The type on the right hand side of the pair.
* @param op The operator that determines the relation between the left and right hand side type.
*/
public UnifyPair(UnifyType lhs, UnifyType rhs, PairOperator op) {
this.lhs = lhs;
this.rhs = rhs;
pairOp = op;
// Caching hashcode
hashCode = 17 + 31 * lhs.hashCode() + 31 * rhs.hashCode() + 31 * pairOp.hashCode();
}
/**
* Returns the type on the left hand side of the pair.
*/
public UnifyType getLhsType() {
return lhs;
}
/**
* Returns the type on the right hand side of the pair.
*/
public UnifyType getRhsType() {
return rhs;
}
/**
* Returns the operator that determines the relation between the left and right hand side type.
*/
public PairOperator getPairOp() {
return pairOp;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof UnifyPair))
return false;
if(obj.hashCode() != this.hashCode())
return false;
UnifyPair other = (UnifyPair) obj;
return other.getPairOp() == pairOp
&& other.getLhsType().equals(lhs)
&& other.getRhsType().equals(rhs);
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public String toString() {
return "(" + lhs + " " + pairOp + " " + rhs + ")";
}
/*
public List<? extends PlaceholderType> getInvolvedPlaceholderTypes() {
ArrayList<PlaceholderType> ret = new ArrayList<>();
ret.addAll(lhs.getInvolvedPlaceholderTypes());
ret.addAll(rhs.getInvolvedPlaceholderTypes());
return ret;
}
*/
}

View File

@ -109,7 +109,6 @@ classOrInterfaceType
| interfaceType_lfno_classOrInterfaceType | interfaceType_lfno_classOrInterfaceType
) )
( classType_lf_classOrInterfaceType ( classType_lf_classOrInterfaceType
| interfaceType_lf_classOrInterfaceType
)* )*
; ;
@ -333,7 +332,7 @@ classMemberDeclaration
; ;
fieldDeclaration fieldDeclaration
: fieldModifier* unannType? variableDeclaratorList ';' : fieldModifier* unannTypeOrAuto? variableDeclaratorList ';'
; ;
fieldModifier fieldModifier
@ -1739,6 +1738,7 @@ Identifier
: JavaLetter JavaLetterOrDigit* : JavaLetter JavaLetterOrDigit*
; ;
fragment fragment
JavaLetter JavaLetter
: [a-zA-Z$_] // these are the "java letters" below 0x7F : [a-zA-Z$_] // these are the "java letters" below 0x7F

View File

@ -0,0 +1,37 @@
grammar UnifyResult;
answer : 'ANSWER' (resultSetRule '.')*;
resultSetRule :
parameter
| equals
| smaller
| typeVar
| type
| otherRule
;
parameterList : '(' value (',' value)* ')';
value : NAME
| resultSetRule ;
parameter : PARAMLIST_NAME parameterList;
equals : EQUALS_NAME parameterList;
smaller : SMALLER_NAME parameterList;
typeVar : TYPEVAR_NAME parameterList;
type : TYPE_NAME parameterList;
otherRule : NAME parameterList;
//TODO: Es sollte Regeln für das Result set geben, welche sich nicht mit den anderen überdecken, dann auch nur diese im Result ausgeben
PARAMLIST_NAME : 'param';
EQUALS_NAME : 'equals';
SMALLER_NAME : 'smaller';
TYPEVAR_NAME : 'typeVar';
TYPE_NAME : 'type';
NAME : [a-zA-Z0-9_]+;
WS : [ \t\r\n\u000C]+ -> skip
;
LINE_COMMENT
: '%' ~[\r\n]* -> skip
;

View File

@ -0,0 +1,23 @@
T__0=1
T__1=2
T__2=3
T__3=4
T__4=5
PARAMLIST_NAME=6
EQUALS_NAME=7
SMALLER_NAME=8
TYPEVAR_NAME=9
TYPE_NAME=10
NAME=11
WS=12
LINE_COMMENT=13
'ANSWER'=1
'.'=2
'('=3
','=4
')'=5
'param'=6
'equals'=7
'smaller'=8
'typeVar'=9
'type'=10

View File

@ -0,0 +1,23 @@
T__0=1
T__1=2
T__2=3
T__3=4
T__4=5
PARAMLIST_NAME=6
EQUALS_NAME=7
SMALLER_NAME=8
TYPEVAR_NAME=9
TYPE_NAME=10
NAME=11
WS=12
LINE_COMMENT=13
'ANSWER'=1
'.'=2
'('=3
','=4
')'=5
'param'=6
'equals'=7
'smaller'=8
'typeVar'=9
'type'=10

View File

@ -0,0 +1,30 @@
package de.dhbwstuttgart.bytecode;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
public abstract class AStatement implements IStatement {
protected Expression expr;
public AStatement(Expression expr) {
this.expr = expr;
}
@Override
public boolean isExprBinary() {
return (expr instanceof BinaryExpr);
}
@Override
public void genBCForRelOp(MethodVisitor mv,Label branchLabel, Label endLabel, BytecodeGenMethod bytecodeGenMethod) {
mv.visitInsn(Opcodes.ICONST_1);
mv.visitJumpInsn(Opcodes.GOTO, endLabel);
mv.visitLabel(branchLabel);
mv.visitInsn(Opcodes.ICONST_0);
mv.visitLabel(endLabel);
}
}

View File

@ -0,0 +1,11 @@
package de.dhbwstuttgart.bytecode;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
public class ArgumentExpr extends AStatement {
public ArgumentExpr(Expression expr) {
super(expr);
}
}

View File

@ -1,48 +1,45 @@
package de.dhbwstuttgart.bytecode; package de.dhbwstuttgart.bytecode;
import org.objectweb.asm.MethodVisitor; import java.util.List;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
import de.dhbwstuttgart.syntaxtree.StatementVisitor; import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.statement.ArgumentList; import de.dhbwstuttgart.syntaxtree.statement.ArgumentList;
import de.dhbwstuttgart.syntaxtree.statement.Assign; import de.dhbwstuttgart.syntaxtree.statement.Assign;
import de.dhbwstuttgart.syntaxtree.statement.AssignToField; import de.dhbwstuttgart.syntaxtree.statement.AssignToField;
import de.dhbwstuttgart.syntaxtree.statement.Binary; import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr;
import de.dhbwstuttgart.syntaxtree.statement.Block; import de.dhbwstuttgart.syntaxtree.statement.Block;
import de.dhbwstuttgart.syntaxtree.statement.CastExpr; import de.dhbwstuttgart.syntaxtree.statement.CastExpr;
import de.dhbwstuttgart.syntaxtree.statement.DoStmt; import de.dhbwstuttgart.syntaxtree.statement.DoStmt;
import de.dhbwstuttgart.syntaxtree.statement.EmptyStmt; import de.dhbwstuttgart.syntaxtree.statement.EmptyStmt;
import de.dhbwstuttgart.syntaxtree.statement.ExpressionReceiver;
import de.dhbwstuttgart.syntaxtree.statement.FieldVar; import de.dhbwstuttgart.syntaxtree.statement.FieldVar;
import de.dhbwstuttgart.syntaxtree.statement.ForStmt; import de.dhbwstuttgart.syntaxtree.statement.ForStmt;
import de.dhbwstuttgart.syntaxtree.statement.IfStmt; import de.dhbwstuttgart.syntaxtree.statement.IfStmt;
import de.dhbwstuttgart.syntaxtree.statement.InstanceOf; import de.dhbwstuttgart.syntaxtree.statement.InstanceOf;
import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression; import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression;
import de.dhbwstuttgart.syntaxtree.statement.Literal;
import de.dhbwstuttgart.syntaxtree.statement.LocalVar; import de.dhbwstuttgart.syntaxtree.statement.LocalVar;
import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl; import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl;
import de.dhbwstuttgart.syntaxtree.statement.MethodCall; import de.dhbwstuttgart.syntaxtree.statement.MethodCall;
import de.dhbwstuttgart.syntaxtree.statement.NewArray; import de.dhbwstuttgart.syntaxtree.statement.NewArray;
import de.dhbwstuttgart.syntaxtree.statement.NewClass; import de.dhbwstuttgart.syntaxtree.statement.NewClass;
import de.dhbwstuttgart.syntaxtree.statement.Receiver;
import de.dhbwstuttgart.syntaxtree.statement.Return; import de.dhbwstuttgart.syntaxtree.statement.Return;
import de.dhbwstuttgart.syntaxtree.statement.ReturnVoid; import de.dhbwstuttgart.syntaxtree.statement.ReturnVoid;
import de.dhbwstuttgart.syntaxtree.statement.StaticClassName; import de.dhbwstuttgart.syntaxtree.statement.StaticClassName;
import de.dhbwstuttgart.syntaxtree.statement.Super; import de.dhbwstuttgart.syntaxtree.statement.Super;
import de.dhbwstuttgart.syntaxtree.statement.SuperCall; import de.dhbwstuttgart.syntaxtree.statement.SuperCall;
import de.dhbwstuttgart.syntaxtree.statement.This; import de.dhbwstuttgart.syntaxtree.statement.This;
import de.dhbwstuttgart.syntaxtree.statement.UnaryPlus; import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr;
import de.dhbwstuttgart.syntaxtree.statement.WhileStmt; import de.dhbwstuttgart.syntaxtree.statement.WhileStmt;
import de.dhbwstuttgart.syntaxtree.statement.literal.Literal;
import de.dhbwstuttgart.syntaxtree.statement.literal.Null;
public class BytecodeGenLambda implements StatementVisitor{
private LambdaExpression lambdaExpression;
private MethodVisitor mv;
public BytecodeGenLambda(LambdaExpression lambdaExpression, MethodVisitor mv) {
this.lambdaExpression = lambdaExpression;
this.mv = mv;
public class ArgumentVisitor implements StatementVisitor {
private List<Boolean> argListMethCall;
private BytecodeGenMethod bytecodeGenMethod;
public ArgumentVisitor(List<Boolean> argListMethCall, BytecodeGenMethod bytecodeGenMethod) {
this.argListMethCall = argListMethCall;
this.bytecodeGenMethod = bytecodeGenMethod;
} }
@Override @Override
@ -53,20 +50,31 @@ public class BytecodeGenLambda implements StatementVisitor{
@Override @Override
public void visit(LambdaExpression lambdaExpression) { public void visit(LambdaExpression lambdaExpression) {
// TODO Auto-generated method stub lambdaExpression.accept(bytecodeGenMethod);
// Zieltype des Lambas ist Funktionale Interface
// kann nie primitiv sein => un-/boxing wird hier nicht gebraucht
argListMethCall.remove(0);
} }
@Override @Override
public void visit(Assign assign) { public void visit(Assign assign) {
// TODO Auto-generated method stub assign.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(assign.getType()));
argListMethCall.remove(0);
} }
@Override @Override
public void visit(Binary binary) { public void visit(BinaryExpr binary) {
// TODO Auto-generated method stub binary.accept(bytecodeGenMethod);
if(argListMethCall.get(0)) {
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(binary.getType()));
} else {
bytecodeGenMethod.doBoxing(bytecodeGenMethod.getResolver().getResolvedType(binary.getType()));
}
argListMethCall.remove(0);
} }
@Override @Override
@ -77,8 +85,11 @@ public class BytecodeGenLambda implements StatementVisitor{
@Override @Override
public void visit(CastExpr castExpr) { public void visit(CastExpr castExpr) {
// TODO Auto-generated method stub castExpr.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(castExpr.getType()));
argListMethCall.remove(0);
} }
@Override @Override
@ -89,8 +100,11 @@ public class BytecodeGenLambda implements StatementVisitor{
@Override @Override
public void visit(FieldVar fieldVar) { public void visit(FieldVar fieldVar) {
// TODO Auto-generated method stub fieldVar.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(fieldVar.getType()));
argListMethCall.remove(0);
} }
@Override @Override
@ -107,14 +121,21 @@ public class BytecodeGenLambda implements StatementVisitor{
@Override @Override
public void visit(InstanceOf instanceOf) { public void visit(InstanceOf instanceOf) {
// TODO Auto-generated method stub instanceOf.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(instanceOf.getType()));
argListMethCall.remove(0);
} }
@Override @Override
public void visit(LocalVar localVar) { public void visit(LocalVar localVar) {
// TODO Auto-generated method stub localVar.accept(bytecodeGenMethod);
if(!bytecodeGenMethod.isBinaryExp) {
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(localVar.getType()));
}
argListMethCall.remove(0);
} }
@Override @Override
@ -125,14 +146,20 @@ public class BytecodeGenLambda implements StatementVisitor{
@Override @Override
public void visit(MethodCall methodCall) { public void visit(MethodCall methodCall) {
// TODO Auto-generated method stub methodCall.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(methodCall.getType()));
argListMethCall.remove(0);
} }
@Override @Override
public void visit(NewClass methodCall) { public void visit(NewClass methodCall) {
// TODO Auto-generated method stub methodCall.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(methodCall.getType()));
argListMethCall.remove(0);
} }
@Override @Override
@ -141,12 +168,6 @@ public class BytecodeGenLambda implements StatementVisitor{
} }
@Override
public void visit(Receiver receiver) {
// TODO Auto-generated method stub
}
@Override @Override
public void visit(Return aReturn) { public void visit(Return aReturn) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
@ -173,14 +194,11 @@ public class BytecodeGenLambda implements StatementVisitor{
@Override @Override
public void visit(This aThis) { public void visit(This aThis) {
// TODO Auto-generated method stub aThis.accept(bytecodeGenMethod);
}
@Override
public void visit(UnaryPlus unaryPlus) {
// TODO Auto-generated method stub
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(aThis.getType()));
argListMethCall.remove(0);
} }
@Override @Override
@ -195,18 +213,6 @@ public class BytecodeGenLambda implements StatementVisitor{
} }
@Override
public void visit(Null aNull) {
// TODO Auto-generated method stub
}
@Override
public void visit(Literal literal) {
// TODO Auto-generated method stub
}
@Override @Override
public void visit(AssignToField assignLeftSide) { public void visit(AssignToField assignLeftSide) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
@ -224,4 +230,29 @@ public class BytecodeGenLambda implements StatementVisitor{
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override
public void visit(ExpressionReceiver expressionReceiver) {
// TODO Auto-generated method stub
}
@Override
public void visit(UnaryExpr unaryExpr) {
unaryExpr.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(unaryExpr.getType()));
argListMethCall.remove(0);
}
@Override
public void visit(Literal literal) {
literal.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(literal.getType()));
argListMethCall.remove(0);
}
} }

View File

@ -0,0 +1,11 @@
package de.dhbwstuttgart.bytecode;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
public class AssignStmt extends AStatement {
public AssignStmt(Expression rightSide) {
super(rightSide);
}
}

View File

@ -0,0 +1,630 @@
package de.dhbwstuttgart.bytecode;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import de.dhbwstuttgart.bytecode.Exception.BytecodeGeneratorError;
import de.dhbwstuttgart.bytecode.descriptor.DescriptorToString;
import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor;
import de.dhbwstuttgart.bytecode.signature.Signature;
import de.dhbwstuttgart.bytecode.signature.TypeToSignature;
import de.dhbwstuttgart.bytecode.signature.TypeToString;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResultForClass;
import de.dhbwstuttgart.bytecode.utilities.MethodUtility;
import de.dhbwstuttgart.bytecode.utilities.NormalConstructor;
import de.dhbwstuttgart.bytecode.utilities.NormalMethod;
import de.dhbwstuttgart.bytecode.utilities.Resolver;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
import de.dhbwstuttgart.syntaxtree.ASTVisitor;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Constructor;
import de.dhbwstuttgart.syntaxtree.Field;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.GenericDeclarationList;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.ParameterList;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.statement.ArgumentList;
import de.dhbwstuttgart.syntaxtree.statement.Assign;
import de.dhbwstuttgart.syntaxtree.statement.AssignToField;
import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr;
import de.dhbwstuttgart.syntaxtree.statement.Block;
import de.dhbwstuttgart.syntaxtree.statement.CastExpr;
import de.dhbwstuttgart.syntaxtree.statement.DoStmt;
import de.dhbwstuttgart.syntaxtree.statement.EmptyStmt;
import de.dhbwstuttgart.syntaxtree.statement.ExpressionReceiver;
import de.dhbwstuttgart.syntaxtree.statement.FieldVar;
import de.dhbwstuttgart.syntaxtree.statement.ForStmt;
import de.dhbwstuttgart.syntaxtree.statement.IfStmt;
import de.dhbwstuttgart.syntaxtree.statement.InstanceOf;
import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression;
import de.dhbwstuttgart.syntaxtree.statement.Literal;
import de.dhbwstuttgart.syntaxtree.statement.LocalVar;
import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl;
import de.dhbwstuttgart.syntaxtree.statement.MethodCall;
import de.dhbwstuttgart.syntaxtree.statement.NewArray;
import de.dhbwstuttgart.syntaxtree.statement.NewClass;
import de.dhbwstuttgart.syntaxtree.statement.Return;
import de.dhbwstuttgart.syntaxtree.statement.ReturnVoid;
import de.dhbwstuttgart.syntaxtree.statement.StaticClassName;
import de.dhbwstuttgart.syntaxtree.statement.Super;
import de.dhbwstuttgart.syntaxtree.statement.SuperCall;
import de.dhbwstuttgart.syntaxtree.statement.This;
import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr;
import de.dhbwstuttgart.syntaxtree.statement.WhileStmt;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.result.ResultSet;
public class BytecodeGen implements ASTVisitor {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
String type;
public static RefTypeOrTPHOrWildcardOrGeneric THISTYPE = null;
private JavaClassName className;
private String pkgName;
private boolean isInterface;
private Collection<ResultSet> listOfResultSets;
private ResultSet resultSet;
private SourceFile sf;
private File path;
private Optional<Constructor> fieldInitializations;
private int indexOfFirstParam = 0;
private String superClass;
private List<String> tphsClass;
// stores parameter, local vars and the next index on the local variable table,
// which use for aload_i, astore_i,...
HashMap<String, Integer> paramsAndLocals = new HashMap<>();
// stores generics and their bounds of class
HashMap<String, String> genericsAndBounds = new HashMap<>();
private int constructorPos = 0;
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes = new HashMap<>();
byte[] bytecode;
HashMap<JavaClassName, byte[]> classFiles;
private final ArrayList<String> methodNameAndParamsT = new ArrayList<>();
private final ArrayList<String> fieldNameAndParamsT = new ArrayList<>();
private final ArrayList<String> fieldNameSignature = new ArrayList<>();
private List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles;
private GenericsGeneratorResultForClass generatedGenerics;
private Resolver resolver;
private final ClassLoader classLoader;
public BytecodeGen(HashMap<JavaClassName, byte[]> classFiles, Collection<ResultSet> listOfResultSets, List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles, SourceFile sf,
File path, ClassLoader classLoader) {
this.classFiles = classFiles;
this.listOfResultSets = listOfResultSets;
this.simplifyResultsForAllSourceFiles = simplifyResultsForAllSourceFiles;
this.sf = sf;
this.path = path;
this.pkgName = sf.getPkgName();
this.classLoader = classLoader;
}
@Override
public void visit(SourceFile sourceFile) {
for (ClassOrInterface cl : sourceFile.getClasses()) {
System.out.println("in Class: " + cl.getClassName().toString());
BytecodeGen classGen = new BytecodeGen(classFiles, listOfResultSets, simplifyResultsForAllSourceFiles, sf, path, classLoader);
cl.accept(classGen);
classGen.writeClass(cl.getClassName());
}
}
/**
* Associates the bytecode of the class that was build with the classWriter
* {@link #cw} with the class name in the map {@link #classFiles}
*
* @param name name of the class with which the bytecode is to be associated
*/
private void writeClass(JavaClassName name) {
bytecode = cw.toByteArray();
classFiles.put(name, bytecode);
}
public HashMap<JavaClassName, byte[]> getClassFiles() {
return classFiles;
}
@Override
public void visit(ClassOrInterface classOrInterface) {
className = classOrInterface.getClassName();
cw.visitSource(className.getClassName() + ".jav", null);
isInterface = (classOrInterface.getModifiers() & 512) == 512;
int acc = isInterface ? classOrInterface.getModifiers() + Opcodes.ACC_ABSTRACT
: classOrInterface.getModifiers() + Opcodes.ACC_SUPER;
fieldInitializations = classOrInterface.getfieldInitializations();
// resultSet = listOfResultSets.get(0);
boolean isVisited = false;
List<ResultSet> listOfResultSetsList = new ArrayList<>(listOfResultSets);
generatedGenerics = simplifyResultsForAllSourceFiles.stream().map(sr->sr.getSimplifyResultsByName(className)).findFirst().get();
for (int i = 0; i < listOfResultSetsList.size(); i++) {
//for (ResultSet rs : listOfResultSets) {
superClass = classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor());
resultSet = listOfResultSetsList.get(i);
resolver = new Resolver(resultSet);
// tphExtractor.setResultSet(resultSet);
// Nur einmal ausführen!!
if (!isVisited) {
String sig = null;
/*
* if class has generics then creates signature Signature looks like:
* <E:Ljava/...>Superclass
*/
if (classOrInterface.getGenerics().iterator().hasNext() || classOrInterface.getSuperClass().acceptTV(new TypeToSignature()).contains("<")
|| !generatedGenerics.getClassConstraints().isEmpty()) {
List<GenericsGeneratorResult> consClass = generatedGenerics.getClassConstraints();
//
Signature signature = new Signature(classOrInterface, genericsAndBounds, consClass);
sig = signature.createSignatureForClassOrInterface();
System.out.println("Signature: => " + sig);
}
cw.visit(Opcodes.V1_8, acc, classOrInterface.getClassName().toString().replace(".", "/"), sig,
classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor()), null);
isVisited = true;
}
for (Field f : classOrInterface.getFieldDecl()) {
f.accept(this);
}
for (Constructor c : classOrInterface.getConstructors()) {
c.accept(this);
}
for (Method m : classOrInterface.getMethods()) {
m.accept(this);
}
}
}
@Override
public void visit(Constructor field) {
// stores generics and their bounds of method
HashMap<String, String> genericsAndBoundsMethod = new HashMap<>();
field.getParameterList().accept(this);
String id = MethodUtility.createID(resolver, field);
if (methodNameAndParamsT.contains(id)) {
return;
}
methodNameAndParamsT.add(id);
System.out.println("Constructor: " + field.name + " , paramsType: " + id);
String desc = null;
boolean hasGen = false;
for (String paramName : methodParamsAndTypes.keySet()) {
String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToSignature());
System.out.println(typeOfParam);
if (genericsAndBounds.containsKey(typeOfParam) || typeOfParam.contains("$") || typeOfParam.contains("<")) {
hasGen = true;
break;
}
}
String sig = null;
if (hasGen) {
List<GenericsGeneratorResult> constraints = generatedGenerics.getClassConstraints();
Signature signature = new Signature(genericsAndBounds,
methodParamsAndTypes, resultSet, constraints);
sig = signature.createSignatureForConstructor(field);
}
if (field.getParameterList().iterator().hasNext())
System.out.println(field.getParameterList().iterator().next().getType().acceptTV(new TypeToDescriptor()));
NormalConstructor constructor = new NormalConstructor(field, genericsAndBounds, hasGen);
desc = constructor.accept(new DescriptorToString(resultSet));
System.out.println("Constructor: " + field.getName() + " Sig: " + sig + " Desc: " + desc);
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", desc, sig, null);
mv.visitCode();
Block block = fieldInitializations.get().block;
constructorPos += 1;
BytecodeGenMethod gen = new BytecodeGenMethod(className, superClass, resultSet, field, mv, paramsAndLocals, cw,
genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path, block, constructorPos, classLoader);
if (!field.getParameterList().iterator().hasNext()
&& !(field.block.statements.get(field.block.statements.size() - 1) instanceof ReturnVoid)) {
mv.visitInsn(Opcodes.RETURN);
}
mv.visitMaxs(0, 0);
mv.visitEnd();
}
@Override
public void visit(Method method) {
// TODO: check if the method is static => if static then the first param will be
// stored in pos 0
// else it will be stored in pos 1 and this will be stored in pos 0
String retType = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor());
String id = MethodUtility.createID(resolver, method);
if (methodNameAndParamsT.contains(id)) {
return;
}
methodNameAndParamsT.add(id);
System.out.println("Method: " + method.name + " , paramsType: " + id);
// stores generics and their bounds of method
HashMap<String, String> genericsAndBoundsMethod = new HashMap<>();
method.getParameterList().accept(this);
String methDesc = null;
// Method getModifiers() ?
int acc = isInterface ? Opcodes.ACC_ABSTRACT : method.modifier;
System.out.println(acc);
/* Prüfe, ob die Rückgabe-Type der Methode eine Type-Variable ist */
boolean hasGenInParameterList = genericsAndBounds.containsKey(retType) || retType.contains("TPH ")
|| resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature())
.contains("<");
/*
* Wenn die Rückgabe-Type eine Typ-variable ist, erzeuge direkt die Signature,
* wenn nicht, prüfe, ob einer der Parameter Typ-Variable als Typ hat
*/
if (!hasGenInParameterList) {
for (String paramName : methodParamsAndTypes.keySet()) {
String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToDescriptor());
String sigOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToSignature());
if (genericsAndBounds.containsKey(typeOfParam) || typeOfParam.contains("TPH ")
|| sigOfParam.contains("<")) {
hasGenInParameterList = true;
break;
}
}
}
// TODO: Test if the return-type or any of the parameter is a parameterized
// type. (VP)
// then create the descriptor with the new syntax.
String sig = null;
/*
* method.getGenerics: <....> RT method(..)
*/
boolean hasGen = method.getGenerics().iterator().hasNext() || hasGenInParameterList;
/* if method has generics or return type is TPH, create signature */
// zwite operand muss weggelassen werden
if (hasGen || resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToString())
.equals("TPH")) {
List<GenericsGeneratorResult> constraints = generatedGenerics.getMethodConstraintsByID(id);
List<GenericsGeneratorResult> classConstraints = generatedGenerics.getClassConstraints();
Signature signature = new Signature(genericsAndBoundsMethod, genericsAndBounds,
methodParamsAndTypes, resultSet, constraints,classConstraints);
sig = signature.createSignatureForMethod(method);
}
System.out.println(method.getName() + " ==> " + sig);
NormalMethod meth = new NormalMethod(method, genericsAndBounds, genericsAndBoundsMethod, hasGen);
methDesc = meth.accept(new DescriptorToString(resultSet));
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC + acc, method.getName(), methDesc, sig, null);
mv.visitCode();
BytecodeGenMethod gen = new BytecodeGenMethod(className, superClass, resultSet, method, mv, paramsAndLocals, cw,
genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path, classLoader);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
@Override
public void visit(ParameterList formalParameters) {
paramsAndLocals = new HashMap<>();
methodParamsAndTypes = new HashMap<>();
Iterator<FormalParameter> itr = formalParameters.iterator();
int i = 1;
while (itr.hasNext()) {
FormalParameter fp = itr.next();
paramsAndLocals.put(fp.getName(), i);
methodParamsAndTypes.put(fp.getName(), resultSet.resolveType(fp.getType()).resolvedType);
fp.accept(this);
i++;
}
}
@Override
public void visit(FormalParameter formalParameter) {
formalParameter.getType().accept(this);
}
@Override
public void visit(RefType refType) {
type = "L" + refType.toString() + ";";
}
@Override
public void visit(SuperWildcardType superWildcardType) {
// TODO Auto-generated method stub
}
@Override
public void visit(TypePlaceholder typePlaceholder) {
// TODO Auto-generated method stub
}
@Override
public void visit(ExtendsWildcardType extendsWildcardType) {
// TODO Auto-generated method stub
}
@Override
public void visit(GenericRefType genericRefType) {
// TODO Auto-generated method stub
}
// ??
@Override
public void visit(FieldVar fieldVar) {
System.out.println("In FieldVar ---");
// cw.newField(fieldVar.receiver.toString(), fieldVar.fieldVarName.toString(), fieldVar.getType().toString());
FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE, fieldVar.fieldVarName, "L" + fieldVar.getType() + ";",
null, null);
fv.visitEnd();
}
@Override
public void visit(Field field) {
System.out.println("In Field ---");
String des = "L";
if (resultSet.resolveType(field.getType()).resolvedType instanceof TypePlaceholder) {
des += Type.getInternalName(Object.class);
} else {
des += resultSet.resolveType(field.getType()).resolvedType.acceptTV(new TypeToDescriptor());
}
des += ";";
System.out.println(des);
String sig = resultSet.resolveType(field.getType()).resolvedType.acceptTV(new TypeToSignature(generatedGenerics.getClassConstraints()));
System.out.println(sig);
if (sig.charAt(sig.length() - 1) != (";").charAt(0)) {
sig += ";";
}
String nameAndDesc = field.getName() + "%%" + des;
String nameAndSig = field.getName() + "%%" + sig;
if (fieldNameAndParamsT.contains(nameAndDesc)) {
if (fieldNameSignature.contains(nameAndSig)) {
return;
}
throw new BytecodeGeneratorError("Bytecode generation aborted due to duplicate field name&signature");
}
fieldNameAndParamsT.add(nameAndDesc);
fieldNameSignature.add(nameAndSig);
cw.visitField(field.modifier, field.getName(), des, sig, null);
}
@Override
public void visit(LambdaExpression lambdaExpression) {
// TODO Auto-generated method stub
}
@Override
public void visit(Assign assign) {
// TODO Auto-generated method stub
}
@Override
public void visit(BinaryExpr binary) {
}
@Override
public void visit(Block block) {
// TODO Auto-generated method stub
}
@Override
public void visit(CastExpr castExpr) {
// TODO Auto-generated method stub
}
@Override
public void visit(EmptyStmt emptyStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(ForStmt forStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(IfStmt ifStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(InstanceOf instanceOf) {
// TODO Auto-generated method stub
}
@Override
public void visit(LocalVar localVar) {
// TODO Auto-generated method stub
}
@Override
public void visit(LocalVarDecl localVarDecl) {
// TODO Auto-generated method stub
}
@Override
public void visit(MethodCall methodCall) {
// TODO Auto-generated method stub
}
@Override
public void visit(NewClass methodCall) {
// TODO Auto-generated method stub
}
@Override
public void visit(NewArray newArray) {
// TODO Auto-generated method stub
}
@Override
public void visit(Return aReturn) {
// TODO Auto-generated method stub
}
@Override
public void visit(ReturnVoid aReturn) {
// TODO Auto-generated method stub
}
@Override
public void visit(StaticClassName staticClassName) {
// TODO Auto-generated method stub
}
@Override
public void visit(Super aSuper) {
// TODO Auto-generated method stub
}
@Override
public void visit(This aThis) {
// TODO Auto-generated method stub
}
@Override
public void visit(WhileStmt whileStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(DoStmt whileStmt) {
// TODO Auto-generated method stub
}
// ???
@Override
public void visit(Literal literal) {
// TODO Auto-generated method stub
}
@Override
public void visit(ArgumentList argumentList) {
// TODO Auto-generated method stub
}
@Override
public void visit(GenericTypeVar genericTypeVar) {
// TODO Auto-generated method stub
}
@Override
public void visit(GenericDeclarationList genericTypeVars) {
// TODO Auto-generated method stub
}
@Override
public void visit(AssignToField assignLeftSide) {
// TODO Auto-generated method stub
}
@Override
public void visit(AssignToLocal assignLeftSide) {
// TODO Auto-generated method stub
}
@Override
public void visit(SuperCall superCall) {
}
@Override
public void visit(ExpressionReceiver expressionReceiver) {
// TODO Auto-generated method stub
}
@Override
public void visit(UnaryExpr unaryExpr) {
throw new NotImplementedException();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,19 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.Exception;
/**
* @author fayez
*
*/
public class BytecodeGeneratorError extends RuntimeException {
/**
* @param message
*/
public BytecodeGeneratorError(String message) {
super(message);
}
}

View File

@ -0,0 +1,25 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.Exception;
/**
* @author fayez
*
*/
public class NotFoundException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @param message
*/
public NotFoundException(String message) {
super(message);
}
}

View File

@ -0,0 +1,26 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.Exception;
/**
* @author fayez
*
*/
public class NotInCurrentPackageException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @param message
*/
public NotInCurrentPackageException(String message) {
super(message);
}
}

View File

@ -0,0 +1,9 @@
package de.dhbwstuttgart.bytecode;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
public interface IStatement {
public boolean isExprBinary();
public void genBCForRelOp(MethodVisitor mv, Label branchLabel, Label endLabel, BytecodeGenMethod bytecodeGenMethod);
}

View File

@ -0,0 +1,29 @@
package de.dhbwstuttgart.bytecode;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
import de.dhbwstuttgart.syntaxtree.statement.Statement;
public class IfStatement extends AStatement{
private Statement then_block;
private Statement else_block;
public IfStatement(Expression expr, Statement then_block, Statement else_block) {
super(expr);
this.then_block = then_block;
this.else_block = else_block;
}
@Override
public void genBCForRelOp(MethodVisitor mv,Label branchLabel, Label endLabel, BytecodeGenMethod bytecodeGenMethod) {
bytecodeGenMethod.isBinary(false);
this.then_block.accept(bytecodeGenMethod);
mv.visitLabel(branchLabel);
this.else_block.accept(bytecodeGenMethod);
}
}

View File

@ -0,0 +1,26 @@
package de.dhbwstuttgart.bytecode;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
import de.dhbwstuttgart.syntaxtree.statement.Statement;
public class LoopStmt extends AStatement {
private Statement loopBlock;
public LoopStmt(Expression expr, Statement loopBlock) {
super(expr);
this.loopBlock = loopBlock;
}
@Override
public void genBCForRelOp(MethodVisitor mv,Label branchLabel, Label endLabel, BytecodeGenMethod bytecodeGenMethod) {
bytecodeGenMethod.isBinary(false);
this.loopBlock.accept(bytecodeGenMethod);
mv.visitJumpInsn(Opcodes.GOTO, endLabel);
mv.visitLabel(branchLabel);
}
}

Some files were not shown because too many files have changed in this diff Show More