Compare commits

...

265 Commits

Author SHA1 Message Date
2c9f085cca modified: src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Zeilen 606 - 623 eingefuegt, um die parallel berechneten Ergebnisse richtig zu filtern
TODO
- Fuer Variance -1 muss das gleiche gemacht werden
- ab Zeile 550: nextSetasListRest muss nach jedem fork aufruf gefiltert werden.
2018-08-09 18:41:28 +02:00
3e4e66d60d modified: ../../src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   ../../src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   ../../test/bytecode/javFiles/Matrix.jav
	modified:   ../../test/bytecode/javFiles/applyLambda.jav
? extends gen_nv =. ? super gen_nv sind in den RES
2018-08-05 15:05:17 +02:00
883ab50f94 modified: ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnify.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   ../bytecode/javFiles/Matrix.jav
einige Aenderungen
2018-07-29 00:07:00 +02:00
9d37e8f637 modified: ../../src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java

Parallelverarbeitungansatz implementiert
Wirft noch ConcurrentModificationException
Das Ergebnis der Parallelverarbeit fork.join muss in Ziel 530 muss noch geklaert werden
2018-07-25 20:15:29 +02:00
496842a3bf new file: test/bytecode/FacultyTest.java 2018-07-25 00:55:01 +02:00
608d73452a new file: src/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java 2018-07-25 00:53:40 +02:00
421169a72d modified: src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   test/bytecode/MatrixTest.java
	src/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java
2018-07-25 00:52:28 +02:00
c43d9ab9f5 Merge branch 'bytecode2' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unifyOptimierung 2018-07-23 17:23:47 +02:00
4e5c75673d new file: ../../test/bytecode/Tph3Test.java
new file:   ../../test/bytecode/javFiles/Tph3.jav
Test mit wechselseitiger Rekursion
2018-07-19 13:57:01 +02:00
2421dd0222 modified: ../../test/bytecode/LambdaTest.java
jetzt korrekt
	modified:   ../../test/bytecode/Tph2Test.java
jetzt korrekt
	modified:   ../../test/bytecode/TphTest.java
jetzt korrekt
	modified:   ../../test/bytecode/applyLambdaTest.java
jetzt korrekt
	modified:   ../../test/bytecode/javFiles/Tph.jav
Rueckgabewert veraendert
2018-07-19 13:54:31 +02:00
14be882b7b LambdaTest Funktioniert. 2018-07-18 22:49:21 +02:00
448d3e04f8 modified: ../../test/bytecode/LambdaTest.java 2018-07-18 17:56:20 +02:00
fe99db81b3 modified: ../../test/bytecode/LambdaTest.java
Lambda-Ausruck wird ausgewertet. Funktioniert nicht, vermutich, weil Lambda-Methode apply private
2018-07-18 17:54:44 +02:00
c3ca4777bb modified: ../../test/bytecode/LambdaTest.java
noch unvllstaendig

	modified:   ../../test/bytecode/MatrixTest.java
Test korrekt
	modified:   ../../test/bytecode/javFiles/Matrix.jav
import byte entfernt, so dass Laufzeit passt
2018-07-18 17:01:01 +02:00
16b7db9218 modified: test/bytecode/MatrixTest.java
Test einfeguegt nicht getestet
	modified:   test/bytecode/OLTest.java
Test eingefuegt
	modified:   test/bytecode/javFiles/OL.jav
- Main in OLMain umbenannt
- Klassen publich gemacht
2018-07-18 15:34:49 +02:00
2d5f03a3e0 Bugs 89 und 90 2018-07-18 13:51:05 +02:00
fd64b84072 modified: TYPEStmt.java
Bei der Addition + Abfragen eingefuegt, ob die Subtypen von Number jeweils import sind. Nur dann werden Annahmen erstellt.

	modified:   ../../../../../test/bytecode/javFiles/Matrix.jav
	modified:   ../../../../../test/bytecode/javFiles/OL.jav
2018-07-17 17:38:00 +02:00
2a5c727400 new file: applyLambdaTest.java
modified:   javFiles/Lambda.jav
	new file:   javFiles/applyLambda.jav
An das JavaTXExamples angepasst
2018-07-14 09:28:13 +02:00
d373b3dbf8 merge 2018-07-10 22:26:52 +02:00
7c3ca93c0b Bug 88 gefixt.
new file:   src/de/dhbwstuttgart/bytecode/ArgumentVisitor.java
Visitor für Argumente des Method Call einer Methode aus Standard-Bibliothek und dient dazu,
wenn die Argument eine primitive Typ besitzt dann wird unboxing gemacht.
Signatur von Konstruktoren angepasst.
2018-07-10 22:15:26 +02:00
72a4c64c5c modified: ../../test/bytecode/javFiles/Matrix.jav
Konstruktoren eingefuegt
2018-07-06 10:37:59 +02:00
bd0bfed2cb Matrix Test läuft. Code muss noch aufgeräumt werden 2018-07-04 22:18:16 +02:00
cee86a6b61 Merge branch 'bytecode2' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bytecode2 2018-07-04 12:07:21 +02:00
f1f34a6733 modified: test/javFiles/Matrix.jav 2018-07-04 12:07:11 +02:00
1a2454e00b modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Kommentare zur Max Min optimierung rasugenommen
2018-07-04 11:47:02 +02:00
bc1a796e28 modified: ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java 2018-07-03 11:54:24 +02:00
9f53d1fdc2 Merge branch 'bytecode2' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bytecode2 2018-07-03 11:20:33 +02:00
69706ee1d2 Bug 82 gefixt und getestet. Descriptor von MethodCall von Interface korrigiert. 2018-07-03 11:15:58 +02:00
b8e229cf3f modified: ../../src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java
	modified:   ../javFiles/Matrix.jav
2018-07-02 17:24:16 +02:00
e0c5afcd6d modified: test/bytecode/javFiles/Lambda.jav
modified:   test/javFiles/Vector.jav
	modified:   test/typeinference/UnifyTest.java
2018-07-02 11:11:29 +02:00
9123e222f4 Vector TEst anfügen 2018-06-28 16:47:05 +02:00
29bd9a3f4f remove logFile 2018-06-27 15:39:04 +02:00
7926c25c7d Soviel wie möglich unnötige TPHs aus Signaturen von Paramtrisierten Typen entfernt 2018-06-27 15:20:35 +02:00
b4c604e2b1 Bug in der Methode simplifyPairs gefixt.
Bug 82 gefixt.
TPHs in paramtrisierten Typen als TypeVariablen in Signature hinzugefügt.
Lambda.jav funktioniert.
2018-06-27 14:49:22 +02:00
d8bb4d6188 modified: test/bytecode/javFiles/Lambda.jav
Lambda auf apply angepasst
2018-06-23 10:54:14 +02:00
0ecaf36648 modified: src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
Bei Literal die Zuweisung des Typs eingefuegt aber wieder auskommentiert,
weil es im Moment nur double Literals gibt.
	modified:   test/javFiles/Lambda.jav
2018-06-23 10:42:46 +02:00
2eb7a63480 modified: src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java
FunN$$ eingefuegt

	modified:   src/de/dhbwstuttgart/syntaxtree/type/FunN.java
	modified:   src/de/dhbwstuttgart/typeinference/assumptions/FunNClass.java
	modified:   src/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java
	modified:   src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
Methodcall einige Bugs sowohl beim apply als uch bei allen anderen gefixt.

	modified:   test/javFiles/Lambda.jav
2018-06-23 01:05:13 +02:00
11649b39d3 generateBCForFun() um Parameter path erweitert. 2018-06-20 18:15:44 +02:00
303cfa5409 log entfernt 2018-06-20 18:08:25 +02:00
660ef68f7e generateBytecode() um Parameter path erweitert. Alle Tests angepasst 2018-06-20 18:07:17 +02:00
23eab0c9a4 TPHs, die nicht in ParameterListe der Methode vorkommen, werden in Signature geschrieben 2018-06-19 14:56:22 +02:00
162ca3eb27 Merge branch 'bytecode2' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bytecode2 2018-06-19 13:32:24 +02:00
6d70464a1c TPH X < TPH Y <...< TPH Z vereinfacht => TPH X < TPH Z und Signature-Erzeugung wird angepasst 2018-06-19 13:31:39 +02:00
04d3ac84e7 jeweils apply eingefuegt, was nicht funktioniert
modified:   ../../test/typeinference/UnifyTest.java
Matrix auskommentiert und Lambda einkommentiert
2018-06-15 16:19:12 +02:00
2db5ecc260 logFile deleted 2018-06-13 15:51:59 +02:00
b325e205a1 Bugs gefixt. Bytecode-Erzeugung für MethodCall ergänzt. Bytecode für Matrix-Test (Funktioniert noch nicht ganzErzeugung Signatures und Descriptors verbessert 2018-06-13 15:50:05 +02:00
ff2bca5ce5 Alle TPHS einer Methode und pairs (TPH < SuperTPH) werden gesammelt,
gemeinsamme TPHs werden bestimmt, die Klassenkopf als Type-Variables
	definiert werden sollen.
	Erzeugung von Signature angepasst.
2018-06-12 11:41:59 +02:00
5a0e53485c modified: src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
Unary-Expression SMALLERNEQDOT eingefuegt
	modified:   test/bytecode/javFiles/Fac.jav
2018-05-30 17:23:55 +02:00
66078360da Alle TPH der Methode werden in eine Liste gespeichert.
Bug gefixt => FacTest liefert richtiges Ergebnis.
Deskriptoren von Methoden, in denen TPHs auftauchen, werden erzeugt.
Signaturen von von Methoden, in denen TPHs auftauchen, werden erzeugt.
Test, RückagbeTypen der Methoden = TPH und ParameterTypen = TPH.
2018-05-30 15:27:21 +02:00
bb26112a9b modified: ../../../target/JavaTXcompiler-0.1-jar-with-dependencies.jar
modified:   Fac.jav
	modified:   Faculty.jav
	modified:   OL.jav
	modified:   While.jav
	modified:   ../../javFiles/AddLong.jav
2018-05-30 00:27:20 +02:00
97d893e66b Merge branch 'plugin' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into plugin
merge
2018-05-28 16:36:46 +02:00
57fb90afaf modified: src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnify.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
LogFile  optional gemacht
2018-05-28 16:35:47 +02:00
63ac79f02c Hotfix für Typparsen Problem 2018-05-28 16:21:52 +02:00
07fa62d11d merge Keine Ahnung mit was ... 2018-05-28 16:21:43 +02:00
66587a8f71 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
SMALERNEQDOT in Regel a <!=. Theta korrigiert
SMALERNEQDOT in Regel Theta <!=. a geloescht
2018-05-28 16:07:29 +02:00
581e5e574e Merge branch 'bytecode2' into plugin 2018-05-25 14:41:22 +02:00
ae14dfd947 modified: src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
2018-05-25 14:39:54 +02:00
9d53d9d5d1 modified: src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java
kleiner Fehler korrigiert
	modified:   test/javFiles/Matrix.jav
2018-05-25 11:16:02 +02:00
58f5e17ab5 FacTest.java 2018-05-25 10:01:44 +02:00
6fce2760c5 While.jav 2018-05-25 09:53:30 +02:00
1de897fb1f modified: src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java
System.out.println geloescht
2018-05-24 17:59:51 +02:00
87dede5d5f modified: ../../src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java
F-Bounded Problematik durche neues greater ggf. geloest.
Es werden Falle ausgeschlossen. Diese Faelle muessen noch ergaenzt werden.
2018-05-24 17:45:10 +02:00
f085f9f499 Merge branch 'bytecode2' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bytecode2 2018-05-24 16:44:28 +02:00
a40d2b991f kleine Änderung 2018-05-24 16:44:05 +02:00
704415ae3b Merge branch 'unifyOptimierung' into plugin
fixed	test/javFiles/Matrix.jav
2018-05-24 16:43:31 +02:00
65531ac12e modified: ../../src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java
modified:   ../../src/de/dhbwstuttgart/typeinference/constraints/Pair.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/PairOperator.java
Einführung eines neuen Operators SMALLERNEQDOT um Ungleichungen a <!=. Number für die Relationsoperatoren einfuehren zu koennen.

	modified:   ../../test/javFiles/Matrix.jav
2018-05-24 16:20:57 +02:00
34e632b872 modified: ../../src/de/dhbwstuttgart/core/JavaTXCompiler.java
Reduce ausgetauscht bei ArgPara und Returntype
	modified:   ../../src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
isUndefinedPair korrigiert.
	modified:   ../../test/bytecode/LambdaTest.java
	modified:   ../../test/bytecode/javFiles/Plus.jav
	modified:   ../../test/bytecode/javFiles/RelOps.jav
2018-05-24 14:11:04 +02:00
3470215bae Merge branch 'bytecode2' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bytecode2 2018-05-24 10:48:57 +02:00
f5398fa8e9 deleted: ../../test/logFiles/log 2018-05-24 10:34:50 +02:00
f617ad8946 modified: ../../src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
Relationen auf verschiedene Numeric-Typen umgestellt
im equals Null abgefragt
2018-05-24 10:28:22 +02:00
876ec6a4f6 Merge branch 'bytecode2' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unifyOptimierung
Conflicts:
	src/de/dhbwstuttgart/core/JavaTXCompiler.java
solved
2018-05-24 09:41:15 +02:00
26d9b1215f modified: ../../src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java
	modified:   ../../test/javFiles/Matrix.jav
F-Bounded angefangen
2018-05-24 09:17:31 +02:00
0f29bc038a Bugs gefixt. Tests für relationalen Operatoren(GreaterEqualTest, ...) laufen.
Für Typplaceholder werden Generics verwendet.

Neue Tests angefügt.
2018-05-23 15:38:41 +02:00
a5ed5a2a46 Merge branch 'unifyOptimierung' into plugin 2018-05-22 17:29:44 +02:00
c597b0430a modified: ../../src/de/dhbwstuttgart/core/JavaTXCompiler.java
cardProd als Variable eingfuegt
	modified:   ../../src/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java
toString() eingfuegt
	modified:   ../../src/de/dhbwstuttgart/syntaxtree/GenericDeclarationList.java
toString() eingfuegt
	modified:   ../../src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
BinaryOp <. statt =.
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Bei nicht importierten (result []) undefinPair gesetzt
	modified:   ../javFiles/Matrix.jav
falsche importe rausgenommen
2018-05-22 17:10:07 +02:00
06a0cb8eaf modified: TypeUnifyTask.java
noAllErasedElements eingefuegt
2018-05-19 10:13:08 +02:00
b5a601d798 modified: TypeUnifyTask.java
Varianceweitergabe in den verschiedenen Cases eingefuegt
Erste Zaehlungen eingefuegt
2018-05-19 09:50:57 +02:00
7ea6777906 modified: ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   ../javFiles/Lambda.jav
	modified:   ../typeinference/UnifyTest.java
2018-05-18 13:12:49 +02:00
6b1896f58c modified: src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
modified:   src/de/dhbwstuttgart/typeinference/unify/distributeVariance.java
greaterFUNN und smallFUNN fuer generierte TPHs Variance gesetzt
	modified:   test/javFiles/Lambda.jav
vom bytecode ruebergeholt
2018-05-18 09:55:45 +02:00
d81c06cdd9 modified: ../../src/de/dhbwstuttgart/typeinference/unify/distributeVariance.java
Implementierung fuer FuNN eingefuegt
	deleted:    ../../src/de/dhbwstuttgart/typeinference/unify/inheritVariance.java

wahrscheinlich bei FuNN-Regeln Variance setzen.
2018-05-18 00:03:07 +02:00
8baff8f376 modified: ../../src/de/dhbwstuttgart/core/JavaTXCompiler.java
Variancenvererbung eingefuegt
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Variancenvererbung geloescht
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java
	modified:   ../../test/typeinference/UnifyTest.java
2018-05-17 22:51:41 +02:00
bc2cab8c95 modified: src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java
	modified:   test/javFiles/Lambda.jav
	modified:   test/javFiles/Lambda3.jav
2018-05-17 18:07:21 +02:00
dca5d21c23 JavaCompilerCoreWithDependencies upload 2018-05-17 12:47:01 +02:00
51a2acdbaf modified: src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   test/typeinference/UnifyTest.java
2018-05-17 11:42:03 +02:00
dcc36f082f code aufräumen 2018-05-16 13:37:31 +02:00
9575afd0b4 Fun umbenannt und Argumente umgedreht 2018-05-15 10:33:30 +02:00
5c797a44a1 modified: ../../src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
disableWildcardtable in den FUNN-Regeln eingefuegt.
2018-05-10 09:07:33 +02:00
87dbcfdad4 Merge branch 'unifyOptimierung' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unifyOptimierung
Merge
2018-05-09 18:10:17 +02:00
8048af2106 modified: ../../test/javFiles/Lambda2.jav
modified:   ../../test/typeinference/UnifyTest.java
2018-05-09 18:10:08 +02:00
e4243b612c modified: src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
Operatoren neue getypte
Returnargument bei FUNN nach hinten verschoben
	modified:   src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
Returnargument bei FUNN nach hinten verschoben
Wildcards in Argumenten von als Undefined Pairs (funktioniert noch nicht)
Methode wrongWildcard eingefuegt
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java
Methode doubleWildcard ind wrongWildcard umbenannt
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java
Methode doubleWildcard ind wrongWildcard umbenannt
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java
Methode doubleWildcard ind wrongWildcard umbenannt
2018-05-09 18:05:06 +02:00
da4c59f2cf modified: ../../src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
modified:   ../../test/typeinference/UnifyTest.java
2018-05-09 16:24:28 +02:00
1c22fc7d57 Merge branch 'bytecode2' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unifyOptimierung
merge bytecode2
2018-05-09 13:29:11 +02:00
0b7aea21d9 modified: ../../test/bytecode/LambdaTest.java
modified:   ../../test/bytecode/javFiles/Lambda2.jav
2018-05-08 18:52:43 +02:00
521a1cbf3b Bug 77 gefixt 2018-05-08 17:42:58 +02:00
22ca2cbd4a modified: BytecodeGenMethod.java 2018-05-08 11:28:24 +02:00
49ea4ee283 Pfad der erzeugten klassendateien angepasst 2018-05-08 10:19:13 +02:00
225dc16a89 modified: test/typeinference/UnifyTest.java 2018-05-08 09:23:20 +02:00
4738add4fc modified: ../../../../../test/javFiles/Matrix.jav
modified:   ../../../../../test/typeinference/UnifyTest.java
2018-05-07 15:31:31 +02:00
bc99dc4c8b Merge branch 'plugin' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into plugin 2018-05-02 21:30:11 +02:00
2bbf9eac36 target/repository anlegen 2018-05-02 21:08:32 +02:00
a785c85d42 tests 2018-05-02 20:54:07 +02:00
ec2b501e63 new file: test/javFiles/LambdaField.jav
modified:   test/typeinference/UnifyTest.java
Lambda-Ausdruck als Attribute/field eingefuegt
2018-04-26 15:10:23 +02:00
8be4f94edf modified: test/javFiles/Matrix.jav
In Matrix.jav Binary-Operation eingefuegt.

	new file:   test/javFiles/Meth_Gen.jav
	new file:   test/typeinference/Meth_GenTest.java
Test zu Constraints ueber eine Methode hinaus
2018-04-25 23:32:12 +02:00
1b6cae1be0 GenTest angefügt 2018-04-25 16:44:27 +02:00
41774b3faf Merge mit bytecode 2018-04-25 16:13:23 +02:00
62d44eb15c modified: ../../src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Undefined Pairs auf oberster Ebene wird zu new HashTable<>() in compute
	new file:   ../../src/de/dhbwstuttgart/typeinference/unify/inheritVariance.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
Unterscheidung zw. <. <? ein compere eingefuegt
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java
Attribut wildcardable eingefuegt
2018-04-24 00:53:33 +02:00
5f8c73f176 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
In compare wird die Gleichung a =. Theta neu gefiltert
2018-04-22 00:56:49 +02:00
0ae777b4ac modified: src/de/dhbwstuttgart/core/JavaTXCompiler.java
varianceInheritance nach TypeUnifyTask.java verschoben
Kommentar eingefuegt

TODO:
1. compare-Funktinen nochmals ueberpruefen
2. Undef-Pairs in JavaTXiCompiler.java abfangen
3. ? extends bei allen Argumenttypen und Returntypen rauslassen
2018-04-20 23:52:12 +02:00
087170bdbf modified: src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java
Variance wieder auskommentiert
	modified:   test/javFiles/Matrix.jav
import String
2018-04-20 13:16:49 +02:00
93d0caaefb modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Varianceberechnung geaendert
2018-04-20 09:36:29 +02:00
1f031149d3 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java
Varianceweitergabe eingefuegt
2018-04-20 01:08:35 +02:00
fc870fd706 modified: ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java 2018-04-18 19:44:00 +02:00
4450f5c0cd Merge 2018-04-18 15:08:37 +02:00
478a2df3dc Statische Methoden Test 2018-04-18 11:51:10 +02:00
59243d9f94 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java 2018-04-17 16:31:13 +02:00
82b08c5aae modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
Wildcard Ordnung veraendert
2018-04-17 14:25:52 +02:00
615983bf37 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
resuat add in cartesion angepasst
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java

equals in UnfyPair auf UndefinedPairs angepasst
2018-04-13 18:13:31 +02:00
21bc2a67a1 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java 2018-04-11 16:58:38 +02:00
52a96d7253 OL Test eingefügt 2018-04-11 13:55:32 +02:00
fef4d27d21 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java 2018-04-11 11:10:08 +02:00
603c4c9c46 modified: ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
logging ergaenzt

	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java
getSubstitution() durch getAllSubstitutions() ersetzt
2018-04-06 20:01:14 +02:00
baee0024e9 modified: ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Zu beginn von unify werden doppelte wildcard konstruktionen entfernt
Variableneumbenennung bei smaller in Fall 1 weider entfernt

	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/interfaces/IMatch.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java
In computeGreater unify durch match ersetzt

	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java

	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java
Abfrage ob eine doppelte wildcard konstruktion vorhanden ist eingefuegt
2018-04-05 18:09:24 +02:00
1baaf79f8c modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java
UndefPairs werden zurueckgegegeben und die naechsten gefiltert

protected boolean isUndefinedPairSet(Set<UnifyPair> s) hat Fehler
2018-04-04 21:47:07 +02:00
52f480147e modified: src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java
modified:   src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java

Subsitution auf UnifyPair umgestellt
2018-04-04 01:14:30 +02:00
9717c54d53 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Mehrfacher Aufruf von computeCartesianRecursive entfernt
2018-04-03 14:16:38 +02:00
c271c689de modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
abhaengige Substitutionen auch bei Faellen 1 - 8 eingefuegt
2018-04-03 10:29:58 +02:00
24c27303dd modified: src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java
modified:   src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java
Substututions die eine UnifyPair erzeugen eingefuegt
UnifyCase1-8 weitermachen
2018-04-01 22:04:10 +02:00
117106a7b3 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
? ext theta bei smaller eingefuegt

	modified:   src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java
basiPair und Subsitution nur noch gefuegt, wen wirk etwas eingesetzt wurde

	modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java
unifier umbenannt in substitution
getBasePair und getSubsitutuon eingefuegt
2018-04-01 17:07:58 +02:00
5680f913ef modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
new file:   src/de/dhbwstuttgart/typeinference/unify/distributeVariance.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java
	new file:   src/de/dhbwstuttgart/typeinference/unify/visitUnifyTypeVisitor.java
2018-03-28 17:42:25 +02:00
22ff521d08 Aufräumen 2018-03-28 15:35:04 +02:00
32ab198f9e Bugfix für duplicate methods 2018-03-28 14:57:36 +02:00
fae26a8f26 modified: src/de/dhbwstuttgart/typeinference/unify/freshPlaceholder.java
modified:   src/de/dhbwstuttgart/typeinference/unify/interfaces/UnifyTypeVisitor.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java

Visitors verallgemeinert
2018-03-28 12:06:23 +02:00
bb5a4e8580 Bug 72 gefixt 2018-03-28 11:31:32 +02:00
000c16b907 Gencoy ASP Generator implementieren 2018-03-27 23:56:12 +02:00
87a2ed8117 APS GeneratorTest.simple anfügen 2018-03-27 14:25:54 +02:00
a0de7a4467 Test, bei dem Bug 72 auftritt 2018-03-24 20:28:26 +01:00
4886976752 Fehler in FCGenerator beheben 2018-03-23 17:20:15 +01:00
daf684deef ASP Factory für Algorithmus von Herr Gencay 2018-03-23 16:54:32 +01:00
0b680f831d modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java
2018-03-22 20:40:22 +01:00
41c87e3085 Merge branch 'bigRefactoring' into sat 2018-03-22 13:50:30 +01:00
bcee5e5209 Fehler im Parsen von Package beheben 2018-03-22 11:41:59 +01:00
95e9b2dbda modified: src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java
Variance auf PlacehloderType uebertragen
2018-03-22 11:26:29 +01:00
72f27fab7a Fehler in ASTFactory Generierung von Superinterfaces beheben 2018-03-22 11:17:51 +01:00
06bb978cf6 Testfall erweitern 2018-03-21 18:08:33 +01:00
dbe05bb718 modified: src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/FCGenerator.java
Feher rausgemacht

TODO: Varianven werden nicht uebertragen wahrscheinlich subst
2018-03-21 17:37:34 +01:00
9a735e86dd GenericFC Test anfügen 2018-03-21 17:26:43 +01:00
240d57a8ba Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bigRefactoring 2018-03-21 17:26:23 +01:00
dd18c7c40e Test anfügen 2018-03-21 17:24:12 +01:00
45ccfb58e3 Test commit 2018-03-21 17:10:40 +01:00
4ac99b61bf Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unify-test 2018-03-21 17:07:14 +01:00
f107c8d1f7 modified: src/de/dhbwstuttgart/core/JavaTXCompiler.java
Variancebestimmung fuer Argument- und Returntypen der Methoden eingefuegt.
2018-03-21 17:03:32 +01:00
161c1a1b53 Test anfügen 2018-03-21 15:15:31 +01:00
6b1a4eddfc Java 9 zu Java 8 ändern. Sollte ausreichen 2018-03-21 14:40:47 +01:00
ae7a63fbca Tests fix 2018-03-21 14:22:30 +01:00
79810be94f FC Generator berücksichtig interfaces 2018-03-21 14:21:50 +01:00
8870bc326c Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bytecode2 2018-03-21 13:47:19 +01:00
e1c6369bcb Bytecode für Post-/Preincrement und Post-/Predecrement 2018-03-21 13:08:39 +01:00
46255efb70 Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unify-test 2018-03-21 11:29:01 +01:00
fb77f9192f Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bigRefactoring 2018-03-21 11:28:35 +01:00
a71e56ea97 Fix 2018-03-21 11:28:21 +01:00
5dfa6769b2 Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unify-test 2018-03-21 11:16:45 +01:00
77be216ee5 Fix 2018-03-21 11:15:59 +01:00
100db9baac Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unify-test
Fehler by atElement
2018-03-21 11:13:20 +01:00
e1f579664a Fix Generics in MethodCall 2018-03-21 11:12:06 +01:00
7a9c0a1e69 LambdaRunnableTest fix 2018-03-21 11:09:29 +01:00
7e5aa852d7 Fehler fix 2018-03-21 10:35:46 +01:00
5d39863cc6 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Maximumsbildung auf maximale Elemente soweit fertig
Argument von mul funktion nicht, liefret nur Vec<TypPl>
2018-03-20 22:30:57 +01:00
01dd4e57e6 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
Letzte Version bevor MatchUnifyTask
2018-03-20 10:14:01 +01:00
6faffdf90c modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java 2018-03-19 17:43:27 +01:00
f4bc057aff modified: src/de/dhbwstuttgart/core/JavaTXCompiler.java
LogAusgabe FC

	modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
fresh TV in unifyCase1 auf alle cs ausgedehnt
	modified:   test/javFiles/Matrix.jav
2018-03-19 15:25:40 +01:00
78db0f0177 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Errorrueckgabe auskommentiert
	new file:   src/de/dhbwstuttgart/typeinference/unify/interfaces/UnifyTypeVisitor.java
eingecheckt vorher vergessen
	modified:   test/javFiles/Matrix.jav
add und mul aktiviert
2018-03-19 09:38:37 +01:00
3233ccd845 Overloading funktioniert. Erzeugt Bytecode für Postincrement (für Integers). 2018-03-18 16:08:52 +01:00
b0b1426e20 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
new file:   src/de/dhbwstuttgart/typeinference/unify/freshPlaceholder.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java
freshtypevraiable Vistor soweit fertig noch nicht getestet
2018-03-18 15:11:45 +01:00
103c7e4b14 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java
visitor freshPlaceholder implements UnifyTypeVisitor
2018-03-17 15:01:03 +01:00
3638edfa73 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   test/javFiles/Matrix.jav
Fehler entdeckt, in unifyCase1 fuer die Typen aus FC keine fresh TV getsetzt werden.
2018-03-16 14:10:40 +01:00
bd98bed5ca Merge branch 'unify-test' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unify-test
Merge
2018-03-15 20:50:59 +01:00
6299086297 modified: typeinference/unify/TypeUnifyTask.java
modified:   typeinference/unify/model/UnifyPair.java
2018-03-15 20:47:16 +01:00
de5b43d72b modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java

Links der substitierten Pare eingefuegt.
2018-03-15 17:00:26 +01:00
7e6dee8e1d modified: ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   ../javFiles/Matrix.jav
2018-03-14 17:48:04 +01:00
dafcd2f125 Bytecode für While-Schleifen 2018-03-14 15:51:38 +01:00
6a5ababa51 ANTLR Parsetreewalker für ASP Result implementieren 2018-03-14 14:32:36 +01:00
273ddb92d7 modified: ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java
	modified:   ../javFiles/Matrix.jav
2018-03-14 13:56:28 +01:00
4a2b901465 aufräumen 2018-03-13 14:53:27 +01:00
dea3da3b69 Merge branch 'bigRefactoring' into unify-test
Fehelr mit elementAt geloest
2018-03-13 10:41:57 +01:00
13c70148a8 modified: ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
	modified:   ../javFiles/Matrix.jav
mul1 und add ergaenzt.
Fehler bei elementAt: Liefert Object als Returntyp
2018-03-13 08:46:25 +01:00
bb5945898a Bug in ASTFactory beseitigen 2018-03-13 01:57:21 +01:00
123f94aea7 ANTLR Parser für ASP Statements implementieren 2018-03-13 00:24:40 +01:00
dff72b0c97 ResultSetOutputGenerator 2018-03-12 00:38:02 +01:00
1667b394f2 modified: ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
Variancen gesetzt
2018-03-11 20:39:38 +01:00
95943b1627 modified: src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
compare(Matrix, Vector<gen_ab>, ? extends Vector<? extends Integer>> <.? gen_ab
   eingefuegt.
2018-03-10 12:32:07 +01:00
0315a1f144 modified: ../../src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnify.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
compare(Matrix, Vector<gen_ab>, ? extends Vector<? extends Integer>> <.? gen_ab
funktioniert nicht
2018-03-10 01:04:19 +01:00
52a5fd7904 erzeugt Bytecode für relationale Operatoren. Getestet. 2018-03-09 21:57:39 +01:00
b5b5b5d9c9 modified: ../../src/de/dhbwstuttgart/typeinference/constraints/Pair.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java
Varinace in UnfyPair eingefuegt und Abfrage in computeCartesianRecursive eingefuegt
Pruefen, ob Varianve bei Subst und andrene erhalten bleibt.
2018-03-09 01:23:02 +01:00
83aaff140c Aufräumen 2018-03-08 01:44:40 +01:00
3deaceec01 UnifyWithoutWildcards Test läuft durch 2018-03-08 01:41:38 +01:00
9862df9e63 modified: ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java

Minimum funktion soweit
2018-03-08 01:12:17 +01:00
9f2702276f Fehler beheben 2018-03-08 00:03:26 +01:00
87cf674352 Fehler in FCGenerator beheben 2018-03-07 23:07:53 +01:00
dfd6a1f532 erge branch 'bigRefactoring' into sat 2018-03-07 23:04:16 +01:00
e8388e2748 Aufräumen 2018-03-07 22:42:05 +01:00
095f9a7956 Tests an neue ASPFactory anpassen 2018-03-07 22:41:00 +01:00
c4aec8379e Erste Version von ASPFactory implementieren 2018-03-07 21:52:46 +01:00
ccc16fd22b modified: ../../src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
modified:   ../../src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java
	modified:   ../../src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java

1. Version mit compare von UnifyPairs
2018-03-07 13:09:47 +01:00
54cf24926e Bytecode arithmetische Operatoren unterschiedlischer Typen vollständig und getestet 2018-03-07 12:26:30 +01:00
94d39ee21a Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bytecode2 2018-03-07 11:49:16 +01:00
725b071d28 Problem mit BinaryExpr gefixt 2018-03-07 08:47:43 +01:00
284af1246b Nicht lauffähig. ASPFactory neu implementieren 2018-03-07 07:41:46 +01:00
f453343f1c Bytecode für arithmetische Operatoren mit Parametern unterschiedlicher Typen. Testfälle bereinigt und aufgeräumt. 2018-03-06 19:14:27 +01:00
bb016e6417 modified: src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java
modified:   src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
2018-03-05 20:04:10 +01:00
831bf1fe17 modified: src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
weitere Fälle in die Ordnung eingebaut
2018-03-04 22:58:31 +01:00
cba489f279 modified: src/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java
eine Variable korrigiert
TODO eingefuegt
compare muss fuer ale moeglichen Faelle aus calculatePairSets erstellt werden
2018-03-03 01:07:25 +01:00
9f3439a15e x 2018-03-02 14:12:06 +01:00
356b8a7a34 modified: src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Eq for Unify vereinfachen noch nicht fertig
2018-03-01 18:00:38 +01:00
ab37e1a607 Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bigRefactoring 2018-03-01 15:03:48 +01:00
18545cff9a GenericRefType umgestalten. Unnötige Backreferenzen entfernen 2018-03-01 13:25:03 +01:00
9840281d83 Test für ASP anfügen 2018-03-01 12:31:56 +01:00
6256bdfe2e modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
In Unfy:
- Bildung des kartesischen Produkts auf secondlevel-Ebene entfernt

In computeCartesianRecursive:
- Vereinigung der Ergebnisse ueber die Schleifen und die Rekursion eingefuegt
- Minimumbestimmung korrigiert
2018-03-01 12:27:38 +01:00
6a9db81981 Merge 2018-02-28 17:16:28 +01:00
53087a8e04 result.add wieder aktiviert 2018-02-28 17:11:50 +01:00
aa631b5099 UnifyTest korrekt benennen 2018-02-28 16:35:45 +01:00
a3a02fe475 Merge branch 'bigRefactoring' into unify-Test 2018-02-28 16:34:48 +01:00
99ce7c1122 <, > Operatoren einführen 2018-02-28 16:33:18 +01:00
cef82c6359 Typgenerator auf alten Stand setzen, damit Matrix test lauft 2018-02-28 16:27:08 +01:00
67fe88215a eigenerTest 2018-02-28 16:25:45 +01:00
f31023b4fa merge2 2018-02-28 16:16:22 +01:00
a733eee8b5 merge 2018-02-28 16:12:57 +01:00
15f5a2dc76 Merge branch 'bigRefactoring' into unify-Test 2018-02-28 16:10:08 +01:00
6fcaafe477 test 2018-02-28 16:07:02 +01:00
35b99a4095 Bytecode kann für folgende Operationen +,-,*,/,% erzeugt werden 2018-02-28 15:59:21 +01:00
327f36f1c2 Faculty Test ändern. UnifyTypeFactory konvertiert automatisch FunN Typen korrekt 2018-02-28 15:21:12 +01:00
6b57aacef0 Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bytecode2 2018-02-28 14:58:58 +01:00
f023754328 TypeStmt für +,-,/,*,% einführen 2018-02-28 14:50:16 +01:00
77aaa0ecb6 Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into bigRefactoring 2018-02-28 13:32:51 +01:00
9f9a94b5cf Testfälle bereinigen 2018-02-28 13:32:36 +01:00
b66d06a165 Merge branch 'parser' into bigRefactoring 2018-02-28 11:53:53 +01:00
92b110a971 Funktionierender Clingo Test 2018-02-27 19:10:16 +01:00
2277f68509 Ordner manually/ in .gitignore hinzugefügt 2018-02-25 13:20:19 +01:00
1c0fa6a820 modified: de/dhbwstuttgart/typeinference/unify/RuleSet.java
modified:   de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java
logFile eingefuegt
2018-02-24 19:56:22 +01:00
10b5d87119 Merge branch 'bigRefactoring' into sat 2018-02-23 11:14:47 +01:00
73c37027d9 Fehler in TypeStmt UnaryExpression beheben 2018-02-23 09:16:12 +01:00
8e198679c7 Instabiler Zustand reduce funktionert nicht 2018-02-23 00:37:59 +01:00
419e4a6d0e MERGE
Merge branch 'unify-test' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unify-test
2018-02-21 17:55:47 +01:00
5cd2ee7d80 geändert: src/de/dhbwstuttgart/core/JavaTXCompiler.java
geändert:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
recursiveCartesionProduct wieder entfernt
2018-02-21 17:54:26 +01:00
9c35f04a09 modified: src/de/dhbwstuttgart/typeinference/unify/RuleSet.java 2018-02-21 17:22:23 +01:00
89246ece5c modified: src/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
	modified:   test/javFiles/Matrix.jav
2018-02-21 14:02:48 +01:00
d53faa0c86 FiniteClosure korrekt generieren 2018-02-19 11:33:08 +01:00
5270cecec9 Changes to be committed:
modified:   src/de/dhbwstuttgart/core/JavaTXCompiler.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   test/javFiles/Matrix.jav

Fehler in der Aufteilung von Unify korrigiert.
Equalcheck in Schritt 6 wiedre eingefuegt.
2018-02-14 17:45:08 +01:00
87fe51767c modified: src/de/dhbwstuttgart/typeinference/unify/RuleSet.java
Reduce 1
C und D koennen auch gleich sein.
Muss nochmals ueberprueft werden.
2018-02-09 22:55:40 +01:00
f0610aeff1 Changes to be committed:
modified:   src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   test/typeinference/JavaTXCompilerTest.java
2018-02-09 21:32:15 +01:00
e4fbd17a55 modified: src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   test/javFiles/Matrix.jav
Rekursive Berechnung des Kartesischen Produkts
2018-02-08 00:02:27 +01:00
9c526f20fb merge 2018-02-07 16:56:11 +01:00
1f269918fb nicht lauffaehig 2018-02-07 16:53:24 +01:00
2d5c863008 HEAD detached at 2f994cdf
Changes to be committed:
Aenderungen am Unify: Fehler behoben und Vereinfachung

	modified:   src/de/dhbwstuttgart/core/JavaTXCompiler.java
	new file:   src/de/dhbwstuttgart/typeinference/unify/Match.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	new file:   src/de/dhbwstuttgart/typeinference/unify/interfaces/IMatch.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/Node.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java
	modified:   src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java
	modified:   test/javFiles/Matrix.jav
2018-02-07 14:38:45 +01:00
5a3dcd7100 Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into plugin 2018-01-31 16:43:04 +01:00
1a1ab2696d Merge branch 'bigRefactoring' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into plugin 2018-01-31 16:06:21 +01:00
9186f5dff5 Alle Dependencies werden in eine Jar gepackt. Diese in Eclipseplugin umwandeln und einbinden funktioniert \o/ 2018-01-24 19:05:09 +01:00
5c9b40e0b7 Rumprobieren. Nicht lauffähig 2018-01-24 16:37:01 +01:00
bd0678f362 Lokales Repo eintragen 2018-01-21 11:17:20 +01:00
a08e2e8815 Versuche google und reflections auch noch als plugin zu verpacken. WIll nicht funktionieren 2018-01-19 17:48:25 +01:00
47689f2fc6 ZIP-FIle erstellen 2018-01-19 16:55:23 +01:00
b7aca99301 local maven repository 2018-01-19 16:36:08 +01:00
8920b32020 Unnötige import entfernen 2018-01-19 15:28:54 +01:00
da41857a4f Plugin deploy backup 2018-01-19 15:22:29 +01:00
09dcdaeb96 Local Repo anfügen 2018-01-19 15:14:39 +01:00
6d0392956d Pom anpassen 2018-01-19 14:34:41 +01:00
237 changed files with 9571 additions and 1571 deletions
.gitignoreREADME.mdpom.xml
src/de/dhbwstuttgart
.DS_Store
bytecode
core
parser
sat
syntaxtree
typedeployment
typeinference
target
test
asp
bytecode
finiteClosure
javFiles
parser
typeinference
visualisation

3
.gitignore vendored

@ -20,3 +20,6 @@ bin
.project
.settings/
/target/
#
manually/

19
README.md Normal file

@ -0,0 +1,19 @@
# plugin site erstellen
* die JAvaTXCOmpiler DAtei in ein plugin umwandeln und deployen.
* siehe: http://www.vogella.com/tutorials/EclipseJarToPlugin/article.html#convert-jar-files-to-osgi-bundles-with-the-p2-maven-plugin
* AUsführung:
* mvn deploy #erstellt die JAR-Datei und steckt sie in ein lokales Repo (maven-repository)
* mvn p2:site
* mvn package # hier wird die ZIP-Filf zum Einbinden in Eclipse erstellt
# Einbinden in Eclipse
* In Eclipse kann die Zip-FIle wie ein Plugin installiert werden
* Hier tritt FEhler auf. Reflections-Library kann nicht installiert werden. Möglicherweise wird sie auch nicht gebraucht
* Nach dem installieren de.dhbwstuttagrt.JavaTXcompiler zu den DEpendencies des plugins hinzufügen
* Anschließend unter "Overview" auf "Updata Classpath" klicken
# Windows
* JAVA_HOME setzen:
* export JAVA_HOME=/c/Program\ Files/Java/jdk1.8.0_102/

95
pom.xml

@ -7,6 +7,7 @@
<groupId>de.dhbwstuttgart</groupId>
<artifactId>JavaTXcompiler</artifactId>
<packaging>jar</packaging>
<version>0.1</version>
<name>JavaTXcompiler</name>
<url>http://maven.apache.org</url>
@ -42,12 +43,18 @@
<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>
<build>
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<finalName>${artifactId}-${version}</finalName>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src/</sourceDirectory>
<testSourceDirectory>test/</testSourceDirectory>
@ -65,14 +72,78 @@
<configuration>
<sourceDirectory>src/de/dhbwstuttgart/parser/antlr/</sourceDirectory>
<outputDirectory>src/de/dhbwstuttgart/parser/antlr/</outputDirectory>
<arguments> <argument>-package</argument> <argument>de.dhbwstuttgart.parser.antlr</argument> </arguments>
</configuration>
</execution>
<execution>
<id>aspParser</id>
<goals>
<goal>antlr4</goal>
</goals>
<configuration>
<sourceDirectory>src/de/dhbwstuttgart/sat/asp/parser/antlr/</sourceDirectory>
<outputDirectory>src/de/dhbwstuttgart/sat/asp/parser/antlr/</outputDirectory>
<arguments>
<argument>-package</argument>
<argument>de.dhbwstuttgart.parser.antlr</argument>
<argument>de.dhbwstuttgart.sat.asp.parser.antlr</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<plugin>
<groupId>org.reficio</groupId>
<artifactId>p2-maven-plugin</artifactId>
<version>1.1.2-SNAPSHOT</version>
<executions>
<execution>
<id>default-cli</id>
<configuration>
<artifacts>
<!-- specify your depencies here -->
<!-- groupId:artifactId:version -->
<artifact>
<id>de.dhbwstuttgart:JavaTXcompiler:0.1</id>
</artifact>
<artifact><id>org.reflections:reflections:0.9.11</id></artifact>
<artifact><id>com.google.guava:guava:22.0</id></artifact>
<artifact><id>javax.annotation:javax.annotation-api:1.3.1</id></artifact>
<artifact><id>org.glassfish:javax.annotation:3.1.1</id></artifact>
</artifacts>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.eclipse.tycho</groupId>
<artifactId>tycho-p2-repository-plugin</artifactId>
<version>${tycho.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>archive-repository</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
@ -83,8 +154,28 @@
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>reficio</id>
<url>http://repo.reficio.org/maven/</url>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<id>maven-repository</id>
<url>file:///${project.basedir}/target</url>
</repository>
</repositories>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<tycho.version>0.23.0</tycho.version>
</properties>
<distributionManagement>
<repository>
<id>maven-repository</id>
<name>MyCo Internal Repository</name>
<url>file:///${project.basedir}/maven-repository/</url>
</repository>
</distributionManagement>
</project>

Binary file not shown.

@ -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);
}
}

@ -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);
}
}

@ -0,0 +1,255 @@
package de.dhbwstuttgart.bytecode;
import java.util.List;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
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.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;
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
public void visit(ArgumentList argumentList) {
// TODO Auto-generated method stub
}
@Override
public void visit(LambdaExpression lambdaExpression) {
lambdaExpression.accept(bytecodeGenMethod);
// Zieltype des Lambas ist Funktionale Interface
// kann nie primitiv sein => un-/boxing wird hier nicht gebraucht
argListMethCall.remove(0);
}
@Override
public void visit(Assign assign) {
assign.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(assign.getType()));
argListMethCall.remove(0);
}
@Override
public void visit(BinaryExpr binary) {
binary.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(binary.getType()));
argListMethCall.remove(0);
}
@Override
public void visit(Block block) {
// TODO Auto-generated method stub
}
@Override
public void visit(CastExpr castExpr) {
castExpr.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(castExpr.getType()));
argListMethCall.remove(0);
}
@Override
public void visit(EmptyStmt emptyStmt) {
// TODO Auto-generated method stub
}
@Override
public void visit(FieldVar fieldVar) {
fieldVar.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(fieldVar.getType()));
argListMethCall.remove(0);
}
@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) {
instanceOf.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(instanceOf.getType()));
argListMethCall.remove(0);
}
@Override
public void visit(LocalVar localVar) {
localVar.accept(bytecodeGenMethod);
if(!bytecodeGenMethod.isBinaryExp) {
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(localVar.getType()));
}
argListMethCall.remove(0);
}
@Override
public void visit(LocalVarDecl localVarDecl) {
// TODO Auto-generated method stub
}
@Override
public void visit(MethodCall methodCall) {
methodCall.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(methodCall.getType()));
argListMethCall.remove(0);
}
@Override
public void visit(NewClass methodCall) {
methodCall.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(methodCall.getType()));
argListMethCall.remove(0);
}
@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) {
aThis.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(aThis.getType()));
argListMethCall.remove(0);
}
@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(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
}
@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.getResolvedType(unaryExpr.getType()));
argListMethCall.remove(0);
}
@Override
public void visit(Literal literal) {
literal.accept(bytecodeGenMethod);
if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(literal.getType()));
argListMethCall.remove(0);
}
}

@ -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);
}
}

@ -1,7 +1,9 @@
package de.dhbwstuttgart.bytecode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.statement.*;
@ -9,11 +11,16 @@ 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.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.utilities.MethodAndTPH;
import de.dhbwstuttgart.bytecode.utilities.NormalConstructor;
import de.dhbwstuttgart.bytecode.utilities.NormalMethod;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.statement.Literal;
@ -23,6 +30,9 @@ 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.GenericInsertPair;
import de.dhbwstuttgart.typeinference.result.ResolvedType;
import de.dhbwstuttgart.typeinference.result.ResultPair;
import de.dhbwstuttgart.typeinference.result.ResultSet;
public class BytecodeGen implements ASTVisitor {
@ -30,12 +40,18 @@ public class BytecodeGen implements ASTVisitor {
ClassWriter cw =new ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS);
String type;
String className;
private boolean isInterface;
private List<ResultSet> listOfResultSets;
private ResultSet resultSet;
private SourceFile sf;
private String path;
private int indexOfFirstParam = 0;
private String superClass;
// 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
@ -43,20 +59,27 @@ public class BytecodeGen implements ASTVisitor {
// stores generics and their bounds of method
HashMap<String, String> genericsAndBoundsMethod = new HashMap<>();
private final TPHExtractor tphExtractor = new TPHExtractor();
private final ArrayList<GenericInsertPair> commonPairs = new ArrayList<>();
HashMap<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes = new HashMap<>();
byte[] bytecode;
HashMap<String,byte[]> classFiles;
public BytecodeGen(HashMap<String,byte[]> classFiles, ResultSet resultSet) {
ArrayList<String> methodNameAndParamsT = new ArrayList<>();
public BytecodeGen(HashMap<String,byte[]> classFiles, List<ResultSet> listOfResultSets,SourceFile sf ,String path) {
this.classFiles = classFiles;
this.resultSet = resultSet;
this.listOfResultSets = listOfResultSets;
this.sf = sf;
this.path = path;
}
@Override
public void visit(SourceFile sourceFile) {
for(ClassOrInterface cl : sourceFile.getClasses()) {
System.out.println("in Class: " + cl.getClassName().toString());
BytecodeGen classGen = new BytecodeGen(classFiles, resultSet);
BytecodeGen classGen = new BytecodeGen(classFiles, listOfResultSets, sf, path);
cl.accept(classGen);
classGen.writeClass(cl.getClassName().toString());
}
@ -81,6 +104,7 @@ public class BytecodeGen implements ASTVisitor {
@Override
public void visit(ClassOrInterface classOrInterface) {
className = classOrInterface.getClassName().toString();
cw.visitSource(className +".jav", null);
@ -88,30 +112,64 @@ public class BytecodeGen implements ASTVisitor {
isInterface = (classOrInterface.getModifiers()&512)==512;
int acc = isInterface?classOrInterface.getModifiers()+Opcodes.ACC_ABSTRACT:classOrInterface.getModifiers()+Opcodes.ACC_SUPER;
String sig = null;
/* if class has generics then creates signature
* Signature looks like:
* <E:Ljava/...>Superclass
*/
if(classOrInterface.getGenerics().iterator().hasNext()) {
Signature signature = new Signature(classOrInterface, genericsAndBounds);
sig = signature.toString();
}
// needs implemented Interfaces?
cw.visit(Opcodes.V1_8, acc, classOrInterface.getClassName().toString()
, sig, classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor()), null);
// for each field in the class
for(Field f : classOrInterface.getFieldDecl()) {
f.accept(this);
// resultSet = listOfResultSets.get(0);
boolean isConsWithNoParamsVisited = false;
boolean isVisited = false;
for(ResultSet rs : listOfResultSets) {
superClass = classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor());
resultSet = rs;
// Nur einmal ausführen!!
if(!isVisited) {
classOrInterface.accept(tphExtractor);
getCommonTPHS(tphExtractor);
String sig = null;
/* if class has generics then creates signature
* Signature looks like:
* <E:Ljava/...>Superclass
*/
if(classOrInterface.getGenerics().iterator().hasNext() || !commonPairs.isEmpty() ||
classOrInterface.getSuperClass().acceptTV(new TypeToSignature()).contains("<")) {
Signature signature = new Signature(classOrInterface, genericsAndBounds,commonPairs);
sig = signature.toString();
System.out.println("Signature: => " + sig);
}
cw.visit(Opcodes.V1_8, acc, classOrInterface.getClassName().toString()
, sig, classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor()), null);
isVisited = true;
}
for(Field f : classOrInterface.getFieldDecl()) {
f.accept(this);
}
for(Constructor c : classOrInterface.getConstructors()) {
if(!isConsWithNoParamsVisited)
c.accept(this);
if(!c.getParameterList().iterator().hasNext())
isConsWithNoParamsVisited = true;
}
for(Method m : classOrInterface.getMethods()) {
m.accept(this);
}
}
for(Constructor c : classOrInterface.getConstructors()) {
c.accept(this);
}
for(Method m : classOrInterface.getMethods()) {
m.accept(this);
}
private void getCommonTPHS(TPHExtractor tphExtractor) {
// Gemeinsame TPHs
ArrayList<TypePlaceholder> cTPHs = new ArrayList<>();
// Alle TPHs der Felder speichern
for(TypePlaceholder tph : tphExtractor.allTPHS.keySet()) {
if(!tphExtractor.allTPHS.get(tph))
cTPHs.add(tph);
}
}
@ -123,46 +181,67 @@ public class BytecodeGen implements ASTVisitor {
boolean hasGen = false;
for(String paramName : methodParamsAndTypes.keySet()) {
String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToDescriptor());
if(genericsAndBounds.containsKey(typeOfParam)) {
String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToSignature());
if(genericsAndBounds.containsKey(typeOfParam) ||typeOfParam.substring(0, 4).equals("TPH ")
|| typeOfParam.contains("<")) {
hasGen = true;
break;
}
}
String sig = null;
if(hasGen) {
Signature signature = new Signature(field, genericsAndBounds,methodParamsAndTypes);
ArrayList<GenericInsertPair> pairs = simplifyPairs(field.name,tphExtractor.allPairs);
Signature signature = new Signature(field, genericsAndBounds,methodParamsAndTypes,resultSet,pairs);
sig = signature.toString();
}
NormalConstructor constructor = new NormalConstructor(field,genericsAndBounds,hasGen);
desc = constructor.accept(new DescriptorToString(resultSet));
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", desc, sig, null);
mv.visitCode();
BytecodeGenMethod gen = new BytecodeGenMethod(className,resultSet,field, mv,paramsAndLocals,cw,
genericsAndBoundsMethod,genericsAndBounds,isInterface,classFiles);
BytecodeGenMethod gen = new BytecodeGenMethod(className,superClass,resultSet,field, mv,paramsAndLocals,cw,
genericsAndBoundsMethod,genericsAndBounds,isInterface,classFiles, sf,path);
if(!field.getParameterList().iterator().hasNext()) {
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 methParamTypes = retType+method.name+"%%";
method.getParameterList().accept(this);
Iterator<FormalParameter> itr = method.getParameterList().iterator();
while(itr.hasNext()) {
FormalParameter fp = itr.next();
methParamTypes += resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+";";
}
if(methodNameAndParamsT.contains(methParamTypes)) {
return;
}
methodNameAndParamsT.add(methParamTypes);
System.out.println("Method: "+method.name +" , paramsType: "+methParamTypes);
String methDesc = null;
// Method getModifiers() ?
int acc = isInterface?Opcodes.ACC_ABSTRACT:method.modifier;
System.out.println(acc);
boolean hasGenInParameterList = genericsAndBounds.containsKey(resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor()));
/*Prüfe, ob die Rückgabe-Type der Methode eine Type-Variable ist*/
boolean hasGenInParameterList = genericsAndBounds.containsKey(retType) || retType.subSequence(0, 4).equals("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());
if(genericsAndBounds.containsKey(typeOfParam)) {
String sigOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToSignature());
if(genericsAndBounds.containsKey(typeOfParam)||typeOfParam.substring(0, 4).equals("TPH ")||sigOfParam.contains("<")) {
hasGenInParameterList = true;
break;
}
@ -170,31 +249,126 @@ public class BytecodeGen implements ASTVisitor {
}
//TODO: Test if the return-type or any of the parameter is a parameterized type. (VP)
//than create the descriptor with the new syntax.
//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 */
if(hasGen||method.getReturnType().acceptTV(new TypeToString()).equals("TPH")) {
// resultset hier zum testen
Signature signature = new Signature(method, genericsAndBoundsMethod, methodParamsAndTypes,resultSet);
// zwite operand muss weggelassen werden
if(hasGen||resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToString()).equals("TPH")) {
ArrayList<GenericInsertPair> pairs = simplifyPairs(method.name,tphExtractor.allPairs);
System.out.println(method.name + " => Simplified Pairs: ");
pairs.forEach(p->System.out.println(p.TA1.getName() + " -> "+p.TA2.getName()));
Signature signature = new Signature(method, genericsAndBoundsMethod, genericsAndBounds,methodParamsAndTypes,resultSet, pairs);
sig = signature.toString();
}
System.out.println(sig);
System.out.println(method.getName()+" ==> "+sig);
NormalMethod meth = new NormalMethod(method,genericsAndBounds,genericsAndBoundsMethod,hasGen);
methDesc = meth.accept(new DescriptorToString(resultSet));
System.out.println(methDesc);
// System.out.println(methDesc);
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);
BytecodeGenMethod gen = new BytecodeGenMethod(className,resultSet,method, mv,paramsAndLocals,cw,
genericsAndBounds,genericsAndBounds,isInterface,classFiles);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
private ArrayList<GenericInsertPair> simplifyPairs(String methodName, ArrayList<GenericInsertPair> allPairs) {
allPairs.forEach(p->System.out.print(p.TA1 + " < "+ p.TA2+ " ; "));
if(allPairs.size() < 2)
return allPairs;
ArrayList<GenericInsertPair> simplifiedPairs = new ArrayList<>();
MethodAndTPH method;
ArrayList<TypePlaceholder> methodTphs = new ArrayList<>();
ArrayList<GenericInsertPair> methodPairs = new ArrayList<>();
for(MethodAndTPH m : tphExtractor.ListOfMethodsAndTph) {
if(m.getName().equals(methodName)) {
methodTphs = m.getTphs();
methodPairs = m.getPairs();
break;
}
}
HashMap<TypePlaceholder, TypePlaceholder> subAndSuperTph = new HashMap<>();
for(GenericInsertPair p : allPairs) {
// Tph2.jav
if(subAndSuperTph.containsKey(p.TA1)) {
if(methodTphs.contains(subAndSuperTph.get(p.TA1)))
continue;
}
subAndSuperTph.put(p.TA1, p.TA2);
}
int numOfVisitedPairs = 0;
for(TypePlaceholder subTph: subAndSuperTph.keySet()) {
if(numOfVisitedPairs>=subAndSuperTph.size())
break;
if(!methodTphs.contains(subTph))
continue;
HashMap<Integer, TypePlaceholder> tphsInRel= new HashMap<>();
tphsInRel.put(tphsInRel.size(), subTph);
TypePlaceholder superTph = subAndSuperTph.get(subTph);
tphsInRel.put(tphsInRel.size(), superTph);
numOfVisitedPairs++;
while(subAndSuperTph.containsKey(superTph)) {
superTph = subAndSuperTph.get(superTph);
tphsInRel.put(tphsInRel.size(), superTph);
numOfVisitedPairs++;
}
// Subtype
TypePlaceholder subTphRes = tphsInRel.get(0);
// Die größte Supertype
TypePlaceholder superTphRes = tphsInRel.get(tphsInRel.size()-1);
while(subAndSuperTph.containsValue(subTphRes)) {
for(TypePlaceholder tph : subAndSuperTph.keySet()) {
if(methodTphs.contains(tph) && subAndSuperTph.get(tph).equals(subTphRes)) {
subTphRes = tph;
break;
}
}
if(subTphRes.equals(tphsInRel.get(0))) {
break;
}
tphsInRel.put(0, subTphRes);
numOfVisitedPairs++;
}
subTphRes = tphsInRel.get(0);
int i = 2;
while(!methodTphs.contains(superTphRes) && (tphsInRel.size()-i) >0) {
superTphRes = tphsInRel.get(tphsInRel.size()-i);
i++;
}
// teste noch den Fall X < Y und Y nicht in TPHS der Methode
// Dann hat man nach der While-Schleife X < Y
// Y muss durch Object ersetzt.
// Zweite Operand für die Fälle wie in Lambda.jav (Paramtrisierte Typen)
if(methodTphs.contains(superTphRes) || !tphExtractor.allTPHS.containsKey(superTphRes)) {
GenericInsertPair sPair = new GenericInsertPair(subTphRes, superTphRes);
simplifiedPairs.add(sPair);
}
}
return simplifiedPairs;
}
@Override
public void visit(ParameterList formalParameters) {
paramsAndLocals = new HashMap<>();
@ -436,5 +610,50 @@ public class BytecodeGen implements ASTVisitor {
public void visit(UnaryExpr unaryExpr) {
throw new NotImplementedException();
}
private class TPHExtractor extends AbstractASTWalker{
// Alle TPHs der Felder werden iKopf der Klasse definiert
// alle TPHs der Klasse: (TPH, is in Method?)
final HashMap<TypePlaceholder,Boolean> allTPHS = new HashMap<>();
MethodAndTPH methodAndTph;
Boolean inMethod = false;
final ArrayList<MethodAndTPH> ListOfMethodsAndTph = new ArrayList<>();
final ArrayList<GenericInsertPair> allPairs = new ArrayList<>();
@Override
public void visit(TypePlaceholder tph) {
if(resultSet.resolveType(tph).resolvedType instanceof TypePlaceholder) {
TypePlaceholder resolvedTPH = (TypePlaceholder) resultSet.resolveType(tph).resolvedType;
if(inMethod)
methodAndTph.getTphs().add(resolvedTPH);
allTPHS.put(resolvedTPH,inMethod);
resultSet.resolveType(tph).additionalGenerics.forEach(ag ->{
if(ag.contains(resolvedTPH)&&ag.TA1.equals(resolvedTPH)&&!contains(allPairs,ag)) {
if(inMethod)
methodAndTph.getPairs().add(ag);
allPairs.add(ag);
}
});
}
}
private boolean contains(ArrayList<GenericInsertPair> pairs, GenericInsertPair genPair) {
for(int i=0; i<pairs.size();++i) {
GenericInsertPair p = pairs.get(i);
if(p.TA1.equals(genPair.TA1) && p.TA2.equals(genPair.TA2))
return true;
}
return false;
}
@Override
public void visit(Method method) {
inMethod = true;
methodAndTph = new MethodAndTPH(method.name);
super.visit(method);
inMethod = false;
ListOfMethodsAndTph.add(methodAndTph);
}
}
}

File diff suppressed because it is too large Load Diff

@ -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);
}

@ -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);
}
}

@ -0,0 +1,14 @@
package de.dhbwstuttgart.bytecode;
import org.objectweb.asm.MethodVisitor;
import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
public class ReturnStmt extends AStatement {
public ReturnStmt(Expression retexpr) {
super(retexpr);
}
}

@ -2,12 +2,14 @@ package de.dhbwstuttgart.bytecode.descriptor;
import java.util.Iterator;
import de.dhbwstuttgart.bytecode.Lambda;
import de.dhbwstuttgart.bytecode.MethodFromMethodCall;
import de.dhbwstuttgart.bytecode.NormalConstructor;
import de.dhbwstuttgart.bytecode.NormalMethod;
import de.dhbwstuttgart.bytecode.SamMethod;
import org.objectweb.asm.Type;
import de.dhbwstuttgart.bytecode.signature.TypeToSignature;
import de.dhbwstuttgart.bytecode.utilities.Lambda;
import de.dhbwstuttgart.bytecode.utilities.MethodFromMethodCall;
import de.dhbwstuttgart.bytecode.utilities.NormalConstructor;
import de.dhbwstuttgart.bytecode.utilities.NormalMethod;
import de.dhbwstuttgart.bytecode.utilities.SamMethod;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
import de.dhbwstuttgart.syntaxtree.type.RefType;
@ -46,12 +48,20 @@ public class DescriptorToString implements DescriptorVisitor{
}else if(method.getGenericsAndBounds().containsKey(fpDesc)){
desc += "L"+method.getGenericsAndBounds().get(fpDesc)+ ";";
}else {
desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
// desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
String resType = resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor());
if(resType.subSequence(0, 4).equals("TPH ")) {
// Bound ist immer Object
desc += "L"+Type.getInternalName(Object.class)+ ";";
} else {
desc += "L"+resType+ ";";
}
}
}
// else if(((RefType) fp.getType()).getParaList().size() > 0){
// desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.toString().replace(".", "%").replace("<", "%%").replace(">", "%%")+ ";";
// }
//TODO: generate a class java%% ... %%
else if(resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()).contains("<")){
desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.toString().replace(".", "$$").replace("<", "$$$").replace(">", "$$$")+ ";";
}
else {
desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
}
@ -67,7 +77,13 @@ public class DescriptorToString implements DescriptorVisitor{
}else if(method.getGenericsAndBounds().containsKey(ret)){
desc += ")L"+method.getGenericsAndBounds().get(ret)+ ";";
}else {
desc += ")" + "L"+resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
String resType = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor());
if(resType.subSequence(0, 4).equals("TPH ")) {
// desc += ")" + "L"+method.getGenericsAndBoundsMethod().get(resType.substring(4)+"$")+ ";";
desc += ")" + "L"+Type.getInternalName(Object.class)+ ";";
} else {
desc += ")" + "L"+resType+ ";";
}
}
}else {
desc += ")" + "L"+resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
@ -107,9 +123,21 @@ public class DescriptorToString implements DescriptorVisitor{
Iterator<FormalParameter> itr = lambdaExpression.getParams().iterator();
while(itr.hasNext()) {
FormalParameter fp = itr.next();
desc = desc + "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()) + ";";
String d = resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor());
if(d.substring(0, 4).equals("TPH ") ||d.contains("<")) {
desc += "L"+Type.getInternalName(Object.class)+ ";";
}else {
desc = desc + "L"+ d + ";";
}
}
String retType = resultSet.resolveType(lambdaExpression.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor());
if(retType.substring(0, 4).equals("TPH ")|| retType.contains("<")){
desc += ")L"+Type.getInternalName(Object.class)+ ";";
}else {
desc = desc + ")"+"L"+retType+";";
}
desc = addReturnType(desc, lambdaExpression.getReturnType(), resultSet);
return desc;
}
@ -119,9 +147,22 @@ public class DescriptorToString implements DescriptorVisitor{
Iterator<RefTypeOrTPHOrWildcardOrGeneric> itr = samMethod.getArgumentList().iterator();
while(itr.hasNext()) {
RefTypeOrTPHOrWildcardOrGeneric rt = itr.next();
desc = desc + "L"+resultSet.resolveType(rt).resolvedType.acceptTV(new TypeToDescriptor())+";";
String d = resultSet.resolveType(rt).resolvedType.acceptTV(new TypeToDescriptor());
if(d.substring(0, 4).equals("TPH ") ||d.contains("<")) {
desc += "L"+Type.getInternalName(Object.class)+ ";";
}else {
desc += "L"+ d + ";";
}
}
String retType = resultSet.resolveType(samMethod.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor());
if(retType.substring(0, 4).equals("TPH ")|| retType.contains("<")){
desc += ")L"+Type.getInternalName(Object.class)+ ";";
}else {
desc = desc + ")"+"L"+retType+";";
}
desc = desc + ")"+"L"+resultSet.resolveType(samMethod.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor())+";";
return desc;
}
@ -129,26 +170,34 @@ public class DescriptorToString implements DescriptorVisitor{
public String visit(MethodFromMethodCall methodFromMethodCall) {
String desc = "(";
for(Expression e : methodFromMethodCall.getArgList().getArguments()) {
String d = e.getType().acceptTV(new TypeToDescriptor());
if(methodFromMethodCall.getGenericsAndBoundsMethod().containsKey(d)) {
desc += "L"+methodFromMethodCall.getGenericsAndBoundsMethod().get(d)+ ";";
}else if(methodFromMethodCall.getGenericsAndBounds().containsKey(d)) {
desc += "L"+methodFromMethodCall.getGenericsAndBounds().get(d)+ ";";
String d = resultSet.resolveType(e.getType()).resolvedType.acceptTV(new TypeToDescriptor());
if(d.substring(0, 4).equals("TPH ") ||d.contains("<") || methodFromMethodCall.getReceiverName().contains("$$")) {
desc += "L"+Type.getInternalName(Object.class)+ ";";
}else {
desc += "L"+resultSet.resolveType(e.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
if(methodFromMethodCall.getGenericsAndBoundsMethod().containsKey(d)) {
desc += "L"+methodFromMethodCall.getGenericsAndBoundsMethod().get(d)+ ";";
}else if(methodFromMethodCall.getGenericsAndBounds().containsKey(d)) {
desc += "L"+methodFromMethodCall.getGenericsAndBounds().get(d)+ ";";
}else {
desc += "L"+resultSet.resolveType(e.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
}
}
}
if(resultSet.resolveType(methodFromMethodCall.getReturnType()).resolvedType.toString().equals("void")) {
String retType = resultSet.resolveType(methodFromMethodCall.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor());
System.out.println("DescriptorToString retType = " + retType);
if(retType.equals("void")) {
desc += ")V";
}else if(retType.substring(0, 4).equals("TPH ")|| retType.contains("<") || methodFromMethodCall.getReceiverName().contains("$$")){
desc += ")L"+Type.getInternalName(Object.class)+ ";";
}else {
String ret = resultSet.resolveType(methodFromMethodCall.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor());
if(methodFromMethodCall.getGenericsAndBoundsMethod().containsKey(ret)) {
desc += ")L"+methodFromMethodCall.getGenericsAndBoundsMethod().get(ret)+ ";";
}else if(methodFromMethodCall.getGenericsAndBounds().containsKey(ret)){
desc += ")L"+methodFromMethodCall.getGenericsAndBounds().get(ret)+ ";";
if(methodFromMethodCall.getGenericsAndBoundsMethod().containsKey(retType)) {
desc += ")L"+methodFromMethodCall.getGenericsAndBoundsMethod().get(retType)+ ";";
}else if(methodFromMethodCall.getGenericsAndBounds().containsKey(retType)){
desc += ")L"+methodFromMethodCall.getGenericsAndBounds().get(retType)+ ";";
}else {
desc += ")" + "L"+resultSet.resolveType(methodFromMethodCall.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
desc += ")" + "L"+retType+ ";";
}
}
// desc = addReturnType(desc, methodFromMethodCall.getReturnType(), resultSet);

@ -1,10 +1,10 @@
package de.dhbwstuttgart.bytecode.descriptor;
import de.dhbwstuttgart.bytecode.Lambda;
import de.dhbwstuttgart.bytecode.MethodFromMethodCall;
import de.dhbwstuttgart.bytecode.NormalConstructor;
import de.dhbwstuttgart.bytecode.NormalMethod;
import de.dhbwstuttgart.bytecode.SamMethod;
import de.dhbwstuttgart.bytecode.utilities.Lambda;
import de.dhbwstuttgart.bytecode.utilities.MethodFromMethodCall;
import de.dhbwstuttgart.bytecode.utilities.NormalConstructor;
import de.dhbwstuttgart.bytecode.utilities.NormalMethod;
import de.dhbwstuttgart.bytecode.utilities.SamMethod;
public interface DescriptorVisitor {
public String visit(NormalMethod method);

@ -13,11 +13,15 @@ public class TypeToDescriptor implements TypeVisitor<String>{
@Override
public String visit(RefType refType) {
return refType.getName().toString().replace(".", "/");
// String t = refType.getName().toString().replace(".", "/");
// return t.equals("Fun1")?(t+"$$"):t;
}
@Override
public String visit(SuperWildcardType superWildcardType) {
throw new NotImplementedException();
System.out.println("\nWILDCARD ="+superWildcardType.getInnerType().toString().replace(".", "/"));
return superWildcardType.getInnerType().toString().replace(".", "/");
//throw new NotImplementedException();
}
@Override
@ -27,7 +31,9 @@ public class TypeToDescriptor implements TypeVisitor<String>{
@Override
public String visit(ExtendsWildcardType extendsWildcardType) {
throw new NotImplementedException();
System.out.println("\nWILDCARD extends ="+extendsWildcardType.getInnerType().toString().replace(".", "/"));
return extendsWildcardType.getInnerType().toString().replace(".", "/");
//throw new NotImplementedException();
}
@Override

@ -1,5 +1,6 @@
package de.dhbwstuttgart.bytecode.signature;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
@ -8,15 +9,19 @@ import org.objectweb.asm.signature.SignatureVisitor;
import org.objectweb.asm.signature.SignatureWriter;
import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor;
import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
import de.dhbwstuttgart.syntaxtree.AbstractASTWalker;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Constructor;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression;
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.result.GenericInsertPair;
import de.dhbwstuttgart.typeinference.result.ResolvedType;
import de.dhbwstuttgart.typeinference.result.ResultSet;
public class Signature {
@ -28,28 +33,36 @@ public class Signature {
private Method method;
private HashMap<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes;
private ResultSet resultSet;
private ArrayList<GenericInsertPair> commonPairs;
private ArrayList<GenericInsertPair> methodPairs;
public Signature(ClassOrInterface classOrInterface, HashMap<String, String> genericsAndBounds) {
public Signature(ClassOrInterface classOrInterface, HashMap<String, String> genericsAndBounds,ArrayList<GenericInsertPair> commonPairs) {
this.classOrInterface = classOrInterface;
this.genericsAndBounds = genericsAndBounds;
this.commonPairs = commonPairs;
sw = new SignatureWriter();
createSignatureForClassOrInterface();
}
public Signature(Constructor constructor, HashMap<String, String> genericsAndBounds, HashMap<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes) {
public Signature(Constructor constructor, HashMap<String, String> genericsAndBounds,
HashMap<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes,ResultSet resultSet,ArrayList<GenericInsertPair> methodPairs) {
this.constructor = constructor;
this.genericsAndBounds = genericsAndBounds;
this.methodParamsAndTypes = methodParamsAndTypes;
this.resultSet = resultSet;
this.methodPairs = methodPairs;
sw = new SignatureWriter();
createSignatureForConsOrMethod(this.constructor,true);
}
public Signature(Method method, HashMap<String, String> genericsAndBoundsMethod,
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes, ResultSet resultSet) {
public Signature(Method method, HashMap<String, String> genericsAndBoundsMethod,HashMap<String, String> genericsAndBounds,
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes, ResultSet resultSet, ArrayList<GenericInsertPair> methodPairs) {
this.method = method;
this.genericsAndBoundsMethod = genericsAndBoundsMethod;
this.genericsAndBounds = genericsAndBounds;
this.methodParamsAndTypes = methodParamsAndTypes;
this.resultSet = resultSet;
this.methodPairs = methodPairs;
sw = new SignatureWriter();
createSignatureForConsOrMethod(this.method,false);
}
@ -61,10 +74,7 @@ public class Signature {
private void createSignatureForFunN(LambdaExpression lambdaExpression, int numberOfParams) {
sw.visitFormalTypeParameter("R");
// getBounds vom Return-Type
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd();
// sw.visitClassBound().visitEnd();
for(int i = 0;i<numberOfParams;i++) {
int j = i+1;
sw.visitFormalTypeParameter("T"+ j);
@ -72,6 +82,11 @@ public class Signature {
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd();
}
sw.visitFormalTypeParameter("R");
// getBounds vom Return-Type
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd();
// TODO: prüfe ob Return-Type = void,
sw.visitSuperclass().visitClassType(Type.getInternalName(Object.class));;
sw.visitEnd();
@ -92,13 +107,112 @@ public class Signature {
GenericTypeVar g = itr.next();
getBoundsOfTypeVar(g,genericsAndBoundsMethod);
}
// visits each method-parameter to create the signature
// Wenn die RückgabeType eine TPH ist, wird als generic behandelt
// z.B: Type = TPH K => wird eine Formal Type Parameter K$ erzeugt und Bound = Object
if(!isConstructor) {
String ret = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature());
System.out.println("RET:::: " + ret);
if(!ret.equals("V")) {
// TODO TypeToSignature nochmal kontrollieren und schauen ob man dort wirklich
// T... braucht und L ...
if(ret.contains("$") && !ret.contains("$$")) {
// String g = ret.substring(4,ret.length())+"$";
if(genericsAndBounds.containsKey(ret)) {
genericsAndBoundsMethod.put(ret.substring(1), genericsAndBounds.get(ret.substring(1)));
}else {
sw.visitFormalTypeParameter(ret.substring(1));
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
genericsAndBoundsMethod.put(ret.substring(1), Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd();
}
}
if(ret.contains("<")) {
RefType ref = (RefType) resultSet.resolveType(method.getReturnType()).resolvedType;
if(hasTPHs(ref)) {
createSignatureForParameterizedType(ref);
}
}
}
}
// Parameters
for(String paramName : methodParamsAndTypes.keySet()) {
RefTypeOrTPHOrWildcardOrGeneric t = methodParamsAndTypes.get(paramName);
String pT = t.acceptTV(new TypeToSignature());
// S.o
// if(pT.substring(0,4).equals("TPH ")) {
if(t instanceof TypePlaceholder) {
// String gP = pT.substring(4,pT.length())+"$";
String gP = t.acceptTV(new TypeToSignature());
if(!genericsAndBounds.containsKey(gP.substring(1)) && !genericsAndBoundsMethod.containsKey(gP.substring(1))) {
sw.visitFormalTypeParameter(gP.substring(1));
String bound = Type.getInternalName(Object.class);
boolean isTypeVar = false;
for(GenericInsertPair pair : methodPairs) {
if(pT.substring(1,pT.length()-1).equals(pair.TA1.getName())) {
bound = pair.TA2.getName()+"$";
isTypeVar = true;
break;
}
}
if(isTypeVar) {
sw.visitClassBound().visitTypeVariable(bound);
}else {
sw.visitClassBound().visitClassType(bound);
sw.visitClassBound().visitEnd();
}
genericsAndBoundsMethod.put(gP.substring(1), bound);
}
}
if(pT.contains("<")) {
RefType ref = (RefType) methodParamsAndTypes.get(paramName);
if(hasTPHs(ref))
createSignatureForParameterizedType(ref);
}
for(GenericInsertPair p:methodPairs) {
String name = p.TA1.getName()+"$";
if(!genericsAndBoundsMethod.containsKey(name)) {
sw.visitFormalTypeParameter(name);
sw.visitClassBound().visitTypeVariable(p.TA2.getName()+"$");
genericsAndBoundsMethod.put(name, p.TA2.getName()+"$");
}
}
ArrayList<TypePlaceholder> types = new ArrayList<>();
ArrayList<TypePlaceholder> superTypes = new ArrayList<>();
for(GenericInsertPair p : methodPairs) {
types.add(p.TA1);
superTypes.add(p.TA2);
}
for(GenericInsertPair p : methodPairs) {
String name = p.TA2.getName()+"$";
if(!types.contains(p.TA2) && !genericsAndBoundsMethod.containsKey(name)) {
String bound = Type.getInternalName(Object.class);
sw.visitFormalTypeParameter(name);
sw.visitClassBound().visitClassType(bound);
genericsAndBoundsMethod.put(name, bound);
sw.visitClassBound().visitEnd();
}
}
}
// visit each method-parameter to create the signature
for(String paramName : methodParamsAndTypes.keySet()) {
RefTypeOrTPHOrWildcardOrGeneric t = methodParamsAndTypes.get(paramName);
// parameter type deswegen ist true
doVisitParamsOrReturn(t,true);
}
if(isConstructor) {
if(isConstructor ||
resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature()).equals("V")) {
sw.visitReturnType().visitBaseType('V');
}else {
RefTypeOrTPHOrWildcardOrGeneric returnType = method.getReturnType();
@ -107,6 +221,146 @@ public class Signature {
}
// sw.visitEnd();
}
private void createSignatureForParameterizedType(RefType ref) {
ArrayList<GenericInsertPair> allPairs = getAllPairs(ref);
allPairs.addAll(methodPairs);
ArrayList<GenericInsertPair> simplifiedPairs = simplifyPairs(allPairs);
HashMap<String, String> names = new HashMap<>();
for(GenericInsertPair pair : simplifiedPairs) {
if(ref.getParaList().contains(pair.TA1)) {
String sub = pair.TA1.getName()+"$";
String superT = pair.TA2.getName()+"$";
names.put(sub, superT);
}
}
for(String sub : names.keySet()) {
if(!genericsAndBoundsMethod.containsKey(sub) && !genericsAndBounds.containsKey(sub)) {
sw.visitFormalTypeParameter(sub);
String bound = names.get(sub);
sw.visitClassBound().visitTypeVariable(bound);
genericsAndBoundsMethod.put(sub, bound);
}
}
for(String superT : names.values()) {
if(!names.containsKey(superT)) {
if(!genericsAndBoundsMethod.containsKey(superT) && !genericsAndBounds.containsKey(superT)) {
sw.visitFormalTypeParameter(superT);
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd();
genericsAndBoundsMethod.put(superT, Type.getInternalName(Object.class));
}
}
}
for(RefTypeOrTPHOrWildcardOrGeneric p: ref.getParaList()) {
if(p instanceof TypePlaceholder) {
String name = ((TypePlaceholder) p).getName() + "$";
if(!genericsAndBoundsMethod.containsKey(name) && !genericsAndBounds.containsKey(name)) {
sw.visitFormalTypeParameter(name);
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd();
genericsAndBoundsMethod.put(name, Type.getInternalName(Object.class));
}
}
}
}
private ArrayList<GenericInsertPair> getAllPairs(RefType ref) {
final ArrayList<GenericInsertPair> res = new ArrayList<>();
for(RefTypeOrTPHOrWildcardOrGeneric p : ref.getParaList()) {
RefTypeOrTPHOrWildcardOrGeneric resolved = resultSet.resolveType(p).resolvedType;
if(resolved instanceof TypePlaceholder) {
resultSet.resolveType(p).additionalGenerics.forEach(ag ->{
if(!contains(res,ag)) {
res.add(ag);
}
});
}
}
return res;
}
private boolean contains(ArrayList<GenericInsertPair> pairs, GenericInsertPair genPair) {
for(int i=0; i<pairs.size();++i) {
GenericInsertPair p = pairs.get(i);
if(p.TA1.equals(genPair.TA1) && p.TA2.equals(genPair.TA2))
return true;
}
return false;
}
private ArrayList<GenericInsertPair> simplifyPairs(ArrayList<GenericInsertPair> allPairs) {
ArrayList<GenericInsertPair> simplifiedPairs = new ArrayList<>();
HashMap<TypePlaceholder, TypePlaceholder> subAndSuperTph = new HashMap<>();
for(GenericInsertPair p : allPairs) {
subAndSuperTph.put(p.TA1, p.TA2);
}
subAndSuperTph.forEach((k,v)->System.out.println(k.getName() + " || " + v.getName()));
int numOfVisitedPairs = 0;
for(TypePlaceholder subTph: subAndSuperTph.keySet()) {
if(numOfVisitedPairs>=subAndSuperTph.size())
break;
HashMap<Integer, TypePlaceholder> tphsInRel= new HashMap<>();
tphsInRel.put(tphsInRel.size(), subTph);
TypePlaceholder superTph = subAndSuperTph.get(subTph);
tphsInRel.put(tphsInRel.size(), superTph);
numOfVisitedPairs++;
while(subAndSuperTph.containsKey(superTph)) {
superTph = subAndSuperTph.get(superTph);
tphsInRel.put(tphsInRel.size(), superTph);
numOfVisitedPairs++;
}
// Subtype
TypePlaceholder subTphRes = tphsInRel.get(0);
// Die größte Supertype
TypePlaceholder superTphRes = tphsInRel.get(tphsInRel.size()-1);
while(subAndSuperTph.containsValue(subTphRes)) {
for(TypePlaceholder tph : subAndSuperTph.keySet()) {
if(subAndSuperTph.get(tph).equals(subTphRes)) {
subTphRes = tph;
break;
}
}
tphsInRel.put(0, subTphRes);
numOfVisitedPairs++;
}
subTphRes = tphsInRel.get(0);
GenericInsertPair sPair = new GenericInsertPair(subTphRes, superTphRes);
simplifiedPairs.add(sPair);
}
return simplifiedPairs;
}
private boolean hasTPHs(RefType ref) {
for(RefTypeOrTPHOrWildcardOrGeneric p : ref.getParaList()) {
System.out.println(p.acceptTV(new TypeToString()));
if(p.acceptTV(new TypeToString()).contains("WC")){
continue;
}
if(resultSet.resolveType(p).resolvedType instanceof TypePlaceholder)
return true;
}
return false;
}
/**
* Visits parameter type or return type with {@link SignatureVisitor} to create
* the method signature
@ -124,18 +378,34 @@ public class Signature {
}
switch (type) {
case "RT":
sv.visitClassType(t.acceptTV(new TypeToSignature()));
String sig = t.acceptTV(new TypeToSignature());
sv.visitClassType(sig.substring(1, sig.length()));
break;
case "GRT":
GenericRefType g = (GenericRefType) t;
sv.visitTypeVariable(g.acceptTV(new TypeToSignature()));
sv.visitTypeVariable(g.acceptTV(new TypeToSignature()).substring(1));
break;
case "TPH":
RefTypeOrTPHOrWildcardOrGeneric r = resultSet.resolveType(t).resolvedType;
if(!r.acceptTV(new TypeToSignature()).substring(0, 4).equals("TPH "))
sv.visitInterface().visitClassType(r.acceptTV(new TypeToSignature()));
// sv.visitClassType(r.acceptTV(new TypeToSignature()));
System.out.println(r.getClass()+" Signature TPH: "+r.acceptTV(new TypeToSignature()));
// der Fall wenn die Type eine Interface ist, muss betrachtet werden
// Deswegen muss in ResutSet noch enthalten werden, ob die Type eine
// Interface oder eine Klasse ist.
// das braucht man nicht es reicht: sv.visitTypeVariable(r.acceptTV(new TypeToSignature())
//
// if(!r.acceptTV(new TypeToSignature()).substring(0, 4).equals("TPH ")) {
String sig2 = r.acceptTV(new TypeToSignature());
if(!(r instanceof TypePlaceholder)) {
// sv.visitInterface().visitClassType(r.acceptTV(new TypeToSignature()));
// sv.visitClassType(r.acceptTV(new TypeToSignature()));
sv.visitClassType(sig2.substring(1, sig2.length()));
} else {
System.out.println(r.getClass()+" Signature TPH: "+r.acceptTV(new TypeToSignature()));
// sv.visitTypeVariable(r.acceptTV(new TypeToSignature()).substring(4)+"$");
sv.visitTypeVariable(sig2.substring(1, sig2.length()));
}
break;
default:
if(!isParameterType)
@ -155,8 +425,36 @@ public class Signature {
GenericTypeVar g = itr.next();
getBoundsOfTypeVar(g,genericsAndBounds);
}
sw.visitSuperclass().visitClassType(classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor()));;
if(!commonPairs.isEmpty()) {
ArrayList<TypePlaceholder> types = new ArrayList<>();
ArrayList<TypePlaceholder> superTypes = new ArrayList<>();
for(GenericInsertPair p : commonPairs) {
types.add(p.TA1);
superTypes.add(p.TA2);
}
for(GenericInsertPair p : commonPairs) {
String t = p.TA1.getName()+"$";
String bound = p.TA2.getName()+"$";
sw.visitFormalTypeParameter(t);
sw.visitClassBound().visitTypeVariable(bound);
genericsAndBounds.put(t, bound);
}
for(GenericInsertPair p : commonPairs) {
if(!types.contains(p.TA2)) {
String t = p.TA2.getName()+"$";
String bound = Type.getInternalName(Object.class);
sw.visitFormalTypeParameter(t);
sw.visitClassBound().visitClassType(bound);
genericsAndBounds.put(t, bound);
sw.visitClassBound().visitEnd();
}
}
}
String sClass = classOrInterface.getSuperClass().acceptTV(new TypeToSignature());
sw.visitSuperclass().visitClassType(sClass.substring(1, sClass.length()-1));
sw.visitEnd();
}
/**
@ -165,7 +463,7 @@ public class Signature {
* @param genAndBounds
*/
private void getBoundsOfTypeVar(GenericTypeVar g, HashMap<String, String> genAndBounds) {
sw.visitFormalTypeParameter(g.getParsedName());
sw.visitFormalTypeParameter(g.getName());
Iterator<? extends RefTypeOrTPHOrWildcardOrGeneric> bItr = g.getBounds().iterator();
while(bItr.hasNext()) {
@ -174,7 +472,7 @@ public class Signature {
// System.out.println("GetBounds: " + boundDesc);
// Ensure that <...> extends java.lang.Object OR ...
sw.visitClassBound().visitClassType(boundDesc);
genAndBounds.put(g.getParsedName(), boundDesc);
genAndBounds.put(g.getName(), boundDesc);
}
sw.visitClassBound().visitEnd();
}

@ -15,6 +15,8 @@ public class TypeToSignature implements TypeVisitor<String> {
@Override
public String visit(RefType refType) {
if(refType.getName().toString().equals("void"))
return "V";
// return refType.toString().replace(".", "/");
String params = "";
if(refType.getParaList().size()>0){
@ -22,27 +24,41 @@ public class TypeToSignature implements TypeVisitor<String> {
Iterator<RefTypeOrTPHOrWildcardOrGeneric> it = refType.getParaList().iterator();
while(it.hasNext()){
RefTypeOrTPHOrWildcardOrGeneric param = it.next();
params += "L"+param.toString().replace(".", "/");
if(it.hasNext())params += ";";
// if(param instanceof TypePlaceholder) {
// params += "T" + ((TypePlaceholder) param).getName() + "$";
// } else if(param instanceof ExtendsWildcardType) {
// params += "+" + ((ExtendsWildcardType) param).getInnerType().acceptTV(new TypeToSignature());
// } else if(param instanceof SuperWildcardType) {
// params += "-" + ((SuperWildcardType) param).getInnerType().acceptTV(new TypeToSignature());
// } else {
// params += "L"+param.toString().replace(".", "/");
// }
params += param.acceptTV(new TypeToSignature());
// if(it.hasNext())params += ";";
}
params += ";>";
params += ">";
}
return refType.getName().toString().replace(".", "/") + params+";";
// String t = refType.getName().toString().replace(".", "/");
// return t.equals("Fun1")?t+"$$"+params+";":t+params+";";
return "L"+refType.getName().toString().replace(".", "/") + params+";";
}
@Override
public String visit(SuperWildcardType superWildcardType) {
throw new NotImplementedException();
// throw new NotImplementedException();
return "-" + superWildcardType.getInnerType().acceptTV(new TypeToSignature());
}
@Override
public String visit(TypePlaceholder typePlaceholder) {
return typePlaceholder.toString().replace(".", "/");
// return typePlaceholder.toString().replace(".", "/");
return "T" + typePlaceholder.getName() + "$";
}
@Override
public String visit(ExtendsWildcardType extendsWildcardType) {
throw new NotImplementedException();
// throw new NotImplementedException();
return "+" + extendsWildcardType.getInnerType().acceptTV(new TypeToSignature());
}
@Override

@ -17,7 +17,7 @@ public class TypeToString implements TypeVisitor<String>{
@Override
public String visit(SuperWildcardType superWildcardType) {
throw new NotImplementedException();
return "SWC";
}
@Override
@ -27,7 +27,7 @@ public class TypeToString implements TypeVisitor<String>{
@Override
public String visit(ExtendsWildcardType extendsWildcardType) {
throw new NotImplementedException();
return "EWC";
}
@Override

@ -1,4 +1,4 @@
package de.dhbwstuttgart.bytecode;
package de.dhbwstuttgart.bytecode.utilities;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.statement.*;

@ -1,4 +1,4 @@
package de.dhbwstuttgart.bytecode;
package de.dhbwstuttgart.bytecode.utilities;
import de.dhbwstuttgart.bytecode.descriptor.DescriptorVisitor;
import de.dhbwstuttgart.syntaxtree.ParameterList;

@ -0,0 +1,29 @@
package de.dhbwstuttgart.bytecode.utilities;
import java.util.ArrayList;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.result.GenericInsertPair;
public class MethodAndTPH {
private String name;
private final ArrayList<TypePlaceholder> tphs = new ArrayList<>();
private final ArrayList<GenericInsertPair> pairs = new ArrayList<>();
public MethodAndTPH(String name) {
this.name = name;
}
public ArrayList<TypePlaceholder> getTphs() {
return tphs;
}
public ArrayList<GenericInsertPair> getPairs(){
return pairs;
}
public String getName() {
return name;
}
}

@ -1,4 +1,4 @@
package de.dhbwstuttgart.bytecode;
package de.dhbwstuttgart.bytecode.utilities;
import java.util.HashMap;
@ -9,13 +9,16 @@ import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
public class MethodFromMethodCall {
private ArgumentList argList;
private RefTypeOrTPHOrWildcardOrGeneric returnType;
private String receiverName;
private HashMap<String, String> genericsAndBoundsMethod;
private HashMap<String,String> genericsAndBounds;
public MethodFromMethodCall(ArgumentList argList,RefTypeOrTPHOrWildcardOrGeneric returnType,
HashMap<String, String> genericsAndBoundsMethod,HashMap<String,String> genericsAndBounds) {
public MethodFromMethodCall(ArgumentList argList,RefTypeOrTPHOrWildcardOrGeneric returnType,
String receiverName, HashMap<String, String> genericsAndBoundsMethod,
HashMap<String,String> genericsAndBounds) {
this.argList = argList;
this.returnType = returnType;
this.receiverName = receiverName;
this.genericsAndBoundsMethod = genericsAndBoundsMethod;
this.genericsAndBounds = genericsAndBounds;
}
@ -28,6 +31,10 @@ public class MethodFromMethodCall {
return returnType;
}
public String getReceiverName() {
return receiverName;
}
public HashMap<String, String> getGenericsAndBoundsMethod(){
return genericsAndBoundsMethod;
}

@ -1,4 +1,4 @@
package de.dhbwstuttgart.bytecode;
package de.dhbwstuttgart.bytecode.utilities;
import java.util.HashMap;

@ -1,4 +1,4 @@
package de.dhbwstuttgart.bytecode;
package de.dhbwstuttgart.bytecode.utilities;
import java.util.HashMap;

@ -1,4 +1,4 @@
package de.dhbwstuttgart.bytecode;
package de.dhbwstuttgart.bytecode.utilities;
import java.util.List;

@ -1,41 +1,58 @@
package de.dhbwstuttgart.core;
import de.dhbwstuttgart.bytecode.BytecodeGen;
import de.dhbwstuttgart.environment.CompilationEnvironment;
import de.dhbwstuttgart.parser.JavaTXParser;
import de.dhbwstuttgart.parser.NullToken;
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.ParameterList;
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.syntaxtree.visual.ASTTypePrinter;
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.RuleSet;
import de.dhbwstuttgart.typeinference.unify.TypeUnify;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
import de.dhbwstuttgart.typeinference.unify.distributeVariance;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JavaTXCompiler {
final boolean parallel = true;
final CompilationEnvironment environment;
public final Map<File, SourceFile> sourceFiles = new HashMap<>();
Boolean log = true; //gibt an ob ein Log-File nach System.getProperty("user.dir")+"/test/logFiles/log" geschrieben werden soll?
public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException {
this(Arrays.asList(sourceFile));
}
public JavaTXCompiler(File sourceFile, Boolean log) throws IOException, ClassNotFoundException {
this(sourceFile);
this.log = log;
}
public JavaTXCompiler(List<File> sources) throws IOException, ClassNotFoundException {
environment = new CompilationEnvironment(sources);
for (File s : sources) {
@ -94,20 +111,140 @@ public class JavaTXCompiler {
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);
try {
FileWriter logFile = new FileWriter(new File(System.getProperty("user.dir")+"/test/logFiles/"+"log"));
logFile.write("FC:\\" + finiteClosure.toString()+"\n");
for(SourceFile sf : this.sourceFiles.values()) {
logFile.write(ASTTypePrinter.print(sf));
}
logFile.flush();
Set<TypeUnifyTask> forks = new HashSet<>();
Set<List<Constraint<UnifyPair>>> cardProd = unifyCons.cartesianProduct();
for (List<Constraint<UnifyPair>> xCons : cardProd ){
Set<UnifyPair> xConsSet = new HashSet<>();
for (Constraint<UnifyPair> constraint : xCons) {
xConsSet.addAll(constraint);
}
//.collect(Collectors.toCollection(ArrayList::new))))
System.out.println(xConsSet);
Set<String> paraTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist()
.stream().filter(z -> z.getType() instanceof TypePlaceholder)
.map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new)))
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) )
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} );
Set<String> returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
.map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get();
xConsSet = xConsSet.stream().map(x -> {
//Hier muss ueberlegt werden, ob
//1. alle Argument- und Retuntyp-Variablen in allen UnifyPairs
// mit disableWildcardtable() werden.
//2. alle Typvariablen mit Argument- oder Retuntyp-Variablen
//in Beziehung auch auf disableWildcardtable() gesetzt werden muessen
//PL 2018-04-23
if ((x.getLhsType() instanceof PlaceholderType)) {
if (paraTypeVarNames.contains(x.getLhsType().getName())) {
((PlaceholderType)x.getLhsType()).setVariance((byte)1);
((PlaceholderType)x.getLhsType()).disableWildcardtable();
}
if (returnTypeVarNames.contains(x.getLhsType().getName())) {
((PlaceholderType)x.getLhsType()).setVariance((byte)-1);
((PlaceholderType)x.getLhsType()).disableWildcardtable();
}
}
if ((x.getRhsType() instanceof PlaceholderType)) {
if (paraTypeVarNames.contains(x.getRhsType().getName())) {
((PlaceholderType)x.getRhsType()).setVariance((byte)1);
((PlaceholderType)x.getRhsType()).disableWildcardtable();
}
if (returnTypeVarNames.contains(x.getRhsType().getName())) {
((PlaceholderType)x.getRhsType()).setVariance((byte)-1);
((PlaceholderType)x.getRhsType()).disableWildcardtable();
}
}
return x;//HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS ANDERE SEITE
}).map( y -> {
if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) {
if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && ((PlaceholderType)y.getRhsType()).getVariance() == 0) {
((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType()).getVariance());
}
if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) {
((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType()).getVariance());
}
}
return y; } )
.collect(Collectors.toCollection(HashSet::new));
varianceInheritance(xConsSet);
if (parallel) {
//Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure, logFile, log);
Set<UnifyPair> eq = new HashSet<>(xConsSet);
TypeUnifyTask fork = new TypeUnifyTask(eq, finiteClosure, true, logFile, log);
forks.add(fork);
fork.fork();
}
else {
Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure, logFile, log);
System.out.println("RESULT: " + result);
logFile.write("RES: " + result.toString()+"\n");
logFile.flush();
results.addAll(result);
}
}
for (TypeUnifyTask fork : forks) {
try {
Set<Set<UnifyPair>> result = fork.join();
System.out.println("RESULT: " + result);
logFile.write("RES: " + result.toString()+"\n");
logFile.flush();
results.addAll(result);
}
catch (ConcurrentModificationException v) {
v.printStackTrace();
while (v.getCause() instanceof ConcurrentModificationException) {
v = (ConcurrentModificationException)v.getCause();
}
System.out.println(v);
}
}
}
return results.stream().map((unifyPairs ->
new ResultSet(UnifyTypeFactory.convert(unifyPairs, generateTPHMap(cons))))).collect(Collectors.toList());
}
catch (IOException e) { }
return results.stream().map((unifyPairs ->
new ResultSet(UnifyTypeFactory.convert(unifyPairs, generateTPHMap(cons))))).collect(Collectors.toList());
}
/**
* Vererbt alle Variancen
* @param eq The set of constraints
*/
private void varianceInheritance(Set<UnifyPair> eq) {
Set<PlaceholderType> usedTPH = new HashSet<>();
Set<PlaceholderType> phSet = eq.stream().map(x -> {
Set<PlaceholderType> pair = new HashSet<>();
if (x.getLhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getLhsType());
if (x.getRhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getRhsType());
return pair;
}).reduce(new HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); return c;});
ArrayList<PlaceholderType> phSetVariance = new ArrayList<>(phSet);
phSetVariance.removeIf(x -> (x.getVariance() == 0));
while(!phSetVariance.isEmpty()) {
PlaceholderType a = phSetVariance.remove(0);
usedTPH.add(a);
//HashMap<PlaceholderType,Integer> ht = new HashMap<>();
//ht.put(a, a.getVariance());
Set<UnifyPair> eq1 = new HashSet<>(eq);
eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType && ((PlaceholderType)x.getLhsType()).equals(a)));
eq1.stream().forEach(x -> { x.getRhsType().accept(new distributeVariance(), a.getVariance());});
eq1 = new HashSet<>(eq);
eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a)));
eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(), a.getVariance());});
phSetVariance = new ArrayList<>(phSet);
phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x)));
}
}
private Map<String, TypePlaceholder> generateTPHMap(ConstraintSet<Pair> constraints) {
HashMap<String, TypePlaceholder> ret = new HashMap<>();
@ -129,5 +266,29 @@ public class JavaTXCompiler {
SourceFile ret = generator.convert(tree, environment.packageCrawler);
return ret;
}
// um pfad erweitern
public void generateBytecode(String path) throws ClassNotFoundException, IOException {
for(File f : sourceFiles.keySet()) {
HashMap<String,byte[]> classFiles = new HashMap<>();
SourceFile sf = sourceFiles.get(f);
List<ResultSet> typeinferenceResult = this.typeInference();
BytecodeGen bytecodeGen = new BytecodeGen(classFiles,typeinferenceResult,sf,path);
// BytecodeGen bytecodeGen = new BytecodeGen(classFiles,typeinferenceResult.get(0));
bytecodeGen.visit(sf);
this.writeClassFile(bytecodeGen.getClassFiles(), path);
}
}
}
private void writeClassFile(HashMap<String, byte[]> classFiles, String path) throws IOException {
FileOutputStream output;
for(String name : classFiles.keySet()) {
byte[] bytecode = classFiles.get(name);
System.out.println("generating "+name+ ".class file ...");
//output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/generatedBC/" +name+".class"));
output = new FileOutputStream(new File(path +name+".class"));
output.write(bytecode);
output.close();
System.out.println(name+".class file generated");
}
}
}

@ -1,7 +1,7 @@
package de.dhbwstuttgart.parser.SyntaxTreeGenerator;
import de.dhbwstuttgart.exceptions.DebugException;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
@ -11,6 +11,7 @@ import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.unify.model.*;
import java.util.*;
import java.util.stream.Collectors;
public class FCGenerator {
/**
@ -19,12 +20,15 @@ public class FCGenerator {
*
* @param availableClasses - Alle geparsten Klassen
*/
public static Set<UnifyPair> toFC(Collection<ClassOrInterface> availableClasses) throws ClassNotFoundException {
HashSet<UnifyPair> pairs = new HashSet<>();
public static Set<UnifyPair> toUnifyFC(Collection<ClassOrInterface> availableClasses) throws ClassNotFoundException {
return toFC(availableClasses).stream().map(t -> UnifyTypeFactory.convert(t)).collect(Collectors.toSet());
}
public static Set<Pair> toFC(Collection<ClassOrInterface> availableClasses) throws ClassNotFoundException {
HashSet<Pair> pairs = new HashSet<>();
for(ClassOrInterface cly : availableClasses){
pairs.addAll(getSuperTypes(cly, availableClasses));
}
System.out.println(pairs);
return pairs;
}
@ -35,67 +39,84 @@ public class FCGenerator {
* @param forType
* @return
*/
private static List<UnifyPair> getSuperTypes(ClassOrInterface forType, Collection<ClassOrInterface> availableClasses) throws ClassNotFoundException {
private static List<Pair> getSuperTypes(ClassOrInterface forType, Collection<ClassOrInterface> availableClasses) throws ClassNotFoundException {
return getSuperTypes(forType, availableClasses, new HashMap<>());
}
//TODO: implements Interface auch als superklassen beachten
private static List<UnifyPair> getSuperTypes(ClassOrInterface forType, Collection<ClassOrInterface> availableClasses, HashMap<String, UnifyType> gtvs) throws ClassNotFoundException {
List<UnifyType> params = new ArrayList<>();
/**
*
* @param forType
* @param availableClasses
* @param gtvs
* @return
* @throws ClassNotFoundException
*/
private static List<Pair> getSuperTypes(ClassOrInterface forType, Collection<ClassOrInterface> availableClasses,
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> gtvs) throws ClassNotFoundException {
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
//Die GTVs, die in forType hinzukommen:
HashMap<String, UnifyType> newGTVs = new HashMap<>();
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> newGTVs = new HashMap<>();
//Generics mit gleichem Namen müssen den selben TPH bekommen
for(GenericTypeVar gtv : forType.getGenerics()){
if(!gtvs.containsKey(gtv.getParsedName())){
gtvs.put(gtv.getParsedName(), PlaceholderType.freshPlaceholder());
newGTVs.put(gtv.getParsedName(), PlaceholderType.freshPlaceholder());
if(!gtvs.containsKey(gtv.getName())){
TypePlaceholder replacePlaceholder = TypePlaceholder.fresh(new NullToken());
gtvs.put(gtv.getName(), replacePlaceholder);
newGTVs.put(gtv.getName(), replacePlaceholder);
}
params.add(gtvs.get(gtv.getParsedName()));
params.add(gtvs.get(gtv.getName()));
}
Optional<ClassOrInterface> hasSuperclass = availableClasses.stream().filter(cl -> forType.getSuperClass().getName().equals(cl.getClassName())).findAny();
ClassOrInterface superClass;
if(!hasSuperclass.isPresent()) //Wenn es die Klasse in den available Klasses nicht gibt wird sie im Classpath gesucht. Ansonsten Exception
{
superClass = ASTFactory.createClass(ClassLoader.getSystemClassLoader().loadClass(forType.getSuperClass().getName().toString()));
}else{
superClass = hasSuperclass.get();
List<RefType> superClasses = new ArrayList<>();
superClasses.add(forType.getSuperClass());
superClasses.addAll(forType.getSuperInterfaces());
List<Pair> retList = new ArrayList<>();
for(RefType superType : superClasses){
Optional<ClassOrInterface> hasSuperclass = availableClasses.stream().filter(cl -> superType.getName().equals(cl.getClassName())).findAny();
ClassOrInterface superClass;
if(!hasSuperclass.isPresent()) //Wenn es die Klasse in den available Klasses nicht gibt wird sie im Classpath gesucht. Ansonsten Exception
{
superClass = ASTFactory.createClass(ClassLoader.getSystemClassLoader().loadClass(superType.getName().toString()));
}else{
superClass = hasSuperclass.get();
}
/*
Die Parameter der superklasse müssen jetzt nach den Angaben in der Subklasse
modifiziert werden
Beispie: Matrix<A> extends Vector<Vector<A>>
Den ersten Parameter mit Vector<A> austauschen und dort alle Generics zu den Typplaceholdern in gtvs austauschen
*/
//Hier vermerken, welche Typen in der Superklasse ausgetauscht werden müssen
Iterator<GenericTypeVar> itGenParams = superClass.getGenerics().iterator();
Iterator<RefTypeOrTPHOrWildcardOrGeneric> itSetParams = superType.getParaList().iterator();
while(itSetParams.hasNext()){
RefTypeOrTPHOrWildcardOrGeneric setType = itSetParams.next();
//In diesem Typ die GTVs durch TPHs und Einsetzungen austauschen:
RefTypeOrTPHOrWildcardOrGeneric setSetType = setType.acceptTV(new TypeExchanger(gtvs));
newGTVs.put(itGenParams.next().getName(), setSetType);
}
//Für den superType kann man nun zum Austauschen der Generics wieder die gtvs nehmen:
//Die newGTVs sind nur für den superClass ClassOrInterface welches möglicherweise per reflection geladen wurde abgestimmt
RefTypeOrTPHOrWildcardOrGeneric superRefType = superType.acceptTV(new TypeExchanger(gtvs));
RefTypeOrTPHOrWildcardOrGeneric t1 = new RefType(forType.getClassName(), params, new NullToken());
RefTypeOrTPHOrWildcardOrGeneric t2 = superRefType;
Pair ret = new Pair(t1, t2, PairOperator.SMALLER);
List<Pair> superTypes;
//Rekursiver Aufruf. Abbruchbedingung ist Object als Superklasse:
if(superClass.getClassName().equals(ASTFactory.createObjectClass().getClassName())){
superTypes = Arrays.asList(new Pair(ASTFactory.createObjectType(), ASTFactory.createObjectType(), PairOperator.SMALLER));
}else{
superTypes = getSuperTypes(superClass, availableClasses, newGTVs);
}
retList.add(ret);
retList.addAll(superTypes);
}
/*
Die Parameter der superklasse müssen jetzt nach den Angaben in der Subklasse
modifiziert werden
Beispie: Matrix<A> extends Vector<Vector<A>>
Den ersten Parameter mit Vector<A> austauschen und dort alle Generics zu den Typplaceholdern in gtvs austauschen
*/
//Hier vermerken, welche Typen im der Superklasse ausgetauscht werden müssen
Iterator<GenericTypeVar> itGenParams = superClass.getGenerics().iterator();
Iterator<RefTypeOrTPHOrWildcardOrGeneric> itSetParams = forType.getSuperClass().getParaList().iterator();
while(itGenParams.hasNext()){
RefTypeOrTPHOrWildcardOrGeneric setType = itSetParams.next();
//In diesem Typ die GTVs durch TPHs und Einsetzungen austauschen:
UnifyType setSetType = setType.acceptTV(new TypeExchanger(gtvs));
newGTVs.put(itGenParams.next().getParsedName(), setSetType);
}
UnifyType superType = forType.getSuperClass().acceptTV(new TypeExchanger(newGTVs));
TypeParams paramList = new TypeParams(params);
UnifyType t1 = new ReferenceType(forType.getClassName().toString(), paramList);
UnifyType t2 = superType;
UnifyPair ret = UnifyTypeFactory.generateSmallerPair(t1, t2);
List<UnifyPair> superTypes;
//Rekursiver Aufruf. Abbruchbedingung ist Object als Superklasse:
if(superClass.getClassName().equals(ASTFactory.createObjectClass().getClassName())){
superTypes = Arrays.asList(UnifyTypeFactory.generateSmallerPair(UnifyTypeFactory.convert(ASTFactory.createObjectType()), UnifyTypeFactory.convert(ASTFactory.createObjectType())));
}else{
superTypes = getSuperTypes(superClass, availableClasses, newGTVs);
}
List<UnifyPair> retList = new ArrayList<>();
retList.add(ret);
retList.addAll(superTypes);
return retList;
}
@ -103,46 +124,43 @@ public class FCGenerator {
/**
* Tauscht die GTVs in einem Typ gegen die entsprechenden Typen in der übergebenen Map aus.
*/
private static class TypeExchanger implements TypeVisitor<UnifyType>{
private static class TypeExchanger implements TypeVisitor<RefTypeOrTPHOrWildcardOrGeneric>{
private final HashMap<String, UnifyType> gtvs;
private final HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> gtvs;
TypeExchanger(HashMap<String, UnifyType> gtvs){
TypeExchanger(HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> gtvs){
this.gtvs = gtvs;
}
@Override
public UnifyType visit(RefType refType) {
List<UnifyType> params = new ArrayList<>();
public RefTypeOrTPHOrWildcardOrGeneric visit(RefType refType) {
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
for(RefTypeOrTPHOrWildcardOrGeneric param : refType.getParaList()){
params.add(param.acceptTV(this));
}
TypeParams paramList = new TypeParams(params);
UnifyType ret = new ReferenceType(refType.getName().toString(), paramList);
RefTypeOrTPHOrWildcardOrGeneric ret = new RefType(refType.getName(), params, new NullToken());
return ret;
}
@Override
public UnifyType visit(SuperWildcardType superWildcardType) {
public RefTypeOrTPHOrWildcardOrGeneric visit(SuperWildcardType superWildcardType) {
throw new DebugException("Dieser Fall darf nicht auftreten");
}
@Override
public UnifyType visit(TypePlaceholder typePlaceholder) {
public RefTypeOrTPHOrWildcardOrGeneric visit(TypePlaceholder typePlaceholder) {
throw new DebugException("Dieser Fall darf nicht auftreten");
}
@Override
public UnifyType visit(ExtendsWildcardType extendsWildcardType) {
public RefTypeOrTPHOrWildcardOrGeneric visit(ExtendsWildcardType extendsWildcardType) {
throw new DebugException("Dieser Fall darf nicht auftreten");
}
@Override
public UnifyType visit(GenericRefType genericRefType) {
public RefTypeOrTPHOrWildcardOrGeneric visit(GenericRefType genericRefType) {
if(! gtvs.containsKey(genericRefType.getParsedName()))
throw new DebugException("Dieser Fall darf nicht auftreten");
//TODO: Diesen Dirty-Hack beseitigen. Fehler tritt bei java.lang.invoke.LambdaFormEditor$Transform$Kind auf.
//return UnifyTypeFactory.convert(ASTFactory.createObjectType());
return gtvs.get(genericRefType.getParsedName());
}

@ -3,8 +3,8 @@ package de.dhbwstuttgart.parser.SyntaxTreeGenerator;
import de.dhbwstuttgart.parser.scope.JavaClassName;
public class GenericContext {
public final String parentMethod;
public final JavaClassName parentClass;
private final String parentMethod;
private final JavaClassName parentClass;
public GenericContext(JavaClassName parentClass, String parentMethod) {
if(parentMethod == null)parentMethod = "";

@ -832,7 +832,7 @@ public class StatementGenerator {
}else if(literal.StringLiteral()!=null){
RefType type = new RefType(reg.getName("java.lang.String"),literal.getStart());
return new Literal(type,
literal.StringLiteral().getText(),
literal.StringLiteral().getText().substring(1, literal.StringLiteral().getText().length()-1),
literal.getStart());
}else if(literal.NullLiteral() != null){
return new Literal(TypePlaceholder.fresh(literal.getStart()), null,
@ -904,7 +904,7 @@ public class StatementGenerator {
funNParams.add(TypePlaceholder.fresh(expression.getStart())));
RefTypeOrTPHOrWildcardOrGeneric lambdaType = TypePlaceholder.fresh(expression.getStart());
//RefType lambdaType = new RefType(reg.getName("Fun"+params.getFormalparalist().size()),
//funNParams, name.getStart());
//funNParams, name.getStart());
return new LambdaExpression(lambdaType, params, block, expression.getStart());
}
}

@ -73,6 +73,7 @@ public class SyntaxTreeGenerator{
}
public SourceFile convert(Java8Parser.CompilationUnitContext ctx, PackageCrawler packageCrawler) throws ClassNotFoundException{
if(ctx.packageDeclaration()!=null)this.pkgName = convert(ctx.packageDeclaration());
List<ClassOrInterface> classes = new ArrayList<>();
Map<String, Integer> imports = GatherNames.getImports(ctx, packageCrawler);
this.imports = imports.keySet().stream().map(name -> reg.getName(name)).collect(Collectors.toSet());
@ -89,6 +90,15 @@ public class SyntaxTreeGenerator{
return new SourceFile(this.pkgName, classes, this.imports);
}
private String convert(Java8Parser.PackageDeclarationContext packageDeclarationContext) {
String ret = "";
for(TerminalNode identifier : packageDeclarationContext.Identifier()){
ret += identifier.getText()+".";
}
ret = ret.substring(0, ret.length()-1);
return ret;
}
public Method convert(Java8Parser.MethodDeclarationContext methodDeclarationContext, JavaClassName parentClass, RefType superClass, GenericsRegistry generics) {
Java8Parser.MethodHeaderContext header = methodDeclarationContext.methodHeader();
int modifiers = SyntaxTreeGenerator.convert(methodDeclarationContext.methodModifier());
@ -165,8 +175,8 @@ public class SyntaxTreeGenerator{
}
}
String className = this.pkgName + (this.pkgName.length()>0?".":"") + ctx.Identifier().getText();
JavaClassName name = reg.getName(className);
if(! name.toString().equals(className)){
JavaClassName name = reg.getName(className); //Holt den Package Namen mit dazu
if(! name.toString().equals(className)){ //Kommt die Klasse schon in einem anderen Package vor?
throw new TypeinferenceException("Name " + className + " bereits vorhanden in " + reg.getName(className).toString()
,ctx.getStart());
}
@ -203,20 +213,20 @@ public class SyntaxTreeGenerator{
}
Boolean isInterface = false;
List<RefTypeOrTPHOrWildcardOrGeneric> implementedInterfaces = convert(ctx.superinterfaces(), generics);
List<RefType> implementedInterfaces = convert(ctx.superinterfaces(), generics);
return new ClassOrInterface(modifiers, name, fielddecl, methods, konstruktoren, genericClassParameters, superClass,
isInterface, implementedInterfaces, offset);
}
private List<RefTypeOrTPHOrWildcardOrGeneric> convert(Java8Parser.SuperinterfacesContext ctx, GenericsRegistry generics) {
private List<RefType> convert(Java8Parser.SuperinterfacesContext ctx, GenericsRegistry generics) {
if(ctx == null)return new ArrayList<>();
return convert(ctx.interfaceTypeList(), generics);
}
private List<RefTypeOrTPHOrWildcardOrGeneric> convert(Java8Parser.InterfaceTypeListContext ctx, GenericsRegistry generics) {
List<RefTypeOrTPHOrWildcardOrGeneric> ret = new ArrayList<>();
private List<RefType> convert(Java8Parser.InterfaceTypeListContext ctx, GenericsRegistry generics) {
List<RefType> ret = new ArrayList<>();
for(Java8Parser.InterfaceTypeContext interfaceType : ctx.interfaceType()){
ret.add(TypeGenerator.convert(interfaceType.classType(), reg, generics));
ret.add((RefType) TypeGenerator.convert(interfaceType.classType(), reg, generics));
}
return ret;
}
@ -400,7 +410,7 @@ public class SyntaxTreeGenerator{
List<Field> fields = convertFields(ctx.interfaceBody());
List<Method> methods = convertMethods(ctx.interfaceBody(), name, superClass, generics);
List<RefTypeOrTPHOrWildcardOrGeneric> extendedInterfaces = convert(ctx.extendsInterfaces(), generics);
List<RefType> extendedInterfaces = convert(ctx.extendsInterfaces(), generics);
return new ClassOrInterface(modifiers, name, fields, methods, new ArrayList<>(),
genericParams, superClass, true, extendedInterfaces, ctx.getStart());
@ -423,7 +433,7 @@ public class SyntaxTreeGenerator{
return ret;
}
private List<RefTypeOrTPHOrWildcardOrGeneric> convert(Java8Parser.ExtendsInterfacesContext extendsInterfacesContext, GenericsRegistry generics) {
private List<RefType> convert(Java8Parser.ExtendsInterfacesContext extendsInterfacesContext, GenericsRegistry generics) {
if(extendsInterfacesContext == null)return new ArrayList<>();
return convert(extendsInterfacesContext.interfaceTypeList(), generics);
}

@ -3,7 +3,6 @@ package de.dhbwstuttgart.parser.SyntaxTreeGenerator;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.exceptions.TypeinferenceException;
import de.dhbwstuttgart.parser.antlr.Java8Parser;
import de.dhbwstuttgart.parser.scope.GenericTypeName;
import de.dhbwstuttgart.parser.scope.GenericsRegistry;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
@ -23,18 +22,20 @@ import java.util.List;
public class TypeGenerator {
public static RefTypeOrTPHOrWildcardOrGeneric convert(Java8Parser.UnannClassOrInterfaceTypeContext unannClassOrInterfaceTypeContext, JavaClassRegistry reg, GenericsRegistry generics) {
String name;
if(unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType() != null){
name = unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType().unannClassType_lfno_unannClassOrInterfaceType().Identifier().getText();
}
Java8Parser.TypeArgumentsContext arguments;
if(unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType() != null){
name = unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType().Identifier().getText();
arguments = unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType().typeArguments();
}else{// if(unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType() != null){
name = unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType().unannClassType_lfno_unannClassOrInterfaceType().getText();
arguments = unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType().unannClassType_lfno_unannClassOrInterfaceType().typeArguments();
}
/**
* Problem sind hier die verschachtelten Typen mit verschachtelten Typargumenten
* Beispiel: Typ<String>.InnererTyp<Integer>
*/
String name = unannClassOrInterfaceTypeContext.getText();
if(name.contains("<")){
name = name.split("<")[0]; //Der Typ ist alles vor den ersten Argumenten
}
return convertTypeName(name, arguments, unannClassOrInterfaceTypeContext.getStart(), reg, generics);
}
@ -75,7 +76,7 @@ public class TypeGenerator {
//Problem <A extends B, B> ist erlaubt, würde aber bei den Bounds von A den Generic B nicht als solchen erkennen
List<RefTypeOrTPHOrWildcardOrGeneric> bounds = TypeGenerator.convert(typeParameter.typeBound(),reg, generics);
GenericTypeVar ret = new GenericTypeVar(new GenericTypeName(new GenericContext(parentClass, parentMethod), name), bounds, typeParameter.getStart(), typeParameter.getStop());
GenericTypeVar ret = new GenericTypeVar(name, bounds, typeParameter.getStart(), typeParameter.getStop());
generics.put(name, new GenericContext(parentClass, parentMethod));
return ret;
}
@ -114,9 +115,7 @@ public class TypeGenerator {
if(referenceTypeContext.classOrInterfaceType() != null){
if(referenceTypeContext.classOrInterfaceType().classType_lfno_classOrInterfaceType()!= null){
Java8Parser.ClassType_lfno_classOrInterfaceTypeContext ctx = referenceTypeContext.classOrInterfaceType().classType_lfno_classOrInterfaceType();
//return convertTypeName(ctx.Identifier().toString(), ctx.typeArguments(),referenceTypeContext.getStart(), reg, generics);
if(ctx.typeArguments() != null)throw new NotImplementedException();
return convertTypeName(referenceTypeContext.getText(), null,referenceTypeContext.getStart(), reg, generics);
return convertTypeName(ctx.Identifier().toString(), ctx.typeArguments(),referenceTypeContext.getStart(), reg, generics);
}else{
throw new NotImplementedException();
}
@ -133,7 +132,7 @@ public class TypeGenerator {
String name, Java8Parser.TypeArgumentsContext typeArguments, Token offset, JavaClassRegistry reg, GenericsRegistry generics){
if(!reg.contains(name)){ //Dann könnte es ein Generische Type sein
if(generics.contains(name)){
return new GenericRefType(new GenericTypeName(generics.get(name),name), offset);
return new GenericRefType(name, offset);
}else{
throw new TypeinferenceException("Der Typ "+ name + " ist nicht vorhanden",offset);
}

@ -1,26 +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();
}
public JavaClassName getParentClass() {
return parentClass;
}
}

@ -0,0 +1,40 @@
package de.dhbwstuttgart.sat.asp;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import java.util.HashMap;
import java.util.Map;
public class ASPStringConverter {
private static final Map<String, String> replacements = new HashMap<>();
static{
replacements.put(".", "_DOT_");
replacements.put("$", "_DOLLAR_");
}
public static String toConstant(JavaClassName name){
return toConstant(name.toString());
}
public static String toConstant(String name){
return "c" + replace(name);
}
public static String fromConstant(String s){
return unReplace(s).substring(1);
}
private static String replace(String input){
for(String toReplace : replacements.keySet()){
input = input.replace(toReplace, replacements.get(toReplace));
}
return input;
}
private static String unReplace(String input){
for(String toReplace : replacements.keySet()){
input = input.replace(replacements.get(toReplace), toReplace);
}
return input;
}
}

@ -17,26 +17,32 @@ public class Clingo {
private static final List<File> programFiles = new ArrayList<>();
static{
programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/basis.lp"));
programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/finiteclosure.lp"));
programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/subst.lp"));
programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/reduce1.lp"));
programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/reduce2.lp"));
programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/reduce.lp"));
programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/unify.lp"));
programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/adapt.lp"));
}
public Clingo(List<File> inputFiles){
this.input = inputFiles;
}
/*
TODO: Clingo per Java Wrapper https://stackoverflow.com/questions/3356200/using-java-to-wrap-over-c
*/
public String runClingo() throws IOException, InterruptedException {
String pathToClingo =
"/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/clingo-5.2.1-linux-x86_64/clingo";
List<String> commands = new ArrayList<>();
commands.add(pathToClingo);
commands.add("--outf=2"); //use JSON-Output
//commands.add("--outf=2"); //use JSON-Output
commands.add("--outf=1"); //use JSON-Output
for(File file : input){
commands.add(file.getPath());
}
commands.addAll(programFiles.stream().map(f->f.getPath()).collect(Collectors.toList()));
Process clingo = new ProcessBuilder( commands.toArray(new String[0])).start();
InputStream output = clingo.getInputStream();
clingo.waitFor();

@ -0,0 +1,26 @@
package de.dhbwstuttgart.sat.asp.model;
public enum ASPGencayRule {
ASP_PAIR_EQUALS_NAME("equals"),
ASP_PAIR_SMALLER_NAME("sub"),
ASP_PAIR_SMALLER_DOT_NAME("subEq"),
ASP_PARAMLIST_NAME("paramEq"),
ASP_FC_PARAMLIST_NAME("param"),
ASP_PARAMLIST_END_POINTER("null"),
ASP_TYPE("typeEq"),
ASP_FCTYPE("type"),
ASP_TYPE_VAR("var"),
ASP_GENERIC_VAR("pph"),
ASP_PARAMLIST_ORDER("paramOrder");
private final String text;
private ASPGencayRule(final String text) {
this.text = text;
}
@Override
public String toString() {
return text;
}
}

@ -1,16 +1,14 @@
package de.dhbwstuttgart.sat.asp.model;
public enum ASPRule {
ASP_GENERIC_TYPE_NAME("genericType"),
ASP_PAIR_EQUALS_NAME("equals"),
ASP_PAIR_SMALLER_NAME("smaller"),
ASP_PAIR_SMALLER_DOT_NAME("smallerDot"),
ASP_PARAMLIST_NAME("param"),
ASP_PARAMLISTNUMERATION_NAME("paramNum"),
ASP_PARAMLIST_END_POINTER("null"),
ASP_TYPE("type"),
ASP_FCTYPE("type")
;
ASP_FCTYPE("typeFC"),
ASP_TYPE_VAR("typeVar");
private final String text;

@ -1,17 +1,231 @@
package de.dhbwstuttgart.sat.asp.parser;
import de.dhbwstuttgart.typeinference.result.ResultPair;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.exceptions.DebugException;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.sat.asp.ASPStringConverter;
import de.dhbwstuttgart.sat.asp.model.ASPRule;
import de.dhbwstuttgart.sat.asp.parser.antlr.UnifyResultBaseListener;
import de.dhbwstuttgart.sat.asp.parser.antlr.UnifyResultLexer;
import de.dhbwstuttgart.sat.asp.parser.antlr.UnifyResultParser;
import de.dhbwstuttgart.sat.asp.parser.model.ParsedType;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.typeinference.result.*;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.util.HashSet;
import java.util.Set;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import java.io.StringReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ASPParser {
ResultSet parse(String result){
Set<ResultPair> ret = new HashSet<>();
for(String pair : result.split(",")){
/**
* Ablauf:
* - Erst werden alle benötigten Statements eingelesen. Die Pointer bleiben als Strings erhalten
* - Anschließend müssen diese wieder zu einem Unify Ergebnis zurückgewandelt werden
* - Hier nicht die Typen aus dem unify.model packages verwenden.
* TODO: Überlegen welche Informationen noch nach der Unifizierung gebraucht werden
* -> Eigentlich nur die korrekten Namen der Typen und TPHs
*/
public class ASPParser extends UnifyResultBaseListener {
private Collection<TypePlaceholder> originalTPHs;
private ResultSet resultSet;
private Map<String, ParsedType> types = new HashMap<>();
private Set<String> tphs = new HashSet<>();
private Map<String, ParameterListNode> parameterLists = new HashMap<>();
private Set<Relation> equalsRelations = new HashSet<>();
private Set<Relation> smallerRelations = new HashSet<>();
/**
* Parst clingo output welcher als JSON (option --outf=2) ausgibt
* @param toParse
* @return
*/
public static ResultSet parse(String toParse, Collection<TypePlaceholder> oldPlaceholders){
return new ASPParser(toParse, oldPlaceholders).resultSet;
}
@Override
public void enterParameter(UnifyResultParser.ParameterContext ctx) {
//Linked List (pointer, Type, nextPointer)
List<String> params = parseParameterList(ctx.parameterList());
parameterLists.put(params.get(0), new ParameterListNode(params.get(1), params.get(2)));
}
private static class Relation {
public final String right;
public final String left;
Relation(String leftType, String rightType){
this.left = leftType;
this.right = rightType;
}
return new ResultSet(ret);
@Override
public int hashCode() {
return (left+right).hashCode();
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Relation)
return (right+left).equals(((Relation) obj).left+((Relation) obj).right);
return super.equals(obj);
}
}
private List<String> parseParameterList(UnifyResultParser.ParameterListContext ctx){
return ctx.value().stream().map(v ->
//ASPStringConverter.fromConstant(v.getText())
v.getText()
).collect(Collectors.toList());
}
@Override
public void enterEquals(UnifyResultParser.EqualsContext ctx) {
List<String> parameterList = parseParameterList(ctx.parameterList());
if(parameterList.size()<2)throw new DebugException("Fehler in Equals-Regel");
String ls = parameterList.get(0);
String rs = parameterList.get(1);
equalsRelations.add(new Relation(ls, rs));
}
@Override
public void enterSmaller(UnifyResultParser.SmallerContext ctx) {
List<String> parameterList = parseParameterList(ctx.parameterList());
if(parameterList.size()<2)throw new DebugException("Fehler in Smaller-Regel");
String ls = parameterList.get(0);
String rs = parameterList.get(1);
smallerRelations.add(new Relation(ls, rs));
}
@Override
public void enterTypeVar(UnifyResultParser.TypeVarContext ctx) {
List<String> parameterList = parseParameterList(ctx.parameterList());
if(parameterList.size()<1)throw new DebugException("Fehler in typeVar-Regel");
tphs.add(parameterList.get(0));
}
@Override
public void enterType(UnifyResultParser.TypeContext ctx){
List<String> parameterList = parseParameterList(ctx.parameterList());
if(parameterList.size()<3)throw new DebugException("Fehler in Type-Regel");
String name = parameterList.get(0);
String typeName = parameterList.get(1);
String paramPointer = parameterList.get(2);
types.put(name, new ParsedType(typeName, paramPointer));
}
/*
private List<String> parsedRule;
private List<String> parseRule(String rule){
UnifyResultLexer lexer = new UnifyResultLexer(CharStreams.fromString(rule));
UnifyResultParser.AspruleContext parseTree = new UnifyResultParser(new CommonTokenStream(lexer)).asprule();
parsedRule = new ArrayList<>();
new ParseTreeWalker().walk(this, parseTree);
return parsedRule;
}
@Override
public void enterAsprule(UnifyResultParser.AspruleContext ctx) {
super.enterAsprule(ctx);
for(int i = 0; i< ctx.getChildCount();i++){
parsedRule.add(ctx.getChild(i).getText());
}
}
*/
private ASPParser(String toParse, Collection<TypePlaceholder> oldPlaceholders){
//System.out.println(toParse);
this.originalTPHs = oldPlaceholders;
/*
JsonObject jsonResult = Json.createReader(new StringReader(toParse)).readObject();
JsonArray results = jsonResult.getJsonArray("Call").getJsonObject(0).
getJsonArray("Witnesses").getJsonObject(0).
getJsonArray("Value");
//Im ersten Schritt werden alle Regeln geparst
String completeResult = "";
for(int i = 0; i<results.size();i++){
String aspStatement = results.getString(i);
completeResult += aspStatement + " ";
}
System.out.println(completeResult);
*/
UnifyResultLexer lexer = new UnifyResultLexer(CharStreams.fromString(toParse));
UnifyResultParser.AnswerContext parseTree = new UnifyResultParser(new CommonTokenStream(lexer)).answer();
new ParseTreeWalker().walk(this, parseTree);
/*
Diese Funktion läuft im folgenden mehrmals über das Result aus dem ASP Programm.
Dabei werden Schritt für Schritt die Felder dieser Klasse befüllt die am Schluss das ResultSet ergeben
*/
Set<ResultPair> ret = new HashSet<>();
//Zuerst die params und typeVars:
//for(String paramPointer : types.values().stream().map(parsedType -> parsedType.params).collect(Collectors.toList())){ }
//Dann die Equalsdot Statements
for(Relation eq : equalsRelations){
RefTypeOrTPHOrWildcardOrGeneric lsType = this.getType(eq.left);
RefTypeOrTPHOrWildcardOrGeneric rsType = this.getType(eq.right);
if(lsType instanceof TypePlaceholder && rsType instanceof RefType)
ret.add(new PairTPHequalRefTypeOrWildcardType((TypePlaceholder) lsType, rsType));
else if(lsType instanceof TypePlaceholder && rsType instanceof TypePlaceholder)
ret.add(new PairTPHEqualTPH((TypePlaceholder)lsType, (TypePlaceholder)rsType));
else throw new NotImplementedException();
}
this.resultSet = new ResultSet(ret);
}
private RefTypeOrTPHOrWildcardOrGeneric getType(String name) {
if(tphs.contains(name)){
name = ASPStringConverter.fromConstant(name);
for(TypePlaceholder tph : originalTPHs){
if(tph.getName().equals(name))return tph;
}
return TypePlaceholder.fresh(new NullToken());
}else
if(types.containsKey(name)){
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
ParsedType t = types.get(name);
for(String param : getParams(t.params)){
params.add(this.getType(param));
}
return new RefType(new JavaClassName(ASPStringConverter.fromConstant(t.name)), params, new NullToken());
}else throw new DebugException("Der Typ " + name + " konnte nicht bestimmt werden");
}
private static class ParameterListNode{
final String type;
final String nextNode;
public ParameterListNode(String type, String next) {
this.type = type;
this.nextNode = next;
}
}
private List<String> getParams(String pointer) {
List<String> params = new ArrayList<>();
while(pointer != null){
if(pointer.equals(ASPRule.ASP_PARAMLIST_END_POINTER.toString()))return params;
if(!parameterLists.containsKey(pointer))
throw new DebugException("Fehler in Ergebnisparsen");
//TODO: Fehler in ASP. Die adapt Regel muss erkennen, wenn die Parameterliste auf der linken Seite kürzer ist und diese Rechtzeitig beenden
ParameterListNode param = parameterLists.get(pointer);
pointer = param.nextNode;
params.add(param.type);
}
return params;
//Optional<ASPParameterList> ret = parameterLists.stream().filter(aspParameterList -> aspParameterList.name.equals(rs)).findAny();
//return ret.get();
}
}

@ -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
;

@ -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

@ -0,0 +1,159 @@
// Generated from UnifyResult.g4 by ANTLR 4.7
package de.dhbwstuttgart.sat.asp.parser.antlr;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode;
/**
* This class provides an empty implementation of {@link UnifyResultListener},
* which can be extended to create a listener which only needs to handle a subset
* of the available methods.
*/
public class UnifyResultBaseListener implements UnifyResultListener {
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterAnswer(UnifyResultParser.AnswerContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitAnswer(UnifyResultParser.AnswerContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterResultSetRule(UnifyResultParser.ResultSetRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitResultSetRule(UnifyResultParser.ResultSetRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterParameterList(UnifyResultParser.ParameterListContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitParameterList(UnifyResultParser.ParameterListContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterValue(UnifyResultParser.ValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitValue(UnifyResultParser.ValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterParameter(UnifyResultParser.ParameterContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitParameter(UnifyResultParser.ParameterContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterEquals(UnifyResultParser.EqualsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitEquals(UnifyResultParser.EqualsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterSmaller(UnifyResultParser.SmallerContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitSmaller(UnifyResultParser.SmallerContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterTypeVar(UnifyResultParser.TypeVarContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitTypeVar(UnifyResultParser.TypeVarContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterType(UnifyResultParser.TypeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitType(UnifyResultParser.TypeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOtherRule(UnifyResultParser.OtherRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOtherRule(UnifyResultParser.OtherRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitTerminal(TerminalNode node) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitErrorNode(ErrorNode node) { }
}

@ -0,0 +1,134 @@
// Generated from UnifyResult.g4 by ANTLR 4.7
package de.dhbwstuttgart.sat.asp.parser.antlr;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.misc.*;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class UnifyResultLexer extends Lexer {
static { RuntimeMetaData.checkVersion("4.7", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
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;
public static String[] channelNames = {
"DEFAULT_TOKEN_CHANNEL", "HIDDEN"
};
public static String[] modeNames = {
"DEFAULT_MODE"
};
public static final String[] ruleNames = {
"T__0", "T__1", "T__2", "T__3", "T__4", "PARAMLIST_NAME", "EQUALS_NAME",
"SMALLER_NAME", "TYPEVAR_NAME", "TYPE_NAME", "NAME", "WS", "LINE_COMMENT"
};
private static final String[] _LITERAL_NAMES = {
null, "'ANSWER'", "'.'", "'('", "','", "')'", "'param'", "'equals'", "'smaller'",
"'typeVar'", "'type'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, null, null, null, null, null, "PARAMLIST_NAME", "EQUALS_NAME", "SMALLER_NAME",
"TYPEVAR_NAME", "TYPE_NAME", "NAME", "WS", "LINE_COMMENT"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
public UnifyResultLexer(CharStream input) {
super(input);
_interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
@Override
public String getGrammarFileName() { return "UnifyResult.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public String[] getChannelNames() { return channelNames; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
public ATN getATN() { return _ATN; }
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\17c\b\1\4\2\t\2\4"+
"\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t"+
"\13\4\f\t\f\4\r\t\r\4\16\t\16\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\3\3\3\3\4"+
"\3\4\3\5\3\5\3\6\3\6\3\7\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3\b\3\b\3\b\3\b\3"+
"\b\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\13"+
"\3\13\3\13\3\13\3\13\3\f\6\fP\n\f\r\f\16\fQ\3\r\6\rU\n\r\r\r\16\rV\3\r"+
"\3\r\3\16\3\16\7\16]\n\16\f\16\16\16`\13\16\3\16\3\16\2\2\17\3\3\5\4\7"+
"\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\17\3\2\5\6\2\62;C\\"+
"aac|\5\2\13\f\16\17\"\"\4\2\f\f\17\17\2e\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3"+
"\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2"+
"\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\3\35"+
"\3\2\2\2\5$\3\2\2\2\7&\3\2\2\2\t(\3\2\2\2\13*\3\2\2\2\r,\3\2\2\2\17\62"+
"\3\2\2\2\219\3\2\2\2\23A\3\2\2\2\25I\3\2\2\2\27O\3\2\2\2\31T\3\2\2\2\33"+
"Z\3\2\2\2\35\36\7C\2\2\36\37\7P\2\2\37 \7U\2\2 !\7Y\2\2!\"\7G\2\2\"#\7"+
"T\2\2#\4\3\2\2\2$%\7\60\2\2%\6\3\2\2\2&\'\7*\2\2\'\b\3\2\2\2()\7.\2\2"+
")\n\3\2\2\2*+\7+\2\2+\f\3\2\2\2,-\7r\2\2-.\7c\2\2./\7t\2\2/\60\7c\2\2"+
"\60\61\7o\2\2\61\16\3\2\2\2\62\63\7g\2\2\63\64\7s\2\2\64\65\7w\2\2\65"+
"\66\7c\2\2\66\67\7n\2\2\678\7u\2\28\20\3\2\2\29:\7u\2\2:;\7o\2\2;<\7c"+
"\2\2<=\7n\2\2=>\7n\2\2>?\7g\2\2?@\7t\2\2@\22\3\2\2\2AB\7v\2\2BC\7{\2\2"+
"CD\7r\2\2DE\7g\2\2EF\7X\2\2FG\7c\2\2GH\7t\2\2H\24\3\2\2\2IJ\7v\2\2JK\7"+
"{\2\2KL\7r\2\2LM\7g\2\2M\26\3\2\2\2NP\t\2\2\2ON\3\2\2\2PQ\3\2\2\2QO\3"+
"\2\2\2QR\3\2\2\2R\30\3\2\2\2SU\t\3\2\2TS\3\2\2\2UV\3\2\2\2VT\3\2\2\2V"+
"W\3\2\2\2WX\3\2\2\2XY\b\r\2\2Y\32\3\2\2\2Z^\7\'\2\2[]\n\4\2\2\\[\3\2\2"+
"\2]`\3\2\2\2^\\\3\2\2\2^_\3\2\2\2_a\3\2\2\2`^\3\2\2\2ab\b\16\2\2b\34\3"+
"\2\2\2\6\2QV^\3\b\2\2";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}

@ -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

@ -0,0 +1,110 @@
// Generated from UnifyResult.g4 by ANTLR 4.7
package de.dhbwstuttgart.sat.asp.parser.antlr;
import org.antlr.v4.runtime.tree.ParseTreeListener;
/**
* This interface defines a complete listener for a parse tree produced by
* {@link UnifyResultParser}.
*/
public interface UnifyResultListener extends ParseTreeListener {
/**
* Enter a parse tree produced by {@link UnifyResultParser#answer}.
* @param ctx the parse tree
*/
void enterAnswer(UnifyResultParser.AnswerContext ctx);
/**
* Exit a parse tree produced by {@link UnifyResultParser#answer}.
* @param ctx the parse tree
*/
void exitAnswer(UnifyResultParser.AnswerContext ctx);
/**
* Enter a parse tree produced by {@link UnifyResultParser#resultSetRule}.
* @param ctx the parse tree
*/
void enterResultSetRule(UnifyResultParser.ResultSetRuleContext ctx);
/**
* Exit a parse tree produced by {@link UnifyResultParser#resultSetRule}.
* @param ctx the parse tree
*/
void exitResultSetRule(UnifyResultParser.ResultSetRuleContext ctx);
/**
* Enter a parse tree produced by {@link UnifyResultParser#parameterList}.
* @param ctx the parse tree
*/
void enterParameterList(UnifyResultParser.ParameterListContext ctx);
/**
* Exit a parse tree produced by {@link UnifyResultParser#parameterList}.
* @param ctx the parse tree
*/
void exitParameterList(UnifyResultParser.ParameterListContext ctx);
/**
* Enter a parse tree produced by {@link UnifyResultParser#value}.
* @param ctx the parse tree
*/
void enterValue(UnifyResultParser.ValueContext ctx);
/**
* Exit a parse tree produced by {@link UnifyResultParser#value}.
* @param ctx the parse tree
*/
void exitValue(UnifyResultParser.ValueContext ctx);
/**
* Enter a parse tree produced by {@link UnifyResultParser#parameter}.
* @param ctx the parse tree
*/
void enterParameter(UnifyResultParser.ParameterContext ctx);
/**
* Exit a parse tree produced by {@link UnifyResultParser#parameter}.
* @param ctx the parse tree
*/
void exitParameter(UnifyResultParser.ParameterContext ctx);
/**
* Enter a parse tree produced by {@link UnifyResultParser#equals}.
* @param ctx the parse tree
*/
void enterEquals(UnifyResultParser.EqualsContext ctx);
/**
* Exit a parse tree produced by {@link UnifyResultParser#equals}.
* @param ctx the parse tree
*/
void exitEquals(UnifyResultParser.EqualsContext ctx);
/**
* Enter a parse tree produced by {@link UnifyResultParser#smaller}.
* @param ctx the parse tree
*/
void enterSmaller(UnifyResultParser.SmallerContext ctx);
/**
* Exit a parse tree produced by {@link UnifyResultParser#smaller}.
* @param ctx the parse tree
*/
void exitSmaller(UnifyResultParser.SmallerContext ctx);
/**
* Enter a parse tree produced by {@link UnifyResultParser#typeVar}.
* @param ctx the parse tree
*/
void enterTypeVar(UnifyResultParser.TypeVarContext ctx);
/**
* Exit a parse tree produced by {@link UnifyResultParser#typeVar}.
* @param ctx the parse tree
*/
void exitTypeVar(UnifyResultParser.TypeVarContext ctx);
/**
* Enter a parse tree produced by {@link UnifyResultParser#type}.
* @param ctx the parse tree
*/
void enterType(UnifyResultParser.TypeContext ctx);
/**
* Exit a parse tree produced by {@link UnifyResultParser#type}.
* @param ctx the parse tree
*/
void exitType(UnifyResultParser.TypeContext ctx);
/**
* Enter a parse tree produced by {@link UnifyResultParser#otherRule}.
* @param ctx the parse tree
*/
void enterOtherRule(UnifyResultParser.OtherRuleContext ctx);
/**
* Exit a parse tree produced by {@link UnifyResultParser#otherRule}.
* @param ctx the parse tree
*/
void exitOtherRule(UnifyResultParser.OtherRuleContext ctx);
}

@ -0,0 +1,639 @@
// Generated from UnifyResult.g4 by ANTLR 4.7
package de.dhbwstuttgart.sat.asp.parser.antlr;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.*;
import org.antlr.v4.runtime.tree.*;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class UnifyResultParser extends Parser {
static { RuntimeMetaData.checkVersion("4.7", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
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;
public static final int
RULE_answer = 0, RULE_resultSetRule = 1, RULE_parameterList = 2, RULE_value = 3,
RULE_parameter = 4, RULE_equals = 5, RULE_smaller = 6, RULE_typeVar = 7,
RULE_type = 8, RULE_otherRule = 9;
public static final String[] ruleNames = {
"answer", "resultSetRule", "parameterList", "value", "parameter", "equals",
"smaller", "typeVar", "type", "otherRule"
};
private static final String[] _LITERAL_NAMES = {
null, "'ANSWER'", "'.'", "'('", "','", "')'", "'param'", "'equals'", "'smaller'",
"'typeVar'", "'type'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, null, null, null, null, null, "PARAMLIST_NAME", "EQUALS_NAME", "SMALLER_NAME",
"TYPEVAR_NAME", "TYPE_NAME", "NAME", "WS", "LINE_COMMENT"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public String getGrammarFileName() { return "UnifyResult.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public ATN getATN() { return _ATN; }
public UnifyResultParser(TokenStream input) {
super(input);
_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
public static class AnswerContext extends ParserRuleContext {
public List<ResultSetRuleContext> resultSetRule() {
return getRuleContexts(ResultSetRuleContext.class);
}
public ResultSetRuleContext resultSetRule(int i) {
return getRuleContext(ResultSetRuleContext.class,i);
}
public AnswerContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_answer; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).enterAnswer(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).exitAnswer(this);
}
}
public final AnswerContext answer() throws RecognitionException {
AnswerContext _localctx = new AnswerContext(_ctx, getState());
enterRule(_localctx, 0, RULE_answer);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(20);
match(T__0);
setState(26);
_errHandler.sync(this);
_la = _input.LA(1);
while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << PARAMLIST_NAME) | (1L << EQUALS_NAME) | (1L << SMALLER_NAME) | (1L << TYPEVAR_NAME) | (1L << TYPE_NAME) | (1L << NAME))) != 0)) {
{
{
setState(21);
resultSetRule();
setState(22);
match(T__1);
}
}
setState(28);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ResultSetRuleContext extends ParserRuleContext {
public ParameterContext parameter() {
return getRuleContext(ParameterContext.class,0);
}
public EqualsContext equals() {
return getRuleContext(EqualsContext.class,0);
}
public SmallerContext smaller() {
return getRuleContext(SmallerContext.class,0);
}
public TypeVarContext typeVar() {
return getRuleContext(TypeVarContext.class,0);
}
public TypeContext type() {
return getRuleContext(TypeContext.class,0);
}
public OtherRuleContext otherRule() {
return getRuleContext(OtherRuleContext.class,0);
}
public ResultSetRuleContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_resultSetRule; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).enterResultSetRule(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).exitResultSetRule(this);
}
}
public final ResultSetRuleContext resultSetRule() throws RecognitionException {
ResultSetRuleContext _localctx = new ResultSetRuleContext(_ctx, getState());
enterRule(_localctx, 2, RULE_resultSetRule);
try {
setState(35);
_errHandler.sync(this);
switch (_input.LA(1)) {
case PARAMLIST_NAME:
enterOuterAlt(_localctx, 1);
{
setState(29);
parameter();
}
break;
case EQUALS_NAME:
enterOuterAlt(_localctx, 2);
{
setState(30);
equals();
}
break;
case SMALLER_NAME:
enterOuterAlt(_localctx, 3);
{
setState(31);
smaller();
}
break;
case TYPEVAR_NAME:
enterOuterAlt(_localctx, 4);
{
setState(32);
typeVar();
}
break;
case TYPE_NAME:
enterOuterAlt(_localctx, 5);
{
setState(33);
type();
}
break;
case NAME:
enterOuterAlt(_localctx, 6);
{
setState(34);
otherRule();
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ParameterListContext extends ParserRuleContext {
public List<ValueContext> value() {
return getRuleContexts(ValueContext.class);
}
public ValueContext value(int i) {
return getRuleContext(ValueContext.class,i);
}
public ParameterListContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_parameterList; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).enterParameterList(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).exitParameterList(this);
}
}
public final ParameterListContext parameterList() throws RecognitionException {
ParameterListContext _localctx = new ParameterListContext(_ctx, getState());
enterRule(_localctx, 4, RULE_parameterList);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(37);
match(T__2);
setState(38);
value();
setState(43);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__3) {
{
{
setState(39);
match(T__3);
setState(40);
value();
}
}
setState(45);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(46);
match(T__4);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ValueContext extends ParserRuleContext {
public TerminalNode NAME() { return getToken(UnifyResultParser.NAME, 0); }
public ResultSetRuleContext resultSetRule() {
return getRuleContext(ResultSetRuleContext.class,0);
}
public ValueContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_value; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).enterValue(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).exitValue(this);
}
}
public final ValueContext value() throws RecognitionException {
ValueContext _localctx = new ValueContext(_ctx, getState());
enterRule(_localctx, 6, RULE_value);
try {
setState(50);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,3,_ctx) ) {
case 1:
enterOuterAlt(_localctx, 1);
{
setState(48);
match(NAME);
}
break;
case 2:
enterOuterAlt(_localctx, 2);
{
setState(49);
resultSetRule();
}
break;
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ParameterContext extends ParserRuleContext {
public TerminalNode PARAMLIST_NAME() { return getToken(UnifyResultParser.PARAMLIST_NAME, 0); }
public ParameterListContext parameterList() {
return getRuleContext(ParameterListContext.class,0);
}
public ParameterContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_parameter; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).enterParameter(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).exitParameter(this);
}
}
public final ParameterContext parameter() throws RecognitionException {
ParameterContext _localctx = new ParameterContext(_ctx, getState());
enterRule(_localctx, 8, RULE_parameter);
try {
enterOuterAlt(_localctx, 1);
{
setState(52);
match(PARAMLIST_NAME);
setState(53);
parameterList();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class EqualsContext extends ParserRuleContext {
public TerminalNode EQUALS_NAME() { return getToken(UnifyResultParser.EQUALS_NAME, 0); }
public ParameterListContext parameterList() {
return getRuleContext(ParameterListContext.class,0);
}
public EqualsContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_equals; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).enterEquals(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).exitEquals(this);
}
}
public final EqualsContext equals() throws RecognitionException {
EqualsContext _localctx = new EqualsContext(_ctx, getState());
enterRule(_localctx, 10, RULE_equals);
try {
enterOuterAlt(_localctx, 1);
{
setState(55);
match(EQUALS_NAME);
setState(56);
parameterList();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class SmallerContext extends ParserRuleContext {
public TerminalNode SMALLER_NAME() { return getToken(UnifyResultParser.SMALLER_NAME, 0); }
public ParameterListContext parameterList() {
return getRuleContext(ParameterListContext.class,0);
}
public SmallerContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_smaller; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).enterSmaller(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).exitSmaller(this);
}
}
public final SmallerContext smaller() throws RecognitionException {
SmallerContext _localctx = new SmallerContext(_ctx, getState());
enterRule(_localctx, 12, RULE_smaller);
try {
enterOuterAlt(_localctx, 1);
{
setState(58);
match(SMALLER_NAME);
setState(59);
parameterList();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class TypeVarContext extends ParserRuleContext {
public TerminalNode TYPEVAR_NAME() { return getToken(UnifyResultParser.TYPEVAR_NAME, 0); }
public ParameterListContext parameterList() {
return getRuleContext(ParameterListContext.class,0);
}
public TypeVarContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_typeVar; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).enterTypeVar(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).exitTypeVar(this);
}
}
public final TypeVarContext typeVar() throws RecognitionException {
TypeVarContext _localctx = new TypeVarContext(_ctx, getState());
enterRule(_localctx, 14, RULE_typeVar);
try {
enterOuterAlt(_localctx, 1);
{
setState(61);
match(TYPEVAR_NAME);
setState(62);
parameterList();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class TypeContext extends ParserRuleContext {
public TerminalNode TYPE_NAME() { return getToken(UnifyResultParser.TYPE_NAME, 0); }
public ParameterListContext parameterList() {
return getRuleContext(ParameterListContext.class,0);
}
public TypeContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_type; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).enterType(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).exitType(this);
}
}
public final TypeContext type() throws RecognitionException {
TypeContext _localctx = new TypeContext(_ctx, getState());
enterRule(_localctx, 16, RULE_type);
try {
enterOuterAlt(_localctx, 1);
{
setState(64);
match(TYPE_NAME);
setState(65);
parameterList();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class OtherRuleContext extends ParserRuleContext {
public TerminalNode NAME() { return getToken(UnifyResultParser.NAME, 0); }
public ParameterListContext parameterList() {
return getRuleContext(ParameterListContext.class,0);
}
public OtherRuleContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_otherRule; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).enterOtherRule(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof UnifyResultListener ) ((UnifyResultListener)listener).exitOtherRule(this);
}
}
public final OtherRuleContext otherRule() throws RecognitionException {
OtherRuleContext _localctx = new OtherRuleContext(_ctx, getState());
enterRule(_localctx, 18, RULE_otherRule);
try {
enterOuterAlt(_localctx, 1);
{
setState(67);
match(NAME);
setState(68);
parameterList();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\17I\4\2\t\2\4\3\t"+
"\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\3"+
"\2\3\2\3\2\3\2\7\2\33\n\2\f\2\16\2\36\13\2\3\3\3\3\3\3\3\3\3\3\3\3\5\3"+
"&\n\3\3\4\3\4\3\4\3\4\7\4,\n\4\f\4\16\4/\13\4\3\4\3\4\3\5\3\5\5\5\65\n"+
"\5\3\6\3\6\3\6\3\7\3\7\3\7\3\b\3\b\3\b\3\t\3\t\3\t\3\n\3\n\3\n\3\13\3"+
"\13\3\13\3\13\2\2\f\2\4\6\b\n\f\16\20\22\24\2\2\2F\2\26\3\2\2\2\4%\3\2"+
"\2\2\6\'\3\2\2\2\b\64\3\2\2\2\n\66\3\2\2\2\f9\3\2\2\2\16<\3\2\2\2\20?"+
"\3\2\2\2\22B\3\2\2\2\24E\3\2\2\2\26\34\7\3\2\2\27\30\5\4\3\2\30\31\7\4"+
"\2\2\31\33\3\2\2\2\32\27\3\2\2\2\33\36\3\2\2\2\34\32\3\2\2\2\34\35\3\2"+
"\2\2\35\3\3\2\2\2\36\34\3\2\2\2\37&\5\n\6\2 &\5\f\7\2!&\5\16\b\2\"&\5"+
"\20\t\2#&\5\22\n\2$&\5\24\13\2%\37\3\2\2\2% \3\2\2\2%!\3\2\2\2%\"\3\2"+
"\2\2%#\3\2\2\2%$\3\2\2\2&\5\3\2\2\2\'(\7\5\2\2(-\5\b\5\2)*\7\6\2\2*,\5"+
"\b\5\2+)\3\2\2\2,/\3\2\2\2-+\3\2\2\2-.\3\2\2\2.\60\3\2\2\2/-\3\2\2\2\60"+
"\61\7\7\2\2\61\7\3\2\2\2\62\65\7\r\2\2\63\65\5\4\3\2\64\62\3\2\2\2\64"+
"\63\3\2\2\2\65\t\3\2\2\2\66\67\7\b\2\2\678\5\6\4\28\13\3\2\2\29:\7\t\2"+
"\2:;\5\6\4\2;\r\3\2\2\2<=\7\n\2\2=>\5\6\4\2>\17\3\2\2\2?@\7\13\2\2@A\5"+
"\6\4\2A\21\3\2\2\2BC\7\f\2\2CD\5\6\4\2D\23\3\2\2\2EF\7\r\2\2FG\5\6\4\2"+
"G\25\3\2\2\2\6\34%-\64";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}

@ -1,7 +0,0 @@
package de.dhbwstuttgart.sat.asp.parser.model;
public class ParsedASPStatement {
public ParsedASPStatement(String statement){
}
}

@ -0,0 +1,12 @@
package de.dhbwstuttgart.sat.asp.parser.model;
import java.util.List;
public class ParsedType {
public final String name;
public final String params;
public ParsedType(String name, String params){
this.name = name;
this.params = params;
}
}

@ -0,0 +1,127 @@
package de.dhbwstuttgart.sat.asp.writer;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator;
import de.dhbwstuttgart.sat.asp.ASPStringConverter;
import de.dhbwstuttgart.sat.asp.model.ASPRule;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import java.util.*;
public class ASPFactory implements TypeVisitor<String>{
public static String generateASP(ConstraintSet<Pair> constraints, Collection<ClassOrInterface> fcClasses) throws ClassNotFoundException{
ASPFactory factory = new ASPFactory();
factory.convertFC(fcClasses);
List<Constraint<Pair>> constraints1 = constraints.cartesianProduct().iterator().next();
for(Constraint<Pair> constraint : constraints1){
for(Pair p : constraint){
factory.convertPair(p);
}
}
return factory.writer.getASPFile();
}
ASPWriter writer = new ASPWriter();
boolean isFCType = false;
private void convertFC(Collection<ClassOrInterface> classes) throws ClassNotFoundException {
Set<Pair> fc = FCGenerator.toFC(classes);
isFCType = true;
for(Pair fcp : fc){
convertPair(fcp);
}
isFCType = false;
}
private void convertPair(Pair p){
String ls = p.TA1.acceptTV(this);
String rs = p.TA2.acceptTV(this);
ASPStatement pairStmt = null;
if(p.GetOperator().equals(PairOperator.SMALLERDOT)){
pairStmt = makeStatement(ASPRule.ASP_PAIR_SMALLER_DOT_NAME.toString(), ls, rs);
}else if(p.GetOperator().equals(PairOperator.EQUALSDOT)){
pairStmt = makeStatement(ASPRule.ASP_PAIR_EQUALS_NAME.toString(), ls, rs);
}else if(p.GetOperator().equals(PairOperator.SMALLER)){
pairStmt = makeStatement(ASPRule.ASP_PAIR_SMALLER_NAME.toString(), ls, rs);
}else throw new NotImplementedException();
writer.add(pairStmt);
}
private ASPStatement makeStatement(String rule, String... params){
String stmt = rule + "(";
for(String param : params){
stmt += param + ",";
}
stmt = stmt.substring(0,stmt.length()-1);
stmt += ")";
return new ASPStatement(stmt);
}
private String convertParameterlist(List<String> pointers){
String pointer = ASPStringConverter.toConstant(NameGenerator.makeNewName());
Iterator<String> it = pointers.iterator();
String p = pointer;
if(!it.hasNext()){
return ASPRule.ASP_PARAMLIST_END_POINTER.toString();
}
while (it.hasNext()){
ASPStatement stmt;
String type = it.next();
String nextP = ASPStringConverter.toConstant(NameGenerator.makeNewName());
if(it.hasNext()){
stmt = makeStatement(ASPRule.ASP_PARAMLIST_NAME.toString(), p, type, nextP);
}else{
stmt = makeStatement(ASPRule.ASP_PARAMLIST_NAME.toString(), p, type,
ASPRule.ASP_PARAMLIST_END_POINTER.toString());
}
p = nextP;
writer.add(stmt);
}
return pointer;
}
@Override
public String visit(RefType refType) {
String pointer = ASPStringConverter.toConstant(NameGenerator.makeNewName());
List<String> params = new ArrayList<>();
for(RefTypeOrTPHOrWildcardOrGeneric param : refType.getParaList()){
params.add(param.acceptTV(this));
}
String typeName = ASPStringConverter.toConstant(refType.getName());
String ruleName = isFCType?ASPRule.ASP_FCTYPE.toString():ASPRule.ASP_TYPE.toString();
ASPStatement stmt = makeStatement(ruleName, pointer, typeName, convertParameterlist(params));
writer.add(stmt);
return pointer;
}
@Override
public String visit(SuperWildcardType superWildcardType) {
throw new NotImplementedException();
}
@Override
public String visit(TypePlaceholder typePlaceholder) {
String name = ASPStringConverter.toConstant(typePlaceholder.getName());
ASPStatement stmt = makeStatement(ASPRule.ASP_TYPE_VAR.toString(), name);
writer.add(stmt);
return name;
}
@Override
public String visit(ExtendsWildcardType extendsWildcardType) {
throw new NotImplementedException();
}
@Override
public String visit(GenericRefType genericRefType) {
throw new NotImplementedException();
}
}

@ -0,0 +1,264 @@
package de.dhbwstuttgart.sat.asp.writer;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator;
import de.dhbwstuttgart.sat.asp.ASPStringConverter;
import de.dhbwstuttgart.sat.asp.model.ASPGencayRule;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import java.util.*;
public class ASPGencayFactory implements TypeVisitor<String> {
/* TODO:
* Alle TPHs müssen als var(tph) definiert sein
* Wenn es eine Variable ist, dann direkt in die type-Regel schreiben: type(p, type, tph)
* Für die FCTypen eindeutige Namen für die pph-Regeln
* (ergibt sich von selbst, weil man einfach den Namen der TPH in der FC verwenden kann)
* paramOrder wird benötigt!
* Nur bei parameterlisten > 1
* paramOrder(paralistPointer, parameter, num)
* (ähnlich meiner paramNum)
* Trennung von FC und Eq:
* sub -> type -> param
* ...Eq -> typeEq -> paramEq
* type..(_,_,_p): p kann sein:
* 1. Variable
* 2. ParameterPointer
* 3. null
*/
ASPWriter writer = new ASPWriter();
boolean isFCType = false;
private static List<ASPStatement> generateVar(ConstraintSet<Pair> constraints){
List<ASPStatement> ret = new ArrayList<>();
for(TypePlaceholder tph : getInvolvedTPHS(constraints)){
ret.add(makeStatement(ASPGencayRule.ASP_TYPE_VAR.toString(),
ASPStringConverter.toConstant(tph.getName())));
}
return ret;
}
protected static Collection<TypePlaceholder> getInvolvedTPHS(ConstraintSet<Pair> toTest) {
List<TypePlaceholder> ret = new ArrayList<>();
toTest.map((Pair p)-> {
ret.addAll(p.TA1.acceptTV(new TPHExtractor()));
ret.addAll(p.TA2.acceptTV(new TPHExtractor()));
return p;
});
return ret;
}
public static String generateASP(ConstraintSet<Pair> constraints, Collection<ClassOrInterface> fcClasses) throws ClassNotFoundException{
ASPGencayFactory factory = new ASPGencayFactory();
factory.convertFC(fcClasses);
List<Constraint<Pair>> constraints1 = constraints.cartesianProduct().iterator().next();
for(Constraint<Pair> constraint : constraints1){
for(Pair p : constraint){
factory.convertPair(p);
}
}
factory.writer.addAll(generateVar(constraints));
return factory.writer.getASPFile();
}
private void convertFC(Collection<ClassOrInterface> classes) throws ClassNotFoundException {
Set<Pair> fc = FCGenerator.toFC(classes);
isFCType = true;
for(Pair fcp : fc){
generateTheta((RefType) fcp.TA1);
generateTheta((RefType) fcp.TA2);
convertPair(fcp);
}
isFCType = false;
}
private void generateTheta(RefType t){
String rule = "theta"+t.getParaList().size() ;
String name = ASPStringConverter.toConstant(t.getName());
writer.add(makeStatement(rule, name));
}
private void convertPair(Pair p){
String ls = p.TA1.acceptTV(this);
String rs = p.TA2.acceptTV(this);
ASPStatement pairStmt = null;
if(p.GetOperator().equals(PairOperator.SMALLERDOT)){
pairStmt = makeStatement(ASPGencayRule.ASP_PAIR_SMALLER_DOT_NAME.toString(), ls, rs);
}else if(p.GetOperator().equals(PairOperator.EQUALSDOT)){
pairStmt = makeStatement(ASPGencayRule.ASP_PAIR_EQUALS_NAME.toString(), ls, rs);
}else if(p.GetOperator().equals(PairOperator.SMALLER)){
pairStmt = makeStatement(ASPGencayRule.ASP_PAIR_SMALLER_NAME.toString(), ls, rs);
}else throw new NotImplementedException();
writer.add(pairStmt);
}
private static ASPStatement makeStatement(String rule, String... params){
String stmt = rule + "(";
for(String param : params){
stmt += param + ",";
}
stmt = stmt.substring(0,stmt.length()-1);
stmt += ")";
return new ASPStatement(stmt);
}
private String convertParameterlist(List<String> pointers){
//if(pointers.size()==1)return pointers.get(0);
String pointer = ASPStringConverter.toConstant(NameGenerator.makeNewName());
Iterator<String> it = pointers.iterator();
String p = pointer;
String paramname = ASPGencayRule.ASP_PARAMLIST_NAME.toString();
if(this.isFCType)paramname = ASPGencayRule.ASP_FC_PARAMLIST_NAME.toString();
if(!it.hasNext()){
return ASPGencayRule.ASP_PARAMLIST_END_POINTER.toString();
}
while (it.hasNext()){
ASPStatement stmt;
String type = it.next();
String nextP = ASPStringConverter.toConstant(NameGenerator.makeNewName());
if(it.hasNext()){
stmt = makeStatement(paramname, p, type, nextP);
}else{
stmt = makeStatement(paramname, p, type,
ASPGencayRule.ASP_PARAMLIST_END_POINTER.toString());
}
p = nextP;
writer.add(stmt);
}
return pointer;
}
//Wird zum erstellen der pph(..) Regeln gebraucht
private String currentFCTypePointer = "";
@Override
public String visit(RefType refType) {
String pointer = ASPStringConverter.toConstant(NameGenerator.makeNewName());
currentFCTypePointer = pointer;
String paramPointer = ASPGencayRule.ASP_PARAMLIST_END_POINTER.toString();
if(refType.getParaList().size() == 1 ){
if(refType.getParaList().get(0) instanceof TypePlaceholder){
TypePlaceholder typePlaceholder = (TypePlaceholder) refType.getParaList().get(0);
paramPointer = typePlaceholder.acceptTV(this);
}
}else{
List<String> params = null;
params = generateParameter(refType);
params.remove(0);
paramPointer = convertParameterlist(params);
if(refType.getParaList().size()>1){
//paramOrder generieren:
for(String param : params) {
ASPStatement pOstmt = makeStatement(ASPGencayRule.ASP_PARAMLIST_ORDER.toString(),
paramPointer, param);
writer.add(pOstmt);
}
}
}
String typeName = ASPStringConverter.toConstant(refType.getName());
String ruleName = isFCType? ASPGencayRule.ASP_FCTYPE.toString(): ASPGencayRule.ASP_TYPE.toString();
ASPStatement stmt = makeStatement(ruleName, pointer, typeName, paramPointer);
writer.add(stmt);
return pointer;
/*
String pointer = ASPStringConverter.toConstant(NameGenerator.makeNewName());
List<String> params = null;
params = generateParameter(refType);
params.remove(0); //Das erste ist der eigentliche Typ kein parameter
String typeName = ASPStringConverter.toConstant(refType.getName());
String ruleName = isFCType? ASPGencayRule.ASP_FCTYPE.toString(): ASPGencayRule.ASP_TYPE.toString();
ASPStatement stmt = makeStatement(ruleName, pointer, typeName, convertParameterlist(params));
writer.add(stmt);
return pointer;
*/
}
/**
* Erstellt die Parameterliste, wobei type auch schon als Parameter betrachtet wird.
* Die RefTypes werden nicht zu extra type-Regeln umgewandelt. Es wird nur ihr Name als Konstante benutzt
* Das funktioniert, weil nacher das ParamOrder zuteilt, welche Typen zusammenhängen.
* Diese funktion nur verwenden, wenn auch ein paramOrder generiert wird
*/
private List<String> generateParameter(RefType type){
List<String> ret = new ArrayList<>();
ret.add(ASPStringConverter.toConstant(type.getName()));
for(RefTypeOrTPHOrWildcardOrGeneric param : type.getParaList()){
if(param instanceof RefType){
ret.addAll(generateParameter((RefType) param));
}else if(param instanceof TypePlaceholder){
ret.add(param.acceptTV(this));
}else throw new NotImplementedException();
}
return ret;
}
@Override
public String visit(SuperWildcardType superWildcardType) {
throw new NotImplementedException();
}
@Override
public String visit(TypePlaceholder typePlaceholder) {
String name = ASPStringConverter.toConstant(typePlaceholder.getName());
ASPStatement stmt = null;
if(isFCType){
stmt = makeStatement(ASPGencayRule.ASP_GENERIC_VAR.toString(),
currentFCTypePointer, name);
} else {
stmt = makeStatement(ASPGencayRule.ASP_TYPE_VAR.toString(), name);
}
writer.add(stmt);
return name;
}
@Override
public String visit(ExtendsWildcardType extendsWildcardType) {
throw new NotImplementedException();
}
@Override
public String visit(GenericRefType genericRefType) {
throw new NotImplementedException();
}
private static class TPHExtractor implements TypeVisitor<List<TypePlaceholder>>{
@Override
public List<TypePlaceholder> visit(RefType refType) {
ArrayList<TypePlaceholder> ret = new ArrayList<>();
for(RefTypeOrTPHOrWildcardOrGeneric param : refType.getParaList()){
ret.addAll(param.acceptTV(this));
}
return ret;
}
@Override
public List<TypePlaceholder> visit(SuperWildcardType superWildcardType) {
return superWildcardType.getInnerType().acceptTV(this);
}
@Override
public List<TypePlaceholder> visit(TypePlaceholder typePlaceholder) {
return Arrays.asList(typePlaceholder);
}
@Override
public List<TypePlaceholder> visit(ExtendsWildcardType extendsWildcardType) {
return extendsWildcardType.getInnerType().acceptTV(this);
}
@Override
public List<TypePlaceholder> visit(GenericRefType genericRefType) {
return new ArrayList<>();
}
}
}

@ -1,111 +0,0 @@
package de.dhbwstuttgart.sat.asp.writer;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.sat.asp.writer.model.*;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ASPGenerator {
ASPWriter writer = new ASPWriter();
private final String asp;
public ASPGenerator(ConstraintSet<Pair> constraints, Collection<ClassOrInterface> fcClasses){
List<Constraint<Pair>> constraints1 = constraints.cartesianProduct().iterator().next();
List<Pair> constraintPairs = new ArrayList<>();
for(Constraint<Pair> constraint : constraints1){
System.out.println(UnifyTypeFactory.convert(constraint));
constraintPairs.addAll(constraint);
}
asp = toASP(constraintPairs, fcClasses);
}
public String getASP(){
return asp;
}
private String toASP(List<Pair> constraintSet, Collection<ClassOrInterface> fcClasses){
TypeConverter converter = new TypeConverter();
for(ClassOrInterface cl : fcClasses){
ASPRefType superClass = (ASPRefType) cl.getSuperClass().acceptTV(converter);
ASPPairSmaller fcEntry = new ASPPairSmaller(new ASPFCType(convert(cl)), new ASPFCType(superClass), writer);
writer.add(new ASPStatement(fcEntry.toASP()));
}
for(Pair cons : constraintSet){
writer.add(new ASPStatement(convert(cons).toASP()));
}
return writer.getASPFile();
}
private ASPPair convert(Pair pair){
TypeConverter converter = new TypeConverter();
ASPType ls = pair.TA1.acceptTV(converter);
ASPType rs = pair.TA2.acceptTV(converter);
if(pair.OperatorEqual()){
return new ASPPairEquals(ls, rs,writer);
}else if(pair.OperatorSmallerDot()){
return new ASPPairSmallerDot(ls, rs, writer);
}else throw new NotImplementedException();
}
private ASPRefType convert(ClassOrInterface cl){
List<ASPType> paramList = new ArrayList<>();
for(GenericTypeVar gtv : cl.getGenerics()){
paramList.add(new ASPGenericType(toConstant(gtv.getName())));
}
ASPParameterList params = new ASPParameterList(paramList, writer);
return new ASPRefType(toConstant(cl.getClassName()), params);
}
public static String toConstant(JavaClassName name){
return toConstant(name.toString().replace(".", "_"));
}
public static String toConstant(String name){
return "c" + name.toString().replace(".", "_");
}
private class TypeConverter implements TypeVisitor<ASPType>{
@Override
public ASPType visit(RefType type) {
List<ASPType> paramList = new ArrayList<>();
for(RefTypeOrTPHOrWildcardOrGeneric gtv : type.getParaList()){
paramList.add(gtv.acceptTV(this));
}
ASPParameterList params = new ASPParameterList(paramList, writer);
return new ASPRefType(toConstant(type.getName()), params);
}
@Override
public ASPType visit(SuperWildcardType superWildcardType) {
throw new NotImplementedException();
}
@Override
public ASPType visit(TypePlaceholder typePlaceholder) {
return new ASPTypeVar(toConstant(typePlaceholder.getName()));
}
@Override
public ASPType visit(ExtendsWildcardType extendsWildcardType) {
throw new NotImplementedException();
}
@Override
public ASPType visit(GenericRefType genericRefType) {
return new ASPRefType(toConstant(genericRefType.getName()),
new ASPParameterList(new ArrayList<>(), writer));
}
}
}

@ -1,4 +1,4 @@
package de.dhbwstuttgart.sat.asp.writer.model;
package de.dhbwstuttgart.sat.asp.writer;
public class ASPStatement {
private final String stmt;

@ -1,8 +1,8 @@
package de.dhbwstuttgart.sat.asp.writer;
import de.dhbwstuttgart.sat.asp.writer.model.ASPStatement;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
public class ASPWriter {
@ -19,4 +19,8 @@ public class ASPWriter {
}
return ret;
}
public void addAll(Collection<ASPStatement> aspStatements) {
content.addAll(aspStatements);
}
}

@ -1,14 +0,0 @@
package de.dhbwstuttgart.sat.asp.writer.model;
import de.dhbwstuttgart.sat.asp.model.ASPRule;
import de.dhbwstuttgart.sat.asp.writer.ASPWriter;
public class ASPFCType extends ASPRefType {
public ASPFCType(ASPRefType refType){
super(refType.name, refType.params);
}
public String toString(){
return ASPRule.ASP_FCTYPE + "(" + name +"," + params.name + ")";
}
}

@ -1,25 +0,0 @@
package de.dhbwstuttgart.sat.asp.writer.model;
import de.dhbwstuttgart.sat.asp.model.ASPRule;
public class ASPGenericType implements ASPType{
private final String name;
public ASPGenericType(String name){
this.name = name;
}
public String toString(){
return ASPRule.ASP_GENERIC_TYPE_NAME + "(" + name + ")";
}
@Override
public String toASP() {
return toString();
}
@Override
public String getPointer() {
return name;
}
}

@ -1,25 +0,0 @@
package de.dhbwstuttgart.sat.asp.writer.model;
import de.dhbwstuttgart.sat.asp.writer.ASPWriter;
public abstract class ASPPair {
public final ASPType leftSide;
public final ASPType rightSide;
public ASPPair(ASPType ls, ASPType rs, ASPWriter writer){
this.leftSide = ls;
this.rightSide = rs;
writer.add(new ASPStatement(ls.toASP()));
writer.add(new ASPStatement(rs.toASP()));
}
public String toASP(){
return this.getRuleName() + "(" + leftSide.getPointer() + ","+ rightSide.getPointer() + ")";
}
public String toString(){
return toASP();
}
protected abstract String getRuleName();
}

@ -1,15 +0,0 @@
package de.dhbwstuttgart.sat.asp.writer.model;
import de.dhbwstuttgart.sat.asp.model.ASPRule;
import de.dhbwstuttgart.sat.asp.writer.ASPWriter;
public class ASPPairEquals extends ASPPair{
public ASPPairEquals(ASPType ls, ASPType rs, ASPWriter writer){
super(ls, rs, writer);
}
@Override
protected String getRuleName() {
return ASPRule.ASP_PAIR_EQUALS_NAME.toString();
}
}

@ -1,17 +0,0 @@
package de.dhbwstuttgart.sat.asp.writer.model;
import de.dhbwstuttgart.sat.asp.model.ASPRule;
import de.dhbwstuttgart.sat.asp.writer.ASPWriter;
import java.util.Map;
public class ASPPairSmaller extends ASPPair{
public ASPPairSmaller(ASPFCType ls, ASPFCType rs, ASPWriter writer){
super(ls, rs, writer);
}
@Override
protected String getRuleName() {
return ASPRule.ASP_PAIR_SMALLER_NAME.toString();
}
}

@ -1,15 +0,0 @@
package de.dhbwstuttgart.sat.asp.writer.model;
import de.dhbwstuttgart.sat.asp.model.ASPRule;
import de.dhbwstuttgart.sat.asp.writer.ASPWriter;
public class ASPPairSmallerDot extends ASPPair{
public ASPPairSmallerDot(ASPType ls, ASPType rs, ASPWriter writer){
super(ls, rs, writer);
}
@Override
protected String getRuleName() {
return ASPRule.ASP_PAIR_SMALLER_DOT_NAME.toString();
}
}

@ -1,45 +0,0 @@
package de.dhbwstuttgart.sat.asp.writer.model;
import de.dhbwstuttgart.sat.asp.model.ASPRule;
import de.dhbwstuttgart.sat.asp.writer.ASPGenerator;
import de.dhbwstuttgart.sat.asp.writer.ASPWriter;
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
import java.util.Iterator;
import java.util.List;
public class ASPParameterList {
public final String name;
private final List<ASPType> types;
public ASPParameterList(List<ASPType> types, ASPWriter writer){
int paramNum = 0;
this.types = types;
if(types.size() == 0){
name = ASPRule.ASP_PARAMLIST_END_POINTER.toString();
}else{
name = newName();
String nextPointer = name;
Iterator<ASPType> it = types.iterator();
while(it.hasNext()){
ASPType t = it.next();
String param = nextPointer + "," + t.toString() + ",";
nextPointer = newName();
if(! it.hasNext())nextPointer = ASPRule.ASP_PARAMLIST_END_POINTER.toString();
param += nextPointer;
writer.add(new ASPStatement(ASPRule.ASP_PARAMLIST_NAME + "(" + param + ")"));
writer.add(new ASPStatement(ASPRule.ASP_PARAMLISTNUMERATION_NAME + "(" + name + "," +t + "," + paramNum + ")"));
paramNum++;
//paramDefinitions.add(new ASPStatement(ASP_PARAMLIST_NAME + "(" + param + ")"));
}
}
}
private String newName() {
return ASPGenerator.toConstant(NameGenerator.makeNewName());
}
public String toString(){
return name;
}
}

@ -1,31 +0,0 @@
package de.dhbwstuttgart.sat.asp.writer.model;
import de.dhbwstuttgart.sat.asp.model.ASPRule;
public class ASPRefType implements ASPType {
protected final ASPParameterList params;
protected final String name;
public ASPRefType(String name, ASPParameterList params){
this.name = name;
this.params = params;
}
public ASPParameterList getParams() {
return params;
}
public String toString(){
return ASPRule.ASP_TYPE + "(" + name +"," + params.name + ")";
}
@Override
public String toASP() {
return toString();
}
@Override
public String getPointer() {
return name;
}
}

@ -1,7 +0,0 @@
package de.dhbwstuttgart.sat.asp.writer.model;
public interface ASPType {
String toASP();
String getPointer();
}

@ -1,24 +0,0 @@
package de.dhbwstuttgart.sat.asp.writer.model;
public class ASPTypeVar implements ASPType{
private final String name;
public ASPTypeVar(String name){
this.name = name;
}
@Override
public String toString() {
return "typeVar("+ name +")";
}
@Override
public String toASP() {
return toString();
}
@Override
public String getPointer() {
return name;
}
}

@ -13,6 +13,7 @@ import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation;
import org.antlr.v4.runtime.Token;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
@ -26,11 +27,11 @@ public class ClassOrInterface extends SyntaxTreeNode implements TypeScope{
private GenericDeclarationList genericClassParameters;
private RefType superClass;
protected boolean isInterface;
private List<? extends RefTypeOrTPHOrWildcardOrGeneric> implementedInterfaces;
private List<RefType> implementedInterfaces;
private List<Constructor> constructors;
public ClassOrInterface(int modifiers, JavaClassName name, List<Field> fielddecl, List<Method> methods, List<Constructor> constructors, GenericDeclarationList genericClassParameters,
RefType superClass, Boolean isInterface, List<? extends RefTypeOrTPHOrWildcardOrGeneric> implementedInterfaces, Token offset){
RefType superClass, Boolean isInterface, List<RefType> implementedInterfaces, Token offset){
super(offset);
this.modifiers = modifiers;
this.name = name;
@ -101,4 +102,12 @@ public class ClassOrInterface extends SyntaxTreeNode implements TypeScope{
public void accept(ASTVisitor visitor) {
visitor.visit(this);
}
public Collection<RefType> getSuperInterfaces() {
return implementedInterfaces;
}
public String toString() {
return this.name.toString() + this.genericClassParameters.toString();
}
}

@ -31,4 +31,8 @@ public class GenericDeclarationList extends SyntaxTreeNode implements Iterable<G
public void accept(ASTVisitor visitor) {
visitor.visit(this);
}
public String toString() {
return this.gtvs.toString();
}
}

@ -1,7 +1,5 @@
package de.dhbwstuttgart.syntaxtree;
import de.dhbwstuttgart.parser.scope.GenericTypeName;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import org.antlr.v4.runtime.Token;
@ -26,9 +24,9 @@ public class GenericTypeVar extends SyntaxTreeNode
*/
List<? extends RefTypeOrTPHOrWildcardOrGeneric> bounds=new ArrayList<RefTypeOrTPHOrWildcardOrGeneric>();
private Token endOffset;
private GenericTypeName name;
private String name;
public GenericTypeVar(GenericTypeName s, List<? extends RefTypeOrTPHOrWildcardOrGeneric> bounds, Token offset, Token endOffset)
public GenericTypeVar(String s, List<? extends RefTypeOrTPHOrWildcardOrGeneric> bounds, Token offset, Token endOffset)
{
super(offset);
name = s;
@ -50,18 +48,15 @@ public class GenericTypeVar extends SyntaxTreeNode
return "BoGTV " + this.name;
}
public GenericTypeName getName() {
return name;
}
public String getParsedName(){
public String getName(){
return name.toString();
}
/*
public JavaClassName definingClass(){
return name.getParentClass();
}
*/
@Override
public void accept(ASTVisitor visitor) {
visitor.visit(this);

@ -8,7 +8,6 @@ import java.util.List;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.GenericContext;
import de.dhbwstuttgart.parser.scope.GenericTypeName;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
import de.dhbwstuttgart.syntaxtree.Field;
@ -43,19 +42,22 @@ public class ASTFactory {
}
int modifier = jreClass.getModifiers();
boolean isInterface = jreClass.isInterface();
//see: https://stackoverflow.com/questions/9934774/getting-generic-parameter-from-supertype-class
ParameterizedType parameterSuperClass = null;
Type tempSuperClass = jreClass.getGenericSuperclass();
if(tempSuperClass != null && tempSuperClass instanceof ParameterizedType)
parameterSuperClass = (ParameterizedType) tempSuperClass;
java.lang.Class superjreClass = jreClass.getSuperclass();
RefType superClass;
if(superjreClass != null){
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
for(TypeVariable tv : superjreClass.getTypeParameters()){
params.add(new GenericRefType(new GenericTypeName(new GenericContext( name, null),tv.getName()), new NullToken()));
}
superClass = new RefType(new JavaClassName(superjreClass.getName()), params, new NullToken());
if(parameterSuperClass != null){
superClass = (RefType) convertType(parameterSuperClass);
}else if(superjreClass != null){
superClass = (RefType) convertType(superjreClass);
}else{//Jede Klasse und jedes Interface erbt von Object: (auch Object selbst!)
superClass = (RefType) createType(java.lang.Object.class, name, "");
}
List<RefType> implementedInterfaces = new ArrayList<>();
for(java.lang.Class jreInterface : jreClass.getInterfaces()){
for(Type jreInterface : jreClass.getGenericInterfaces()){
implementedInterfaces.add((RefType) createType(jreInterface, name, ""));
}
GenericDeclarationList genericDeclarationList = createGenerics(jreClass.getTypeParameters(), jreClass, null);
@ -65,18 +67,46 @@ public class ASTFactory {
return new ClassOrInterface(modifier, name, felder, methoden, konstruktoren, genericDeclarationList, superClass,isInterface, implementedInterfaces, offset);
}
private static RefTypeOrTPHOrWildcardOrGeneric convertType(Type type){
if(type instanceof ParameterizedType){
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
for(Type paramType : ((ParameterizedType)type).getActualTypeArguments()){
params.add(convertType(paramType));
}
JavaClassName name = new JavaClassName(((ParameterizedType) type).getRawType().getTypeName());
return new RefType(name, params, new NullToken());
}else if(type instanceof TypeVariable){
return new GenericRefType(((TypeVariable) type).getName(), new NullToken());
}else if(type instanceof Class){
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
Class paramClass = (Class) type;
for(TypeVariable tv : paramClass.getTypeParameters()){
params.add(new GenericRefType(tv.getName(), new NullToken()));
}
JavaClassName name = new JavaClassName(paramClass.getName());
return new RefType(name, params, new NullToken());
}else throw new NotImplementedException();
}
private static Field createField(java.lang.reflect.Field field, JavaClassName jreClass) {
return new Field(field.getName(), createType(field.getType(), jreClass, null), field.getModifiers(), new NullToken());
}
//private static RefType createType(Class classType) {
// return createClass(classType).getType();
//}
private static de.dhbwstuttgart.syntaxtree.Constructor createConstructor(Constructor constructor, Class inClass) {
String name = constructor.getName();
RefTypeOrTPHOrWildcardOrGeneric returnType = createType(inClass, new JavaClassName(inClass.getName()), name);
Parameter[] jreParams = constructor.getParameters();
Type[] jreGenericParams = constructor.getGenericParameterTypes();
List<FormalParameter> params = new ArrayList<>();
for(Parameter jreParam : jreParams){
RefTypeOrTPHOrWildcardOrGeneric paramType = createType(jreParam.getType(),new JavaClassName(inClass.getName()), name);
params.add(new FormalParameter(jreParam.getName(),paramType, new NullToken()));
int i = 0;
for(Type jreParam : jreGenericParams){
RefTypeOrTPHOrWildcardOrGeneric paramType = createType(jreParam,new JavaClassName(inClass.getName()), name);
params.add(new FormalParameter(jreParams[i].getName(),paramType, new NullToken()));
i++;
}
ParameterList parameterList = new ParameterList(params, new NullToken());
Block block = new Block(new ArrayList<Statement>(), new NullToken());
@ -89,21 +119,26 @@ public class ASTFactory {
}
return new de.dhbwstuttgart.syntaxtree.Constructor(modifier, name,returnType, parameterList, block, gtvDeclarations, offset, new ArrayList<>());
}
//private static RefType createType(Class classType) {
// return createClass(classType).getType();
//}
}
public static Method createMethod(java.lang.reflect.Method jreMethod, java.lang.Class inClass){
String name = jreMethod.getName();
RefTypeOrTPHOrWildcardOrGeneric returnType;
returnType = createType(jreMethod.getReturnType(),new JavaClassName(inClass.getName()), name);
Type jreRetType;
if(jreMethod.getGenericReturnType()!=null){
jreRetType = jreMethod.getGenericReturnType();
}else{
jreRetType = jreMethod.getReturnType();
}
returnType = createType(jreRetType,new JavaClassName(inClass.getName()), name);
Parameter[] jreParams = jreMethod.getParameters();
Type[] jreGenericParams = jreMethod.getGenericParameterTypes();
List<FormalParameter> params = new ArrayList<>();
for(Parameter jreParam : jreParams){
RefTypeOrTPHOrWildcardOrGeneric paramType = createType(jreParam.getType(),new JavaClassName(inClass.getName()), name);
params.add(new FormalParameter(jreParam.getName(),paramType, new NullToken()));
int i = 0;
for(Type jreParam : jreGenericParams){
RefTypeOrTPHOrWildcardOrGeneric paramType = createType(jreParam,new JavaClassName(inClass.getName()), name);
params.add(new FormalParameter(jreParams[i].getName(),paramType, new NullToken()));
i++;
}
ParameterList parameterList = new ParameterList(params, new NullToken());
Block block = new Block(new ArrayList<Statement>(), new NullToken());
@ -153,9 +188,7 @@ public class ASTFactory {
}else{
if(type instanceof TypeVariable){
//GTVDeclarationContext via "(TypeVariable) type).getGenericDeclaration()"
return new GenericRefType(
new GenericTypeName(new GenericContext(parentClass, parentMethod),type.getTypeName()),
new NullToken());
return new GenericRefType(type.getTypeName(), new NullToken());
}
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
if(type instanceof ParameterizedType){
@ -163,7 +196,12 @@ public class ASTFactory {
params.add(createType(t, parentClass, parentMethod));
}
}
RefType ret = new RefType(new JavaClassName(type.getTypeName()), params, new NullToken());
String name = type.getTypeName();
if(name.contains("<")){ //Komischer fix. Type von Generischen Typen kann die Generics im Namen enthalten Type<A>
//Diese entfernen:
name = name.split("<")[0];
}
RefType ret = new RefType(new JavaClassName(name), params, new NullToken());
return ret;
}
}
@ -177,9 +215,7 @@ public class ASTFactory {
genericBounds.add((RefType) createType(bound, parentClass, parentMethod));
}
}
return new de.dhbwstuttgart.syntaxtree.GenericTypeVar(
new GenericTypeName(new GenericContext(parentClass, parentMethod), jreTVName)
, genericBounds, new NullToken(), new NullToken());
return new de.dhbwstuttgart.syntaxtree.GenericTypeVar(jreTVName, genericBounds, new NullToken(), new NullToken());
}
public static ClassOrInterface createObjectClass() {

@ -1,6 +1,8 @@
package de.dhbwstuttgart.syntaxtree.factory;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import de.dhbwstuttgart.exceptions.DebugException;
@ -8,8 +10,9 @@ import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.sat.asp.model.ASPRule;
import de.dhbwstuttgart.sat.asp.parser.ASPParser;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.syntaxtree.type.Void;
import de.dhbwstuttgart.syntaxtree.type.WildcardType;
@ -23,6 +26,8 @@ import de.dhbwstuttgart.typeinference.result.ResultPair;
import de.dhbwstuttgart.typeinference.unify.model.*;
public class UnifyTypeFactory {
private static ArrayList<PlaceholderType> PLACEHOLDERS = new ArrayList<>();
public static FiniteClosure generateFC(List<ClassOrInterface> fromClasses) throws ClassNotFoundException {
/*
@ -35,7 +40,7 @@ public class UnifyTypeFactory {
Generell dürfen sie immer die gleichen Namen haben.
TODO: die transitive Hülle bilden
*/
return new FiniteClosure(FCGenerator.toFC(fromClasses));
return new FiniteClosure(FCGenerator.toUnifyFC(fromClasses));
}
public static UnifyPair generateSmallerPair(UnifyType tl, UnifyType tr){
@ -46,6 +51,10 @@ public class UnifyTypeFactory {
return new UnifyPair(tl, tr, PairOperator.SMALLERDOT);
}
public static UnifyPair generateSmallNotEqualDotPair(UnifyType tl, UnifyType tr){
return new UnifyPair(tl, tr, PairOperator.SMALLERNEQDOT);
}
public static UnifyPair generateEqualDotPair(UnifyType tl, UnifyType tr){
return new UnifyPair(tl, tr, PairOperator.EQUALSDOT);
}
@ -74,6 +83,16 @@ public class UnifyTypeFactory {
}
public static UnifyType convert(RefType t){
//Check if it is a FunN Type:
Pattern p = Pattern.compile("Fun(\\d+)");
Matcher m = p.matcher(t.getName().toString());
boolean b = m.matches();
if(b){
Integer N = Integer.valueOf(m.group(1));
if((N + 1) == t.getParaList().size()){
return convert(new FunN(t.getParaList()));
}
}
UnifyType ret;
if(t.getParaList() != null && t.getParaList().size() > 0){
List<UnifyType> params = new ArrayList<>();
@ -100,7 +119,15 @@ public class UnifyTypeFactory {
}
public static UnifyType convert(TypePlaceholder tph){
return new PlaceholderType(tph.getName());
PlaceholderType ntph = new PlaceholderType(tph.getName());
int in = PLACEHOLDERS.indexOf(ntph);
if (in == -1) {
PLACEHOLDERS.add(ntph);
return ntph;
}
else {
return PLACEHOLDERS.get(in);
}
}
public static UnifyType convert(GenericRefType t){
@ -129,10 +156,17 @@ public class UnifyTypeFactory {
UnifyPair ret = generateSmallerDotPair(UnifyTypeFactory.convert(p.TA1)
, UnifyTypeFactory.convert(p.TA2));
return ret;
}else if(p.GetOperator().equals(PairOperator.EQUALSDOT)){
}else if(p.GetOperator().equals(PairOperator.SMALLERNEQDOT)) {
UnifyPair ret = generateSmallNotEqualDotPair(UnifyTypeFactory.convert(p.TA1)
, UnifyTypeFactory.convert(p.TA2));
return ret;
}else if(p.GetOperator().equals(PairOperator.EQUALSDOT)) {
UnifyPair ret = generateEqualDotPair(UnifyTypeFactory.convert(p.TA1)
, UnifyTypeFactory.convert(p.TA2));
return ret;
}else if(p.GetOperator().equals(PairOperator.SMALLER)){
return generateSmallerPair(UnifyTypeFactory.convert(p.TA1),
UnifyTypeFactory.convert(p.TA2));
}else throw new NotImplementedException();
}
@ -164,7 +198,9 @@ public class UnifyTypeFactory {
}else if(tr instanceof WildcardType){
return new PairTPHequalRefTypeOrWildcardType((TypePlaceholder)tl, (WildcardType) tr);
}else throw new NotImplementedException();
}else throw new NotImplementedException();
}else {
throw new NotImplementedException();
}
}
public static RefTypeOrTPHOrWildcardOrGeneric convert(ReferenceType t, Map<String,TypePlaceholder> tphs) {
@ -174,7 +210,7 @@ public class UnifyTypeFactory {
}
public static RefTypeOrTPHOrWildcardOrGeneric convert(FunNType t, Map<String,TypePlaceholder> tphs) {
RefType ret = new RefType(new JavaClassName(t.getName()), convert(t.getTypeParams(), tphs), new NullToken());
RefType ret = new RefType(new JavaClassName(t.getName()+"$$"), convert(t.getTypeParams(), tphs), new NullToken());
return ret;
}

@ -13,16 +13,17 @@ public class BinaryExpr extends Expression
}
public enum Operator{
ADD,
SUB,
MUL,
AND,
OR,
DIV,
LESSTHAN,
BIGGERTHAN,
LESSEQUAL,
BIGGEREQUAL
ADD, // +
SUB, // -
MUL, // *
MOD, // Modulo Operator %
AND, // &&
OR, // ||
DIV, // /
LESSTHAN, // <
BIGGERTHAN, // >
LESSEQUAL, // <=
BIGGEREQUAL // >=
}
public final Operator operation;

@ -24,7 +24,7 @@ public class FunN extends RefType {
* @return
*/
public FunN(List<RefTypeOrTPHOrWildcardOrGeneric> params) {
super(new JavaClassName("Fun"+params.size()), params, new NullToken());
super(new JavaClassName("Fun"+(params.size())), params, new NullToken());
}
/**

@ -1,25 +1,19 @@
package de.dhbwstuttgart.syntaxtree.type;
import de.dhbwstuttgart.parser.scope.GenericTypeName;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.syntaxtree.ASTVisitor;
import de.dhbwstuttgart.typeinference.result.ResultSetVisitor;
import org.antlr.v4.runtime.Token;
public class GenericRefType extends RefTypeOrTPHOrWildcardOrGeneric
{
private GenericTypeName name;
private String name;
public GenericRefType(GenericTypeName name, Token offset)
public GenericRefType(String name, Token offset)
{
super(offset);
this.name = name;
}
public GenericTypeName getName(){
return name;
}
public String getParsedName(){
return name.toString();
}

@ -30,7 +30,7 @@ public class SuperWildcardType extends WildcardType{
* Beispiel: ? super Integer.
* Integer wird zurückgegeben.
*/
public RefTypeOrTPHOrWildcardOrGeneric get_SuperType()
public RefTypeOrTPHOrWildcardOrGeneric getInnerType()
{
return this.innerType;
}

@ -1,6 +1,5 @@
package de.dhbwstuttgart.syntaxtree.visual;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.statement.*;
@ -171,7 +170,7 @@ public class OutputGenerator implements ASTVisitor{
@Override
public void visit(GenericRefType genericRefType) {
out.append(genericRefType.getName().toString());
out.append(genericRefType.getParsedName().toString());
}
@Override

@ -0,0 +1,34 @@
package de.dhbwstuttgart.syntaxtree.visual;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.typeinference.result.*;
public class ResultSetOutputGenerator extends OutputGenerator implements ResultSetVisitor{
public ResultSetOutputGenerator(StringBuilder out) {
super(out);
}
@Override
public void visit(PairTPHsmallerTPH p) {
print(p, "<");
}
@Override
public void visit(PairTPHequalRefTypeOrWildcardType p) {
print(p, "=.");
}
@Override
public void visit(PairTPHEqualTPH p) {
print(p, "=.");
}
private void print(ResultPair p , String operator){
out.append("(");
p.getLeft().accept((ResultSetVisitor) this);
out.append(" "+operator+" ");
p.getRight().accept((ResultSetVisitor) this);
out.append(")");
}
}

@ -0,0 +1,20 @@
package de.dhbwstuttgart.syntaxtree.visual;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.typeinference.result.ResultPair;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import java.util.Set;
public class ResultSetPrinter {
public static String print(ResultSet toPrint){
StringBuilder output = new StringBuilder();
for(ResultPair p : toPrint.results){
p.accept(new ResultSetOutputGenerator(output));
output.append("\n");
}
return output.toString();
}
}

@ -126,7 +126,7 @@ class TypeToInsertString implements ResultSetVisitor{
@Override
public void visit(GenericRefType genericRefType) {
insert += genericRefType.getName();
insert += genericRefType.getParsedName();
}
@Override

@ -1,5 +1,6 @@
package de.dhbwstuttgart.typeinference.assumptions;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.TypeScope;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
@ -25,7 +26,7 @@ public class FieldAssumption extends Assumption{
}
public RefTypeOrTPHOrWildcardOrGeneric getReceiverType(GenericsResolver resolver) {
return null;
//TODO
throw new NotImplementedException();
}
}

@ -1,8 +1,6 @@
package de.dhbwstuttgart.typeinference.assumptions;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.GenericContext;
import de.dhbwstuttgart.parser.scope.GenericTypeName;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.GenericDeclarationList;
@ -10,33 +8,36 @@ import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
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 org.antlr.v4.runtime.Token;
import java.util.ArrayList;
import java.util.List;
public class FunNClass extends ClassOrInterface {
public FunNClass(List<RefTypeOrTPHOrWildcardOrGeneric> funNParams) {
super(0, new JavaClassName("Fun"+(funNParams.size()-1)), new ArrayList<>(),
public FunNClass(List<GenericRefType> funNParams) {
super(0, new JavaClassName("Fun"+(funNParams.size())), new ArrayList<>(),
createMethods(funNParams), new ArrayList<>(), createGenerics(funNParams),
ASTFactory.createObjectType(), true, new ArrayList<>(), new NullToken());
}
private static GenericDeclarationList createGenerics(List<RefTypeOrTPHOrWildcardOrGeneric> funNParams) {
private static GenericDeclarationList createGenerics(List<GenericRefType> funNParams) {
//PL 2018-06-22: so geaendert, dass generierte Generics den Namen der funParams entsprechen.
List<GenericTypeVar> generics = new ArrayList<>();
for(RefTypeOrTPHOrWildcardOrGeneric param : funNParams){
generics.add(new GenericTypeVar(new GenericTypeName(new GenericContext(
new JavaClassName("Fun"+(funNParams.size()-1)), null), NameGenerator.makeNewName()),
for(GenericRefType param : funNParams){
generics.add(new GenericTypeVar(param.getParsedName(),//NameGenerator.makeNewName(),
new ArrayList<>(), new NullToken(), new NullToken()));
}
return new GenericDeclarationList(generics, new NullToken());
}
private static List<Method> createMethods(List<RefTypeOrTPHOrWildcardOrGeneric> funNParams) {
private static List<Method> createMethods(List<GenericRefType> funNParams) {
return null;
}
}

@ -3,9 +3,7 @@ package de.dhbwstuttgart.typeinference.assumptions;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.ParameterList;
import de.dhbwstuttgart.syntaxtree.TypeScope;
import de.dhbwstuttgart.syntaxtree.statement.Assign;
import de.dhbwstuttgart.syntaxtree.type.FunN;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
@ -14,15 +12,14 @@ import de.dhbwstuttgart.typeinference.constraints.GenericsResolver;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class MethodAssumption extends Assumption{
private ClassOrInterface receiver;
private RefTypeOrTPHOrWildcardOrGeneric retType;
List<RefTypeOrTPHOrWildcardOrGeneric> params;
List<? extends RefTypeOrTPHOrWildcardOrGeneric> params;
public MethodAssumption(ClassOrInterface receiver, RefTypeOrTPHOrWildcardOrGeneric retType,
List<RefTypeOrTPHOrWildcardOrGeneric> params, TypeScope scope){
List<? extends RefTypeOrTPHOrWildcardOrGeneric> params, TypeScope scope){
super(scope);
this.receiver = receiver;
this.retType = retType;
@ -40,7 +37,10 @@ public class MethodAssumption extends Assumption{
return receiver;
}
public RefTypeOrTPHOrWildcardOrGeneric getReturnType() {
public RefTypeOrTPHOrWildcardOrGeneric getReturnType(GenericsResolver resolver) {
if(retType instanceof GenericRefType) {
return resolver.resolve(retType);
}
return retType;
}

@ -11,6 +11,7 @@ public class Pair implements Serializable
public final RefTypeOrTPHOrWildcardOrGeneric TA2;
private PairOperator eOperator = PairOperator.SMALLER;
public Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2 )
{
@ -41,14 +42,16 @@ public class Pair implements Serializable
if( TA2 != null )
strElement2 = TA2.toString();
/* PL ausskommentiert 2018-05-24
if(OperatorEqual())
Operator = "=";
if(OperatorSmaller())
Operator = "<.";
if(OperatorSmallerExtends())
Operator = "<?";
*/
return "\n(" + strElement1 + " " + Operator + " " + strElement2 + ")";
return "\n(" + strElement1 + " " + eOperator.toString() + " " + strElement2 + ")";
/*- Equals: " + bEqual*/
}

@ -9,7 +9,7 @@ public class PairTPHEqualTPH extends ResultPair<TypePlaceholder, TypePlaceholder
}
@Override
public void accept(ResultSetVisitor visitor) {
public void accept(ResultPairVisitor visitor) {
visitor.visit(this);
}
}

@ -18,7 +18,7 @@ public class PairTPHequalRefTypeOrWildcardType extends ResultPair{
}
@Override
public void accept(ResultSetVisitor visitor) {
public void accept(ResultPairVisitor visitor) {
visitor.visit(this);
}
}

@ -17,7 +17,7 @@ public class PairTPHsmallerTPH extends ResultPair{
}
@Override
public void accept(ResultSetVisitor visitor) {
public void accept(ResultPairVisitor visitor) {
visitor.visit(this);
}
}

@ -9,7 +9,7 @@ public abstract class ResultPair<A extends RefTypeOrTPHOrWildcardOrGeneric,B ext
private final A left;
private final B right;
public abstract void accept(ResultSetVisitor visitor);
public abstract void accept(ResultPairVisitor visitor);
public ResultPair(A left, B right){
this.left = left;

@ -0,0 +1,7 @@
package de.dhbwstuttgart.typeinference.result;
public interface ResultPairVisitor {
void visit(PairTPHsmallerTPH p);
void visit(PairTPHequalRefTypeOrWildcardType p);
void visit(PairTPHEqualTPH p);
}

@ -2,10 +2,7 @@ package de.dhbwstuttgart.typeinference.result;
import de.dhbwstuttgart.syntaxtree.type.*;
public interface ResultSetVisitor {
void visit(PairTPHsmallerTPH p);
void visit(PairTPHequalRefTypeOrWildcardType p);
void visit(PairTPHEqualTPH p);
public interface ResultSetVisitor extends ResultPairVisitor{
void visit(RefType refType);

@ -4,9 +4,9 @@ import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.exceptions.TypeinferenceException;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
import de.dhbwstuttgart.parser.antlr.Java8Parser;
import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
import de.dhbwstuttgart.syntaxtree.statement.*;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.typeinference.assumptions.FieldAssumption;
@ -58,8 +58,8 @@ public class TYPEStmt implements StatementVisitor{
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);
lambdaParams.add(tphRetType);
//lambdaParams.add(0,tphRetType);
constraintsSet.addUndConstraint(
new Pair(lambdaExpression.getType(),
new FunN(lambdaParams),PairOperator.EQUALSDOT));
@ -81,11 +81,6 @@ public class TYPEStmt implements StatementVisitor{
assign.rightSide.getType(), assign.lefSide.getType(), PairOperator.SMALLERDOT));
}
@Override
public void visit(BinaryExpr binary) {
//TODO
}
@Override
public void visit(Block block) {
for(Statement stmt : block.getStatements()){
@ -190,6 +185,15 @@ public class TYPEStmt implements StatementVisitor{
receiver.expr.accept(this);
}
private final RefType number = new RefType(ASTFactory.createClass(Number.class).getClassName(), new NullToken());
private final RefType longg = new RefType(ASTFactory.createClass(Long.class).getClassName(), new NullToken());
private final RefType integer = new RefType(ASTFactory.createClass(Integer.class).getClassName(), new NullToken());
private final RefType shortt = new RefType(ASTFactory.createClass(Short.class).getClassName(), new NullToken());
private final RefType bytee = new RefType(ASTFactory.createClass(Byte.class).getClassName(), new NullToken());
private final RefType floatt = new RefType(ASTFactory.createClass(Float.class).getClassName(), new NullToken());
private final RefType doublee = new RefType(ASTFactory.createClass(Double.class).getClassName(), new NullToken());
private final RefType string = new RefType(ASTFactory.createClass(String.class).getClassName(), new NullToken());
private final RefType bool = new RefType(ASTFactory.createClass(Boolean.class).getClassName(), new NullToken());
@Override
public void visit(UnaryExpr unaryExpr) {
if(unaryExpr.operation == UnaryExpr.Operation.POSTDECREMENT ||
@ -198,8 +202,7 @@ public class TYPEStmt implements StatementVisitor{
unaryExpr.operation == UnaryExpr.Operation.PREINCREMENT){
//@see: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.14.2
//Expression muss zu Numeric Convertierbar sein. also von Numeric erben
RefType number = new RefType(ASTFactory.createClass(Number.class).getClassName(), unaryExpr.getOffset());
constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), number, PairOperator.EQUALSDOT));
constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), number, PairOperator.SMALLERNEQDOT));
//The type of the postfix increment expression is the type of the variable
constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), unaryExpr.getType(), PairOperator.EQUALSDOT));
}else{
@ -207,9 +210,159 @@ public class TYPEStmt implements StatementVisitor{
}
}
@Override
public void visit(BinaryExpr binary) {
binary.lexpr.accept(this);
binary.rexpr.accept(this);
if(binary.operation.equals(BinaryExpr.Operator.DIV) ||
binary.operation.equals(BinaryExpr.Operator.MUL)||
binary.operation.equals(BinaryExpr.Operator.MOD)||
binary.operation.equals(BinaryExpr.Operator.ADD)){
Set<Constraint<Pair>> numericAdditionOrStringConcatenation = new HashSet<>();
//Zuerst der Fall für Numerische AusdrücPairOpnumericeratorke, das sind Mul, Mod und Div immer:
//see: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17
//Expression muss zu Numeric Convertierbar sein. also von Numeric erben
Constraint<Pair> numeric;
//PL eingefuegt 2018-07-17
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(bytee.getName())) {
numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), bytee, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), bytee, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), integer, PairOperator.SMALLERDOT));
numericAdditionOrStringConcatenation.add(numeric);
}
//PL eingefuegt 2018-07-17
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(shortt.getName())) {
numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), shortt, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), shortt, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), integer, PairOperator.SMALLERDOT));
numericAdditionOrStringConcatenation.add(numeric);
}
//PL eingefuegt 2018-07-17
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(integer.getName())) {
numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), integer, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), integer, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), integer, PairOperator.SMALLERDOT));
numericAdditionOrStringConcatenation.add(numeric);
}
//PL eingefuegt 2018-07-17
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(longg.getName())) {
numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), longg, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), longg, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), longg, PairOperator.SMALLERDOT));
numericAdditionOrStringConcatenation.add(numeric);
}
//PL eingefuegt 2018-07-17
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(floatt.getName())) {
numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), floatt, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), floatt, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), floatt, PairOperator.SMALLERDOT));
numericAdditionOrStringConcatenation.add(numeric);
}
//PL eingefuegt 2018-07-17
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(doublee.getName())) {
numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), doublee, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), doublee, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), doublee, PairOperator.SMALLERDOT));
numericAdditionOrStringConcatenation.add(numeric);
}
/* PL auskommentiert Anfang 2018-07-17
/*
In Java passiert bei den binären Operatoren eine sogenannte Type Promotion:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2
Das bedeutet, dass Java die Typen je nach belieben castet, so lange sie nur von Number erben
numeric = new Constraint<>();
numeric.add(new Pair(binary.getType(), number, PairOperator.SMALLERDOT));
numericAdditionOrStringConcatenation.add(numeric);
* PL auskommentiert Ende 2018-07-17 */
if(binary.operation.equals(BinaryExpr.Operator.ADD)) {
//Dann kann der Ausdruck auch das aneinanderfügen zweier Strings sein: ("a" + "b") oder (1 + 2)
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(string.getName())) {
Constraint<Pair> stringConcat = new Constraint<>();
stringConcat.add(new Pair(binary.lexpr.getType(), string, PairOperator.EQUALSDOT));
stringConcat.add(new Pair(binary.rexpr.getType(), string, PairOperator.EQUALSDOT));
stringConcat.add(new Pair(binary.getType(), string, PairOperator.EQUALSDOT));
numericAdditionOrStringConcatenation.add(stringConcat);
}
}
constraintsSet.addOderConstraint(numericAdditionOrStringConcatenation);
}else if(binary.operation.equals(BinaryExpr.Operator.LESSEQUAL) ||
binary.operation.equals(BinaryExpr.Operator.BIGGEREQUAL) ||
binary.operation.equals(BinaryExpr.Operator.BIGGERTHAN) ||
binary.operation.equals(BinaryExpr.Operator.LESSTHAN)){
/* //eingefuegt PL 2018-05-24
Set<Constraint<Pair>> numericRelationConcatenation = new HashSet<>();
Constraint<Pair> numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), bytee, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), bytee, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT));
numericRelationConcatenation.add(numeric);
numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), shortt, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), shortt, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT));
numericRelationConcatenation.add(numeric);
numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), integer, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), integer, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT));
numericRelationConcatenation.add(numeric);
numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), longg, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), longg, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT));
numericRelationConcatenation.add(numeric);
numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), floatt, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), floatt, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT));
numericRelationConcatenation.add(numeric);
numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), doublee, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.rexpr.getType(), doublee, PairOperator.SMALLERDOT));
numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT));
numericRelationConcatenation.add(numeric);
//***ACHTUNG: Moeglicherweise oder und und-Contraint falsch
constraintsSet.addOderConstraint(numericRelationConcatenation);
//***ACHTUNG: Moeglicherweise oder und und-Contraint falsch
*/
//Testeise eingefuegt PL 2018-05-24
constraintsSet.addUndConstraint(new Pair(binary.lexpr.getType(), number, PairOperator.SMALLERNEQDOT));
constraintsSet.addUndConstraint(new Pair(binary.rexpr.getType(), number, PairOperator.SMALLERNEQDOT));
//Rückgabetyp ist Boolean
constraintsSet.addUndConstraint(new Pair(bool, binary.getType(), PairOperator.SMALLERDOT));
//auskommentiert PL 2018-05-24
//constraintsSet.addUndConstraint(new Pair(binary.lexpr.getType(), number, PairOperator.SMALLERDOT));
//constraintsSet.addUndConstraint(new Pair(binary.rexpr.getType(), number, PairOperator.SMALLERDOT));
//Rückgabetyp ist Boolean
//constraintsSet.addUndConstraint(new Pair(bool, binary.getType(), PairOperator.EQUALSDOT));
}else{
throw new NotImplementedException();
}
}
@Override
public void visit(Literal literal) {
//Nothing to do here. Literale kriegen beim parsen den korrekten Typ.
//Nothing to do here. Literale erzeugen keine Constraints
//PL 2018-06-23 Sie haben einen Typ. Der muesste hier eingefuegt werden
//wie hier fuer double gezeigt. Im Momment auskommentiert, weil zu wenige Literaltypen
//funktionieren
//if (literal.value instanceof Double) {
// constraintsSet.addUndConstraint(new Pair(literal.getType(), doublee, PairOperator.EQUALSDOT));
//}
//else {
// throw new NotImplementedException();
//}
}
@Override
@ -303,14 +456,14 @@ public class TYPEStmt implements StatementVisitor{
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
for(GenericTypeVar gtv : receiverCl.getGenerics()){
//Die Generics werden alle zu TPHs umgewandelt.
params.add(resolver.resolve(gtv.getParsedName()));
params.add(resolver.resolve(gtv.getName()));
}
RefTypeOrTPHOrWildcardOrGeneric receiverType = new RefType(assumption.getReceiver().getClassName(), params, forMethod.getOffset());
*/
methodConstraint.add(new Pair(forMethod.receiver.getType(), assumption.getReceiverType(resolver),
PairOperator.SMALLERDOT));
methodConstraint.add(new Pair(assumption.getReturnType(), forMethod.getType(),
methodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(),
PairOperator.EQUALSDOT));
methodConstraint.addAll(generateParameterConstraints(forMethod, assumption, info, resolver));
return methodConstraint;
@ -333,11 +486,14 @@ public class TYPEStmt implements StatementVisitor{
List<MethodAssumption> ret = new ArrayList<>();
//TODO: apply Methoden wieder anfügen. Diese könnten möglicherweise auch in den Assumptions auftauchen (überdenken)
if(name.equals("apply")){
List<RefTypeOrTPHOrWildcardOrGeneric> funNParams = new ArrayList<>();
List<GenericRefType> funNParams = new ArrayList<>();
for(int i = 0; i< numArgs + 1 ; i++){
funNParams.add(TypePlaceholder.fresh(new NullToken()));
//funNParams.add(TypePlaceholder.fresh(new NullToken()));
funNParams.add(new GenericRefType(NameGenerator.makeNewName(),
new NullToken()));
}
ret.add(new MethodAssumption(new FunNClass(funNParams), funNParams.get(0), funNParams.subList(1, funNParams.size()),
funNParams.get(funNParams.size()-1);
ret.add(new MethodAssumption(new FunNClass(funNParams), funNParams.get(funNParams.size()-1), funNParams.subList(0, funNParams.size()-1),
new TypeScope() {
@Override
public Iterable<? extends GenericTypeVar> getGenerics() {
@ -354,7 +510,7 @@ public class TYPEStmt implements StatementVisitor{
for(Method m : cl.getMethods()){
if(m.getName().equals(name) &&
m.getParameterList().getFormalparalist().size() == numArgs){
RefTypeOrTPHOrWildcardOrGeneric retType = info.checkGTV(m.getReturnType());
RefTypeOrTPHOrWildcardOrGeneric retType = m.getReturnType();//info.checkGTV(m.getReturnType());
ret.add(new MethodAssumption(cl, retType, convertParams(m.getParameterList(),info),
createTypeScope(cl, m)));
@ -380,7 +536,7 @@ public class TYPEStmt implements StatementVisitor{
*/
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
for(FormalParameter fp : parameterList.getFormalparalist()){
params.add(info.checkGTV(fp.getType()));
params.add(fp.getType()); //info.checkGTV(fp.getType())); //PL 2018-06-22 GTV sollen in Argumenten erhalten bleiben
}
return params;
}
@ -403,7 +559,7 @@ public class TYPEStmt implements StatementVisitor{
protected Constraint<Pair> generateConstructorConstraint(NewClass forConstructor, MethodAssumption assumption,
TypeInferenceBlockInformation info, GenericsResolver resolver){
Constraint methodConstraint = new Constraint();
methodConstraint.add(new Pair(assumption.getReturnType(), forConstructor.getType(),
methodConstraint.add(new Pair(assumption.getReturnType(resolver), forConstructor.getType(),
PairOperator.SMALLERDOT));
methodConstraint.addAll(generateParameterConstraints(forConstructor, assumption, info, resolver));
return methodConstraint;

@ -94,7 +94,8 @@ public class MartelliMontanariUnify implements IUnify {
// SUBST - Rule
if(lhsType instanceof PlaceholderType) {
mgu.add((PlaceholderType) lhsType, rhsType);
termsList = termsList.stream().map(mgu::apply).collect(Collectors.toCollection(ArrayList::new));
//PL 2018-04-01 nach checken, ob es richtig ist, dass keine Substitutionen uebergeben werden muessen.
termsList = termsList.stream().map(x -> mgu.apply(x)).collect(Collectors.toCollection(ArrayList::new));
idx = idx+1 == termsList.size() ? 0 : idx+1;
continue;
}

@ -0,0 +1,89 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.dhbwstuttgart.typeinference.unify.interfaces.IMatch;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
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 match derived from unification algorithm.
* @author Martin Pluemicke
*/
public class Match implements IMatch {
@Override
public Optional<Unifier> match(ArrayList<UnifyPair> termsList) {
// Start with the identity unifier. Substitutions will be added later.
Unifier mgu = Unifier.identity();
// Apply rules while possible
int idx = 0;
while(idx < termsList.size()) {
UnifyPair pair = termsList.get(idx);
UnifyType rhsType = pair.getRhsType();
UnifyType lhsType = pair.getLhsType();
TypeParams rhsTypeParams = rhsType.getTypeParams();
TypeParams lhsTypeParams = lhsType.getTypeParams();
// REDUCE - Rule
if(!(rhsType instanceof PlaceholderType) && !(lhsType instanceof PlaceholderType)) {
Set<UnifyPair> result = new HashSet<>();
// f<...> = g<...> with f != g are not unifiable
if(!rhsType.getName().equals(lhsType.getName()))
return Optional.empty(); // conflict
// f<t1,...,tn> = f<s1,...,sm> are not unifiable
if(rhsTypeParams.size() != lhsTypeParams.size())
return Optional.empty(); // conflict
// f = g is not unifiable (cannot be f = f because erase rule would have been applied)
//if(rhsTypeParams.size() == 0)
//return Optional.empty();
// Unpack the arguments
for(int i = 0; i < rhsTypeParams.size(); i++)
result.add(new UnifyPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT));
termsList.remove(idx);
termsList.addAll(result);
continue;
}
// DELETE - Rule
if(pair.getRhsType().equals(pair.getLhsType())) {
termsList.remove(idx);
continue;
}
// SWAP - Rule
if(!(lhsType instanceof PlaceholderType) && (rhsType instanceof PlaceholderType)) {
return Optional.empty(); // conflict
}
// OCCURS-CHECK
//deleted
// SUBST - Rule
if(lhsType instanceof PlaceholderType) {
mgu.add((PlaceholderType) lhsType, rhsType);
termsList = termsList.stream().map(mgu::applyleft).collect(Collectors.toCollection(ArrayList::new));
idx = idx+1 == termsList.size() ? 0 : idx+1;
continue;
}
idx++;
}
return Optional.of(mgu);
}
}

@ -24,13 +24,27 @@ import de.dhbwstuttgart.typeinference.unify.model.Unifier;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
import de.dhbwstuttgart.typeinference.unify.model.WildcardType;
import de.dhbwstuttgart.typeinference.unify.distributeVariance;
import java.io.FileWriter;
import java.io.IOException;
/**
* Implementation of the type inference rules.
* @author Florian Steurer
*
*/
public class RuleSet implements IRuleSet{
public class RuleSet implements IRuleSet{
FileWriter logFile;
RuleSet() {
super();
}
RuleSet(FileWriter logFile) {
this.logFile = logFile;
}
@Override
public Optional<UnifyPair> reduceUp(UnifyPair pair) {
@ -47,7 +61,7 @@ public class RuleSet implements IRuleSet{
return Optional.empty();
// Rule is applicable, unpack the SuperType
return Optional.of(new UnifyPair(lhsType, ((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT));
return Optional.of(new UnifyPair(lhsType, ((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
}
@Override
@ -65,7 +79,7 @@ public class RuleSet implements IRuleSet{
return Optional.empty();
// Rule is applicable, unpack the ExtendsType
return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(), rhsType, PairOperator.SMALLERDOT));
return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(), rhsType, PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
}
@Override
@ -83,7 +97,7 @@ public class RuleSet implements IRuleSet{
return Optional.empty();
// Rule is applicable, unpack both sides
return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(),((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT));
return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(),((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
}
@Override
@ -117,7 +131,7 @@ public class RuleSet implements IRuleSet{
if(x instanceof ExtendsType)
xFromFc = new ExtendsType(xFromFc);
UnifyType extYFromFc = fc.grArg(xFromFc).stream().filter(t -> t.getName().equals(extY.getName())).filter(t -> t.getTypeParams().arePlaceholders()).findAny().orElse(null);
UnifyType extYFromFc = fc.grArg(xFromFc, new HashSet<>()).stream().filter(t -> t.getName().equals(extY.getName())).filter(t -> t.getTypeParams().arePlaceholders()).findAny().orElse(null);
if(extYFromFc == null || extYFromFc.getTypeParams() != xFromFc.getTypeParams())
return Optional.empty();
@ -133,7 +147,7 @@ public class RuleSet implements IRuleSet{
Set<UnifyPair> result = new HashSet<>();
for(int rhsIdx = 0; rhsIdx < extYParams.size(); rhsIdx++)
result.add(new UnifyPair(xParams.get(pi[rhsIdx]), extYParams.get(rhsIdx), PairOperator.SMALLERDOTWC));
result.add(new UnifyPair(xParams.get(pi[rhsIdx]), extYParams.get(rhsIdx), PairOperator.SMALLERDOTWC, pair.getSubstitution(), pair.getBasePair()));
return Optional.of(result);
}
@ -169,7 +183,7 @@ public class RuleSet implements IRuleSet{
if(x instanceof SuperType)
xFromFc = new SuperType(xFromFc);
UnifyType supYFromFc = fc.grArg(xFromFc).stream().filter(t -> t.getName().equals(supY.getName())).filter(t -> t.getTypeParams().arePlaceholders()).findAny().orElse(null);
UnifyType supYFromFc = fc.grArg(xFromFc, new HashSet<>()).stream().filter(t -> t.getName().equals(supY.getName())).filter(t -> t.getTypeParams().arePlaceholders()).findAny().orElse(null);
if(supYFromFc == null || supYFromFc.getTypeParams() != xFromFc.getTypeParams())
return Optional.empty();
@ -184,7 +198,7 @@ public class RuleSet implements IRuleSet{
return Optional.empty();
for(int rhsIdx = 0; rhsIdx < supYParams.size(); rhsIdx++)
result.add(new UnifyPair(supYParams.get(rhsIdx), xParams.get(pi[rhsIdx]), PairOperator.SMALLERDOTWC));
result.add(new UnifyPair(supYParams.get(rhsIdx), xParams.get(pi[rhsIdx]), PairOperator.SMALLERDOTWC, pair.getSubstitution(), pair.getBasePair()));
return Optional.of(result);
}
@ -215,7 +229,7 @@ public class RuleSet implements IRuleSet{
TypeParams rhsTypeParams = rhsType.getTypeParams();
for(int i = 0; i < lhsTypeParams.size(); i++)
result.add(new UnifyPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT));
result.add(new UnifyPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
return Optional.of(result);
}
@ -236,19 +250,53 @@ public class RuleSet implements IRuleSet{
ReferenceType lhsSType = (ReferenceType) c;
ReferenceType rhsSType = (ReferenceType) d;
//try {
// logFile.write("PAIR Rules: " + pair + "\n");
// logFile.flush();
//}
//catch (IOException e) { }
if(lhsSType.getTypeParams().empty() || lhsSType.getTypeParams().size() != rhsSType.getTypeParams().size())
return Optional.empty();
UnifyType cFromFc = fc.getLeftHandedType(c.getName()).orElse(null);
//2018-02-23: liefert Vector<Vector<Integer>>: Das kann nicht sein.
//NOCHMAL UEBERPRUEFEN
//PL 18-02-09 Eingfuegt Anfang
//C und D koennen auch gleich sein.
if (c.getName().equals(d.getName())) {
Set<UnifyPair> result = new HashSet<>();
TypeParams rhsTypeParams = d.getTypeParams();
TypeParams lhsTypeParams = c.getTypeParams();
for(int rhsIdx = 0; rhsIdx < c.getTypeParams().size(); rhsIdx++)
result.add(new UnifyPair(lhsTypeParams.get(rhsIdx), rhsTypeParams.get(rhsIdx), PairOperator.SMALLERDOTWC, pair.getSubstitution(), pair.getBasePair()));
return Optional.of(result);
}
//PL 18-02-09 Eingfuegt ENDE
//try {
// logFile.write("cFromFc: " + cFromFc);
// logFile.flush();
//}
//catch (IOException e) { }
if(cFromFc == null || !cFromFc.getTypeParams().arePlaceholders())
return Optional.empty();
UnifyType dFromFc = fc.getAncestors(cFromFc).stream().filter(x -> x.getName().equals(d.getName())).findAny().orElse(null);
//try {
// logFile.write("cFromFc: " + cFromFc);
// logFile.flush();
//}
//catch (IOException e) { }
if(dFromFc == null || !dFromFc.getTypeParams().arePlaceholders() || dFromFc.getTypeParams().size() != cFromFc.getTypeParams().size())
return Optional.empty();
//System.out.println("cFromFc: " + cFromFc);
//System.out.println("dFromFc: " + dFromFc);
int[] pi = pi(cFromFc.getTypeParams(), dFromFc.getTypeParams());
if(pi.length == 0)
@ -259,7 +307,7 @@ public class RuleSet implements IRuleSet{
Set<UnifyPair> result = new HashSet<>();
for(int rhsIdx = 0; rhsIdx < rhsTypeParams.size(); rhsIdx++)
result.add(new UnifyPair(lhsTypeParams.get(pi[rhsIdx]), rhsTypeParams.get(rhsIdx), PairOperator.SMALLERDOTWC));
result.add(new UnifyPair(lhsTypeParams.get(pi[rhsIdx]), rhsTypeParams.get(rhsIdx), PairOperator.SMALLERDOTWC, pair.getSubstitution(), pair.getBasePair()));
return Optional.of(result);
}
@ -314,16 +362,31 @@ public class RuleSet implements IRuleSet{
TypeParams rhsTypeParams = rhsSType.getTypeParams();
TypeParams lhsTypeParams = lhsSType.getTypeParams();
for(int i = 0; i < rhsTypeParams.size(); i++)
result.add(new UnifyPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT));
result.add(new UnifyPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
return Optional.of(result);
}
@Override
public boolean erase1(UnifyPair pair, IFiniteClosure fc) {
if(pair.getPairOp() != PairOperator.SMALLERDOT)
if((pair.getPairOp() != PairOperator.SMALLERDOT) && (pair.getPairOp() != PairOperator.SMALLERNEQDOT))
return false;
if (pair.getPairOp() == PairOperator.SMALLERNEQDOT) {
UnifyType lhs = pair.getLhsType();
UnifyType rhs = pair.getRhsType();
if (lhs instanceof WildcardType) {
lhs = ((WildcardType)lhs).getWildcardedType();
}
if (rhs instanceof WildcardType) {
rhs = ((WildcardType)rhs).getWildcardedType();
}
if (lhs.equals(rhs)){
return false;
}
}
UnifyType lhsType = pair.getLhsType();
if(!(lhsType instanceof ReferenceType) && !(lhsType instanceof PlaceholderType))
return false;
@ -332,7 +395,7 @@ public class RuleSet implements IRuleSet{
if(!(rhsType instanceof ReferenceType) && !(rhsType instanceof PlaceholderType))
return false;
return fc.greater(lhsType).contains(rhsType);
return fc.greater(lhsType, new HashSet<>()).contains(rhsType);
}
@Override
@ -343,7 +406,7 @@ public class RuleSet implements IRuleSet{
UnifyType lhsType = pair.getLhsType();
UnifyType rhsType = pair.getRhsType();
return fc.grArg(lhsType).contains(rhsType);
return fc.grArg(lhsType, new HashSet<>()).contains(rhsType);
}
@Override
@ -365,7 +428,7 @@ public class RuleSet implements IRuleSet{
if(!(pair.getRhsType() instanceof PlaceholderType))
return Optional.empty();
return Optional.of(new UnifyPair(pair.getRhsType(), pair.getLhsType(), PairOperator.EQUALSDOT));
return Optional.of(new UnifyPair(pair.getRhsType(), pair.getLhsType(), PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
}
@Override
@ -407,11 +470,19 @@ public class RuleSet implements IRuleSet{
TypeParams typeDParams = typeD.getTypeParams();
TypeParams typeDgenParams = typeDgen.getTypeParams();
//System.out.println("Pair: " +pair);
//System.out.println("typeD: " +typeD);
//System.out.println("typeDParams: " +typeDParams);
//System.out.println("typeDgen: " +typeD);
//System.out.println("typeDgenParams: " +typeDgenParams);
Unifier unif = Unifier.identity();
for(int i = 0; i < typeDParams.size(); i++)
for(int i = 0; i < typeDParams.size(); i++) {
//System.out.println("ADAPT" +typeDgenParams);
if (typeDgenParams.get(i) instanceof PlaceholderType)
unif.add((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i));
return Optional.of(new UnifyPair(unif.apply(newLhs), typeDs, PairOperator.SMALLERDOT));
else System.out.println("ERROR");
}
return Optional.of(new UnifyPair(unif.apply(newLhs), typeDs, PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
}
@Override
@ -441,7 +512,7 @@ public class RuleSet implements IRuleSet{
if(typeDgen == null)
return Optional.empty();
Set<UnifyType> grArg = fc.grArg(typeDgen);
Set<UnifyType> grArg = fc.grArg(typeDgen, new HashSet<>());
Optional<UnifyType> opt = grArg.stream().filter(x -> x.getName().equals(typeExtDs.getName())).findAny();
@ -457,7 +528,7 @@ public class RuleSet implements IRuleSet{
for(int i = 1; i < typeDParams.size(); i++)
unif.add((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i));
return Optional.of(new UnifyPair(unif.apply(newLhs), typeExtDs, PairOperator.SMALLERDOTWC));
return Optional.of(new UnifyPair(unif.apply(newLhs), typeExtDs, PairOperator.SMALLERDOTWC, pair.getSubstitution(), pair.getBasePair()));
}
@Override
@ -487,7 +558,7 @@ public class RuleSet implements IRuleSet{
// Use of smArg instead of grArg because
// a in grArg(b) => b in smArg(a)
Set<UnifyType> smArg = fc.smArg(typeSupDgen);
Set<UnifyType> smArg = fc.smArg(typeSupDgen, new HashSet<>());
opt = smArg.stream().filter(x -> x.getName().equals(typeDs.getName())).findAny();
if(!opt.isPresent())
@ -509,7 +580,7 @@ public class RuleSet implements IRuleSet{
for(int i = 1; i < typeDParams.size(); i++)
unif.add((PlaceholderType) typeSupDsgenParams.get(i), typeDParams.get(i));
return Optional.of(new UnifyPair(unif.apply(newLhs), newRhs, PairOperator.SMALLERDOTWC));
return Optional.of(new UnifyPair(unif.apply(newLhs), newRhs, PairOperator.SMALLERDOTWC, pair.getSubstitution(), pair.getBasePair()));
}
/**
@ -581,8 +652,8 @@ public class RuleSet implements IRuleSet{
&& typeMap.get(lhsType) > 1 // The type occurs in more pairs in the set than just the recent pair.
&& !rhsType.getTypeParams().occurs(lhsType)) {
Unifier uni = new Unifier(lhsType, rhsType);
result = result.stream().map(uni::apply).collect(Collectors.toCollection(ArrayList::new));
result1 = result1.stream().map(uni::apply).collect(Collectors.toCollection(LinkedList::new));
result = result.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(ArrayList::new));
result1 = result1.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(LinkedList::new));
applied = true;
}
@ -602,7 +673,7 @@ public class RuleSet implements IRuleSet{
if(!(lhsType instanceof ExtendsType) || !(rhsType instanceof ExtendsType))
return Optional.empty();
return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(), ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT));
return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(), ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
}
@Override
@ -615,7 +686,7 @@ public class RuleSet implements IRuleSet{
if(!(lhsType instanceof ReferenceType) || !(rhsType instanceof ExtendsType))
return Optional.empty();
return Optional.of(new UnifyPair(lhsType, ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT));
return Optional.of(new UnifyPair(lhsType, ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
}
@Override
@ -628,7 +699,7 @@ public class RuleSet implements IRuleSet{
if(!(lhsType instanceof SuperType) || !(rhsType instanceof SuperType))
return Optional.empty();
return Optional.of(new UnifyPair(((SuperType) rhsType).getSuperedType(), ((SuperType) lhsType).getSuperedType(), PairOperator.SMALLERDOT));
return Optional.of(new UnifyPair(((SuperType) rhsType).getSuperedType(), ((SuperType) lhsType).getSuperedType(), PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
}
@Override
@ -641,9 +712,11 @@ public class RuleSet implements IRuleSet{
if(!(lhsType instanceof ReferenceType) || !(rhsType instanceof SuperType))
return Optional.empty();
return Optional.of(new UnifyPair(((SuperType) rhsType).getSuperedType(), lhsType, PairOperator.SMALLERDOTWC));
return Optional.of(new UnifyPair(((SuperType) rhsType).getSuperedType(), lhsType, PairOperator.SMALLERDOTWC, pair.getSubstitution(), pair.getBasePair()));
}
/* PL 2018-03-06 auskommentiert sind mutmaßlich falsch
* vgl. JAVA_BSP/Wildcard6.java
@Override
public Optional<UnifyPair> reduceWildcardLowUp(UnifyPair pair) {
if(pair.getPairOp() != PairOperator.SMALLERDOTWC)
@ -670,6 +743,7 @@ public class RuleSet implements IRuleSet{
return Optional.of(new UnifyPair(((SuperType) lhsType).getSuperedType(), ((ExtendsType) rhsType).getExtendedType(), PairOperator.EQUALSDOT));
}
@Override
public Optional<UnifyPair> reduceWildcardLeft(UnifyPair pair) {
if(pair.getPairOp() != PairOperator.SMALLERDOTWC)
@ -686,7 +760,7 @@ public class RuleSet implements IRuleSet{
return Optional.empty();
}
*/
@Override
public Optional<Set<UnifyPair>> reduceFunN(UnifyPair pair) {
if((pair.getPairOp() != PairOperator.SMALLERDOT)
@ -709,13 +783,19 @@ public class RuleSet implements IRuleSet{
Set<UnifyPair> result = new HashSet<UnifyPair>();
result.add(new UnifyPair(funNLhsType.getTypeParams().get(0), funNRhsType.getTypeParams().get(0), PairOperator.SMALLERDOT));
for(int i = 1; i < funNLhsType.getTypeParams().size(); i++)
result.add(new UnifyPair(funNRhsType.getTypeParams().get(i), funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT));
result.add(new UnifyPair(funNLhsType.getTypeParams().get(funNLhsType.getTypeParams().size()-1), funNRhsType.getTypeParams().get(funNRhsType.getTypeParams().size()-1), PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
for(int i = 0; i < funNLhsType.getTypeParams().size()-1; i++) {
result.add(new UnifyPair(funNRhsType.getTypeParams().get(i), funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
}
result.stream().forEach(x -> { UnifyType l = x.getLhsType();
if (l instanceof PlaceholderType) { ((PlaceholderType)l).disableWildcardtable(); }
UnifyType r = x.getRhsType();
if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); }
} );
return Optional.of(result);
}
@Override
public Optional<Set<UnifyPair>> greaterFunN(UnifyPair pair) {
if(pair.getPairOp() != PairOperator.SMALLERDOT)
@ -731,15 +811,29 @@ public class RuleSet implements IRuleSet{
Set<UnifyPair> result = new HashSet<UnifyPair>();
Integer variance = ((PlaceholderType)rhsType).getVariance();
Integer inversVariance = distributeVariance.inverseVariance(variance);
UnifyType[] freshPlaceholders = new UnifyType[funNLhsType.getTypeParams().size()];
for(int i = 0; i < freshPlaceholders.length; i++)
for(int i = 0; i < freshPlaceholders.length-1; i++) {
freshPlaceholders[i] = PlaceholderType.freshPlaceholder();
((PlaceholderType)freshPlaceholders[i]).setVariance(inversVariance);
}
freshPlaceholders[freshPlaceholders.length-1] = PlaceholderType.freshPlaceholder();
((PlaceholderType)freshPlaceholders[freshPlaceholders.length-1]).setVariance(variance);
result.add(new UnifyPair(funNLhsType.getTypeParams().get(funNLhsType.getTypeParams().size()-1), freshPlaceholders[funNLhsType.getTypeParams().size()-1], PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
result.add(new UnifyPair(funNLhsType.getTypeParams().get(0), freshPlaceholders[0], PairOperator.SMALLERDOT));
for(int i = 1; i < funNLhsType.getTypeParams().size(); i++)
result.add(new UnifyPair(freshPlaceholders[i], funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT));
result.add(new UnifyPair(rhsType, funNLhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT));
for(int i = 0; i < funNLhsType.getTypeParams().size()-1; i++) {
result.add(new UnifyPair(freshPlaceholders[i], funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
}
result.add(new UnifyPair(rhsType, funNLhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
result.stream().forEach(x -> { UnifyType l = x.getLhsType();
if (l instanceof PlaceholderType) { ((PlaceholderType)l).disableWildcardtable(); }
UnifyType r = x.getRhsType();
if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); }
} );
return Optional.of(result);
}
@ -758,15 +852,30 @@ public class RuleSet implements IRuleSet{
Set<UnifyPair> result = new HashSet<UnifyPair>();
Integer variance = ((PlaceholderType)lhsType).getVariance();
Integer inversVariance = distributeVariance.inverseVariance(variance);
UnifyType[] freshPlaceholders = new UnifyType[funNRhsType.getTypeParams().size()];
for(int i = 0; i < freshPlaceholders.length; i++)
for(int i = 0; i < freshPlaceholders.length-1; i++) {
freshPlaceholders[i] = PlaceholderType.freshPlaceholder();
((PlaceholderType)freshPlaceholders[i]).setVariance(inversVariance);
}
freshPlaceholders[freshPlaceholders.length-1] = PlaceholderType.freshPlaceholder();
((PlaceholderType)freshPlaceholders[freshPlaceholders.length-1]).setVariance(variance);
result.add(new UnifyPair(freshPlaceholders[0], funNRhsType.getTypeParams().get(0), PairOperator.SMALLERDOT));
for(int i = 1; i < funNRhsType.getTypeParams().size(); i++)
result.add(new UnifyPair(funNRhsType.getTypeParams().get(i), freshPlaceholders[i], PairOperator.SMALLERDOT));
result.add(new UnifyPair(lhsType, funNRhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT));
result.add(new UnifyPair(freshPlaceholders[funNRhsType.getTypeParams().size()-1], funNRhsType.getTypeParams().get(funNRhsType.getTypeParams().size()-1), PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
for(int i = 0; i < funNRhsType.getTypeParams().size()-1; i++) {
result.add(new UnifyPair(funNRhsType.getTypeParams().get(i), freshPlaceholders[i], PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
}
result.add(new UnifyPair(lhsType, funNRhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
result.stream().forEach(x -> { UnifyType l = x.getLhsType();
if (l instanceof PlaceholderType) { ((PlaceholderType)l).disableWildcardtable(); }
UnifyType r = x.getRhsType();
if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); }
} );
return Optional.of(result);
}
@ -780,7 +889,7 @@ public class RuleSet implements IRuleSet{
if(!(lhsType instanceof PlaceholderType) || !(rhsType instanceof ReferenceType))
return Optional.empty();
return Optional.of(new UnifyPair(lhsType, rhsType, PairOperator.EQUALSDOT));
return Optional.of(new UnifyPair(lhsType, rhsType, PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
}
@Override
@ -799,11 +908,11 @@ public class RuleSet implements IRuleSet{
Set<UnifyPair> result = new HashSet<>();
if(isGen)
result.add(new UnifyPair(rhsType, lhsType, PairOperator.EQUALSDOT));
result.add(new UnifyPair(rhsType, lhsType, PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
else {
UnifyType freshTph = PlaceholderType.freshPlaceholder();
result.add(new UnifyPair(rhsType, new ExtendsType(freshTph), PairOperator.EQUALSDOT));
result.add(new UnifyPair(extendedType, freshTph, PairOperator.SMALLERDOT));
result.add(new UnifyPair(rhsType, new ExtendsType(freshTph), PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
result.add(new UnifyPair(extendedType, freshTph, PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
}
return Optional.of(result);
@ -825,11 +934,13 @@ public class RuleSet implements IRuleSet{
Set<UnifyPair> result = new HashSet<>();
if(isGen)
result.add(new UnifyPair(rhsType, lhsType, PairOperator.EQUALSDOT));
result.add(new UnifyPair(rhsType, lhsType, PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
else {
UnifyType freshTph = PlaceholderType.freshPlaceholder();
result.add(new UnifyPair(rhsType, new SuperType(freshTph), PairOperator.EQUALSDOT));
result.add(new UnifyPair(freshTph, superedType, PairOperator.SMALLERDOT));
result.add(new UnifyPair(rhsType, new SuperType(freshTph), PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
Set<UnifyType> fBounded = pair.getfBounded();
fBounded.add(lhsType);
result.add(new UnifyPair(freshTph, superedType, PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair(), fBounded));
}
return Optional.of(result);

@ -1,5 +1,7 @@
package de.dhbwstuttgart.typeinference.unify;
import java.io.FileWriter;
import java.util.ConcurrentModificationException;
import java.util.Set;
import java.util.concurrent.ForkJoinPool;
@ -7,16 +9,21 @@ 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);
public Set<Set<UnifyPair>> unify(Set<UnifyPair> eq, IFiniteClosure fc, FileWriter logFile, Boolean log) {
TypeUnifyTask unifyTask = new TypeUnifyTask(eq, fc, true, logFile, log);
ForkJoinPool pool = new ForkJoinPool();
try {
pool.invoke(unifyTask);
}
catch (ConcurrentModificationException v) {
v.printStackTrace();
}
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);
public Set<Set<UnifyPair>> unifySequential(Set<UnifyPair> eq, IFiniteClosure fc, FileWriter logFile, Boolean log) {
TypeUnifyTask unifyTask = new TypeUnifyTask(eq, fc, false, logFile, log);
Set<Set<UnifyPair>> res = unifyTask.compute();
return res;
}

@ -0,0 +1,32 @@
package de.dhbwstuttgart.typeinference.unify;
import java.io.FileWriter;
import java.util.HashSet;
import java.util.Set;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
public class TypeUnify2Task extends TypeUnifyTask {
Set<Set<UnifyPair>> setToFlatten;
public TypeUnify2Task(Set<Set<UnifyPair>> setToFlatten, Set<UnifyPair> eq, IFiniteClosure fc, boolean parallel, FileWriter logFile, Boolean log) {
super(eq, fc, parallel, logFile, log);
this.setToFlatten = setToFlatten;
}
@Override
protected Set<Set<UnifyPair>> compute() {
if (one) {
System.out.println("two");
}
one = true;
Set<Set<UnifyPair>> res = unify2(setToFlatten, eq, fc, parallel);
/*if (isUndefinedPairSetSet(res)) {
return new HashSet<>(); }
else
*/
return res;
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,54 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import de.dhbwstuttgart.typeinference.unify.model.FunNType;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.TypeParams;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
public class distributeVariance extends visitUnifyTypeVisitor<Integer> {
public static int inverseVariance(int variance) {
Integer ret = 0;
if (variance == 1) {
ret = -1;
}
if (variance == -1) {
ret = 1;
}
return ret;
}
@Override
public PlaceholderType visit(PlaceholderType phty, Integer ht) {
if (ht != 0) {
if (phty.getVariance() == 0) {
phty.setVariance(ht);
}
//PL 2018-05-17 urspruengliche Variance nicht veraendern
//else if (phty.getVariance() != ht) {
// phty.setVariance(0);
//}
}
return phty;
}
public FunNType visit(FunNType funnty, Integer ht) {
List<UnifyType> param = new ArrayList<>(funnty.getTypeParams().get().length);
param.addAll(Arrays.asList(funnty.getTypeParams().get()));
UnifyType resultType = param.remove(param.size()-1);
Integer htInverse = inverseVariance(ht);
param = param.stream()
.map(x -> x.accept(this, htInverse))
.collect(Collectors.toCollection(ArrayList::new));
param.add(resultType.accept(this, ht));
return FunNType.getFunNType(new TypeParams(param));
}
}

@ -0,0 +1,15 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.HashMap;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
public class freshPlaceholder extends visitUnifyTypeVisitor<HashMap<PlaceholderType,PlaceholderType>> {
@Override
public PlaceholderType visit(PlaceholderType phty, HashMap<PlaceholderType,PlaceholderType> ht) {
return ht.get(phty);
}
}

@ -5,6 +5,7 @@ import java.util.Set;
import de.dhbwstuttgart.typeinference.unify.model.ExtendsType;
import de.dhbwstuttgart.typeinference.unify.model.FunNType;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.ReferenceType;
import de.dhbwstuttgart.typeinference.unify.model.SuperType;
@ -20,45 +21,47 @@ public interface IFiniteClosure {
* Returns all types of the finite closure that are subtypes of the argument.
* @return The set of subtypes of the argument.
*/
public Set<UnifyType> smaller(UnifyType type);
public Set<UnifyType> smaller(UnifyType type, Set<UnifyType> fBounded);
/**
* Returns all types of the finite closure that are supertypes of the argument.
* @return The set of supertypes of the argument.
*/
public Set<UnifyType> greater(UnifyType type);
public Set<UnifyType> greater(UnifyType type, Set<UnifyType> fBounded);
/**
* Wo passt Type rein?
* @param type
* @return
*/
public Set<UnifyType> grArg(UnifyType type);
public Set<UnifyType> grArg(UnifyType type, Set<UnifyType> fBounded);
/**
* Was passt in Type rein?
* @param type
* @return
*/
public Set<UnifyType> smArg(UnifyType type);
public Set<UnifyType> smArg(UnifyType type, Set<UnifyType> fBounded);
public Set<UnifyType> grArg(ReferenceType type);
public Set<UnifyType> smArg(ReferenceType type);
public Set<UnifyType> grArg(ReferenceType type, Set<UnifyType> fBounded);
public Set<UnifyType> smArg(ReferenceType type, Set<UnifyType> fBounded);
public Set<UnifyType> grArg(ExtendsType type);
public Set<UnifyType> smArg(ExtendsType type);
public Set<UnifyType> grArg(ExtendsType type, Set<UnifyType> fBounded);
public Set<UnifyType> smArg(ExtendsType type, Set<UnifyType> fBounded);
public Set<UnifyType> grArg(SuperType type);
public Set<UnifyType> smArg(SuperType type);
public Set<UnifyType> grArg(SuperType type, Set<UnifyType> fBounded);
public Set<UnifyType> smArg(SuperType type, Set<UnifyType> fBounded);
public Set<UnifyType> grArg(PlaceholderType type);
public Set<UnifyType> smArg(PlaceholderType type);
public Set<UnifyType> grArg(PlaceholderType type, Set<UnifyType> fBounded);
public Set<UnifyType> smArg(PlaceholderType type, Set<UnifyType> fBounded);
public Set<UnifyType> grArg(FunNType type);
public Set<UnifyType> smArg(FunNType type);
public Set<UnifyType> grArg(FunNType type, Set<UnifyType> fBounded);
public Set<UnifyType> smArg(FunNType type, Set<UnifyType> fBounded);
public Optional<UnifyType> getLeftHandedType(String typeName);
public Set<UnifyType> getAncestors(UnifyType t);
public Set<UnifyType> getChildren(UnifyType t);
public Set<UnifyType> getAllTypesByName(String typeName);
public Set<UnifyType> getAllTypesByName(String typeName);
public int compare(UnifyType rhsType, UnifyType rhsType2, PairOperator pairop);
}

@ -0,0 +1,29 @@
package de.dhbwstuttgart.typeinference.unify.interfaces;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
import de.dhbwstuttgart.typeinference.unify.model.Unifier;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
/**
* Match
* @author Martin Pluemicke
* abgeleitet aus IUnify.java
*/
public interface IMatch {
/**
* Finds the most general matcher sigma of the set {t1 =. t1',...,tn =. tn'} so that
* sigma(t1) = t1' , ... sigma(tn) = tn'.
* @param terms The set of terms to be matched
* @return An optional of the most general matcher if it exists or an empty optional if there is no matcher.
*/
public Optional<Unifier> match(ArrayList<UnifyPair> termsList);
}

@ -27,9 +27,13 @@ public interface IRuleSet {
public Optional<UnifyPair> reduceWildcardLowRight(UnifyPair pair);
public Optional<UnifyPair> reduceWildcardUp(UnifyPair pair);
public Optional<UnifyPair> reduceWildcardUpRight(UnifyPair pair);
/*
* vgl. JAVA_BSP/Wildcard6.java
public Optional<UnifyPair> reduceWildcardLowUp(UnifyPair pair);
public Optional<UnifyPair> reduceWildcardUpLow(UnifyPair pair);
public Optional<UnifyPair> reduceWildcardLeft(UnifyPair pair);
*/
/*
* Additional Rules which replace cases of the cartesian product

@ -15,16 +15,16 @@ import de.dhbwstuttgart.typeinference.unify.model.Unifier;
public interface IUnify {
/**
* Finds the most general unifier sigma of the set {t1,...,tn} so that
* sigma(t1) = sigma(t2) = ... = sigma(tn).
* Finds the most general unifier sigma of the set {t1 =. t1',...,tn =. tn'} so that
* sigma(t1) = sigma(t1') , ... sigma(tn) = sigma(tn').
* @param terms The set of terms to be unified
* @return An optional of the most general unifier if it exists or an empty optional if there is no unifier.
*/
public Optional<Unifier> unify(Set<UnifyType> terms);
/**
* Finds the most general unifier sigma of the set {t1,...,tn} so that
* sigma(t1) = sigma(t2) = ... = sigma(tn).
* Finds the most general unifier sigma of the set {t1 =. t1',...,tn =. tn'} so that
* sigma(t1) = sigma(t1') , ... sigma(tn) = sigma(tn').
* @param terms The set of terms to be unified
* @return An optional of the most general unifier if it exists or an empty optional if there is no unifier.
*/

@ -0,0 +1,23 @@
package de.dhbwstuttgart.typeinference.unify.interfaces;
import java.util.HashMap;
import de.dhbwstuttgart.typeinference.unify.model.ExtendsType;
import de.dhbwstuttgart.typeinference.unify.model.FunNType;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.ReferenceType;
import de.dhbwstuttgart.typeinference.unify.model.SuperType;
public interface UnifyTypeVisitor<T> {
public ReferenceType visit(ReferenceType refty, T ht);
public PlaceholderType visit(PlaceholderType phty, T ht);
public FunNType visit(FunNType funnty, T ht);
public SuperType visit(SuperType suty, T ht);
public ExtendsType visit(ExtendsType extty, T ht);
}

@ -2,21 +2,30 @@ package de.dhbwstuttgart.typeinference.unify.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.interfaces.UnifyTypeVisitor;
/**
* An extends wildcard type "? extends T".
*/
public final class ExtendsType extends WildcardType {
public <T> UnifyType accept(UnifyTypeVisitor<T> visitor, T ht) {
return visitor.visit(this, ht);
}
/**
* Creates a new extends wildcard type.
* @param extendedType The extended type e.g. Integer in "? extends Integer"
*/
public ExtendsType(UnifyType extendedType) {
super("? extends " + extendedType.getName(), extendedType);
super("? extends " + extendedType.getName(), extendedType);
if (extendedType instanceof ExtendsType) {
System.out.print("");
}
}
/**
@ -38,13 +47,13 @@ public final class ExtendsType extends WildcardType {
}
@Override
Set<UnifyType> smArg(IFiniteClosure fc) {
return fc.smArg(this);
Set<UnifyType> smArg(IFiniteClosure fc, Set<UnifyType> fBounded) {
return fc.smArg(this, fBounded);
}
@Override
Set<UnifyType> grArg(IFiniteClosure fc) {
return fc.grArg(this);
Set<UnifyType> grArg(IFiniteClosure fc, Set<UnifyType> fBounded) {
return fc.grArg(this, fBounded);
}
@Override

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