Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3ba2714da |
Binary file not shown.
@@ -1,19 +0,0 @@
|
||||
import java.util.stream.Stream;
|
||||
import Pair;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class Kombinatoren_After {
|
||||
|
||||
|
||||
after (fst, snd) { //System.out.println("after2");
|
||||
|
||||
return () -> Stream.of(
|
||||
toks -> {
|
||||
return fst.apply().flatMap(x ->
|
||||
x.apply(toks).flatMap(p1 ->
|
||||
snd.apply().flatMap(y -> y.apply(p1.snd()).map(p2 ->
|
||||
new Pair<>(new Pair<>(p1.fst(), p2.fst()), p2.snd()))))); } );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
import java.util.stream.Stream;
|
||||
import Pair;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class Kombinatoren_After_Lazy {
|
||||
|
||||
|
||||
afterP (fst, snd) {
|
||||
return toks -> {
|
||||
return fst.apply(toks).flatMap(p1 ->
|
||||
snd.apply(p1.snd()).map(p2 ->
|
||||
new Pair<>(new Pair<>(p1.fst(), p2.fst()), p2.snd())));
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import java.util.stream.Stream;
|
||||
import Pair;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class Kombinatoren_Or {
|
||||
|
||||
|
||||
orP (p1, p2) {
|
||||
return ()-> Stream.concat(p1.apply(), p2.apply());
|
||||
}
|
||||
|
||||
/*
|
||||
after (fst, snd) { //System.out.println("after2");
|
||||
|
||||
return () -> Stream.of(
|
||||
toks -> {
|
||||
return fst.apply().flatMap(x ->
|
||||
x.apply(toks).flatMap(p1 ->
|
||||
snd.apply().flatMap(y -> y.apply(p1.snd()).map(p2 ->
|
||||
new Pair<>(new Pair<>(p1.fst(), p2.fst()), p2.snd()))))); } );
|
||||
}
|
||||
|
||||
|
||||
trans (p, f) {
|
||||
return () -> p.apply().map(x -> (toks -> x.apply(toks).map(pr -> new Pair<>(f.apply(pr.fst()), pr.snd() ) ) ) );
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
import java.util.stream.Stream;
|
||||
//import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.io.PrintStream;
|
||||
import java.lang.System;
|
||||
|
||||
//import java.lang.String;
|
||||
import java.lang.Boolean;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import Pair;
|
||||
import Kombinatoren_failure;
|
||||
|
||||
public class Kombinatoren_Satisfy {
|
||||
|
||||
kb = new Kombinatoren_failure();
|
||||
|
||||
satisfy(cond) {
|
||||
// return () -> Stream.of (newToks -> new Kombinatoren_failure().failure().apply().map(x -> x.apply(newToks)));
|
||||
//}
|
||||
return () -> Stream.of (toks -> {
|
||||
if(toks.isEmpty()) {
|
||||
return new ArrayList<>().stream();
|
||||
}
|
||||
else
|
||||
{
|
||||
var fst = toks.getFirst();
|
||||
if (cond.apply(fst))
|
||||
{
|
||||
//var newToks = List.copyOf(toks.subList(1, toks.size()));
|
||||
var newToks = new ArrayList<>(toks);
|
||||
return newToks.removeFirst();
|
||||
kb.getContent(
|
||||
kb.succeed(fst).apply().map(x -> x.apply(newToks))
|
||||
);
|
||||
// ;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
);
|
||||
}
|
||||
/* () -> Stream.of (toks -> {
|
||||
//System.out.println(toks);
|
||||
if(toks.isEmpty())
|
||||
{
|
||||
return new ArrayList<>().stream();
|
||||
}
|
||||
else {
|
||||
var fst = toks.getFirst();
|
||||
if (cond.apply(fst))
|
||||
{
|
||||
var newToks = List.copyOf(toks.subList(1, toks.size()));
|
||||
//System.out.println("satisfy ok " + fst.toString());
|
||||
//return get(succeed(fst).apply().map(x -> x.apply(newToks)));
|
||||
}
|
||||
else {
|
||||
//System.out.println("satisfy failure " + fst.toString());
|
||||
//return get(failure().apply()).apply(toks);
|
||||
}
|
||||
return new ArrayList<>().stream();
|
||||
} } ) ;
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import java.util.stream.Stream;
|
||||
import Pair;
|
||||
//import java.util.function.Function;
|
||||
|
||||
public class Kombinatoren_Trans {
|
||||
|
||||
|
||||
trans (p, f) {
|
||||
return () -> p.apply().map(x -> (toks -> x.apply(toks).map(pr -> new Pair<>(f.apply(pr.fst()), pr.snd() ) ) ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.io.PrintStream;
|
||||
import java.lang.System;
|
||||
import java.util.Optional;
|
||||
|
||||
import java.lang.String;
|
||||
import java.lang.Boolean;
|
||||
import java.util.function.Function;
|
||||
|
||||
import Pair;
|
||||
|
||||
|
||||
public class Kombinatoren_failure {
|
||||
public getContent(s) {
|
||||
return s.toList().getFirst();
|
||||
}
|
||||
|
||||
public failure() {
|
||||
return () -> Stream.of(
|
||||
toks -> new ArrayList<>().stream());
|
||||
}
|
||||
public succeed( value) {
|
||||
return () -> Stream.of(toks -> {
|
||||
//System.out.println("succeed");
|
||||
var al = new ArrayList<>();
|
||||
al.add(new Pair<>(value, toks));
|
||||
//al.forEach(x -> { System.out.println(x.toString());});
|
||||
return al.stream();});
|
||||
}
|
||||
|
||||
parser(p, inp) {
|
||||
return p.map(y -> y.apply(
|
||||
inp.chars().mapToObj(c -> (char) c)
|
||||
.collect(Collectors.toList())))
|
||||
.flatMap(x -> x)
|
||||
.filter(x -> x.snd().isEmpty())
|
||||
.findFirst()
|
||||
.get()
|
||||
.fst();
|
||||
}
|
||||
|
||||
}
|
||||
/*
|
||||
|
||||
satisfy(cond) {
|
||||
return newToks -> failure().apply().map(x -> x.apply(newToks));
|
||||
/*
|
||||
return () -> Stream.of (toks -> {
|
||||
if(toks.isEmpty()) {
|
||||
return new ArrayList<>().stream();
|
||||
}
|
||||
else {
|
||||
var fst = toks.getFirst();
|
||||
if (cond.apply(fst)) {
|
||||
var newToks = List.copyOf(toks.subList(1, toks.size()));
|
||||
this.getContent(
|
||||
succeed(fst)
|
||||
.apply().map(x -> x.apply(newToks))
|
||||
)
|
||||
;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
);
|
||||
*/
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -1,24 +1,36 @@
|
||||
|
||||
import java.util.Vector;
|
||||
import java.lang.Boolean;
|
||||
import java.lang.Object;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
class Pair<T, U> {
|
||||
T a;
|
||||
U b;
|
||||
|
||||
public Pair() { }
|
||||
public Pair(T a, U b) {
|
||||
this.a = a;
|
||||
this.b = b;
|
||||
}
|
||||
|
||||
public T fst () {
|
||||
return a;
|
||||
}
|
||||
|
||||
public U snd () {
|
||||
return b;
|
||||
class Pair<U, T> {
|
||||
U a;
|
||||
T b;
|
||||
|
||||
make(x) {
|
||||
var ret = new Pair<>();
|
||||
ret.a = x.elementAt(0);
|
||||
ret.b = x.elementAt(1);
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
eq(a, b) {
|
||||
b = a;
|
||||
return a == b;
|
||||
}
|
||||
|
||||
|
||||
compare( p) {
|
||||
return eq(p.a, p.b);
|
||||
//return p.a == p.b;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
void m(Pair<?, ?> p, Vector<?> b)
|
||||
{
|
||||
//this.compare(p); //1, type incorrect
|
||||
this.compare(this.make(b)); //2, OK
|
||||
}
|
||||
*/
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import java.util.*;
|
||||
|
||||
public class Pair<T, U> {
|
||||
T a;
|
||||
U b;
|
||||
|
||||
public Pair() { }
|
||||
public Pair(T a, U b) {
|
||||
System.out.println("Pair a; " + a + " b: " + b);
|
||||
this.a = a;
|
||||
this.b = b;
|
||||
}
|
||||
|
||||
public T fst () {
|
||||
return a;
|
||||
}
|
||||
|
||||
public U snd () {
|
||||
System.out.println("snd b: " + b);
|
||||
return b;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "Pair<"+a.toString()+","+b.toString()+">";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
import java.util.stream.Stream;
|
||||
//import java.util.stream.IntStream;
|
||||
//import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.io.PrintStream;
|
||||
import java.lang.System;
|
||||
import java.util.Optional;
|
||||
import java.lang.Character;
|
||||
import java.lang.String;
|
||||
import java.lang.Boolean;
|
||||
import java.lang.Integer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
//import java.util.function.IntFunction;
|
||||
|
||||
import Pair;
|
||||
|
||||
|
||||
public class Parser {
|
||||
|
||||
|
||||
strToList(s) {
|
||||
var al;
|
||||
al = new ArrayList<>();
|
||||
var i = 0;
|
||||
while (i < s.length()) {
|
||||
al.add(s.charAt(i));
|
||||
i=i+1;
|
||||
}
|
||||
return al;
|
||||
}
|
||||
/*
|
||||
|
||||
parser(p, inp) {
|
||||
return p.map(y -> y.apply(
|
||||
strToList(inp)//chars().mapToObj(c -> (Character) c)
|
||||
//.toList()
|
||||
))
|
||||
|
||||
//.flatMap(x -> x)
|
||||
|
||||
//.filter(x -> x.snd().isEmpty())
|
||||
;
|
||||
/*
|
||||
.findFirst()
|
||||
.get()
|
||||
.fst()
|
||||
|
||||
;
|
||||
}
|
||||
*/
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
satisfy(cond) {
|
||||
return newToks -> failure().apply().map(x -> x.apply(newToks));
|
||||
/*
|
||||
return () -> Stream.of (toks -> {
|
||||
if(toks.isEmpty()) {
|
||||
return new ArrayList<>().stream();
|
||||
}
|
||||
else {
|
||||
var fst = toks.getFirst();
|
||||
if (cond.apply(fst)) {
|
||||
var newToks = List.copyOf(toks.subList(1, toks.size()));
|
||||
this.getContent(
|
||||
succeed(fst)
|
||||
.apply().map(x -> x.apply(newToks))
|
||||
)
|
||||
;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
);
|
||||
*/
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -2,7 +2,7 @@ import java.lang.String;
|
||||
import java.lang.Object;
|
||||
|
||||
public class Bug365{
|
||||
swap(Fun1$$<String, Fun1$$<String, Object>> f){
|
||||
swap(f){
|
||||
return x -> y -> f.apply(y).apply(x);
|
||||
}
|
||||
|
||||
@@ -18,8 +18,4 @@ public class Bug365{
|
||||
var func = x -> y -> z -> x + y + z;
|
||||
return swap(func).apply("A").apply("B").apply("C");
|
||||
}
|
||||
public ex3() {
|
||||
var func = x -> y -> x + y;
|
||||
return swap(func).apply("A").apply("B");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ record Cons<T>(T a , List<T> l ) implements List <T> {}
|
||||
record Empty<T>() implements List <T> {}
|
||||
|
||||
public class Bug380 {
|
||||
public <T> List<T> append(List<T> l1, List<T> l2) {
|
||||
public <T> List<T> append(l1, List<T> l2) {
|
||||
return switch ( l1 ) {
|
||||
case Cons(e, rest) -> new Cons<>(e, append(rest, l2)); //::Typ TPH A
|
||||
case Empty() -> l2;//::TPH B
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import java.lang.String;
|
||||
|
||||
public class Bug389 {
|
||||
public swap(f) {
|
||||
return x -> y -> f.apply(y).apply(x);
|
||||
}
|
||||
public swap(f) {
|
||||
return x -> y -> z -> f.apply(z).apply(x).apply(y);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import Bug389;
|
||||
import java.util.List;
|
||||
import java.lang.String;
|
||||
import java.lang.Integer;
|
||||
|
||||
public class Bug389Main {
|
||||
public static main(args) {
|
||||
var func = x -> y -> z -> x + y + z;
|
||||
var swap = new Bug389();
|
||||
swap.swap(func).apply(1).apply(2).apply(3);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import java.lang.String;
|
||||
|
||||
public class Fac {
|
||||
getFac(n) {
|
||||
Double res = 1;
|
||||
var res = 1;
|
||||
var i = 1;
|
||||
while (i <= n) {
|
||||
res = res * i;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import java.lang.String;
|
||||
import java.lang.Integer;
|
||||
|
||||
sealed interface List<T> permits LinkedElem, Elem {}
|
||||
public record LinkedElem<T>(T a, List<T> l) implements List<T>{}
|
||||
public record Elem<T>(T c) implements List<T>{}
|
||||
sealed interface List permits LinkedElem, Elem {}
|
||||
|
||||
|
||||
public record LinkedElem<T>(T a,List l) implements List{}
|
||||
public record Elem<T>(T c) implements List{}
|
||||
|
||||
public class GenericRecordSwitchCase {
|
||||
public main(o) {
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import java.lang.System;
|
||||
import java.lang.String;
|
||||
import java.io.PrintStream;
|
||||
import java.lang.Object;
|
||||
|
||||
public class HelloWorld {
|
||||
public static hello() {
|
||||
System.out.println("Hello World!");
|
||||
System.out.println("Bye World!");
|
||||
System.out.println("The end!");
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
//Grundsaetzlich wird Lazy-Evaluation so realisiert, dass immer beim
|
||||
//Methoden/Konstruktor-Aufruf das Argument in einen Lambda-Ausdruck (Supplier)
|
||||
//eingepackt wird (siehe Aufruf von Cons und Empty in Count und main) und
|
||||
//ein Lazy-Argument mit get ausgerollt wird (siehe Methode rest)
|
||||
|
||||
import java.lang.Integer;
|
||||
import java.lang.String;
|
||||
import java.lang.System;
|
||||
import java.io.PrintStream;
|
||||
|
||||
public sealed interface LazyList permits Empty, Cons {
|
||||
public Integer fst();
|
||||
public LazyList rest();
|
||||
}
|
||||
|
||||
//Der Konstruktor Cons muss lazy sein, deshalb hier Supplier<...>
|
||||
record Cons(Integer x, Fun0$$<LazyList> l) implements LazyList {
|
||||
public Integer fst() { return this.x; }
|
||||
public LazyList rest() { return this.l.apply(); }
|
||||
public String toString() {
|
||||
return "Cons(" + this.x.toString() + ", " + this.l.apply().toString() + ")";
|
||||
}
|
||||
}
|
||||
|
||||
record Empty() implements LazyList {
|
||||
public Integer fst() { return -1;}
|
||||
public LazyList rest() { return null; }
|
||||
}
|
||||
|
||||
|
||||
class Main {
|
||||
static LazyList Count(int i) { return new Cons(i, () -> Count(i+1)); }
|
||||
|
||||
public static void main(args) {
|
||||
System.out.println(new Cons(1, () -> new Cons(2, () -> new Empty())).fst());
|
||||
System.out.println(Count(1).rest().fst());
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,25 @@
|
||||
public sealed interface List<T> permits Cons, Empty {}
|
||||
sealed interface List<T> permits Cons, Empty {}
|
||||
|
||||
public record Cons<T>(T a, List<T> l) implements List<T> {}
|
||||
public record Empty<T>() implements List<T> {}
|
||||
public record Pair<T1, T2>(T1 a, T2 b) {}
|
||||
public record Tuple<T1, T2>(T1 a, T2 b) {}
|
||||
|
||||
public class PatternMatching {
|
||||
// Anmerkung: Typ muss angegeben werden
|
||||
public <A, B> Cons<Pair<A, B>> zip(Cons(x, xs), Cons(y, ys)) {
|
||||
return new Cons<>(new Pair<>(x, y), zip(xs, ys));
|
||||
public zip(Cons(x, xs), Cons(y, ys)) {
|
||||
return new Cons(new Tuple(x, y), zip(xs, ys));
|
||||
}
|
||||
public zip(Empty(), Empty()) { return new Empty<>(); }
|
||||
public zip(Empty x, Empty y) { return new Empty(); }
|
||||
|
||||
/*public zip(Empty x, Cons y) { return new Empty(); }
|
||||
public zip(Cons x, Empty y) { return new Empty(); }
|
||||
public zip(Empty x, Empty y) { return new Empty(); }
|
||||
*/
|
||||
|
||||
/*
|
||||
Generiert:
|
||||
Cons zip<T>(Cons(T x, Cons xs), Cons(T y, Cons ys))
|
||||
Cons zip<T>(Cons(T x, Cons xs), Cons(T y, Empty ys))
|
||||
Cons zip<T>(Cons(T x, Empty xs), Cons(T y, Cons ys))
|
||||
Cons zip<T>(Cons(T x, Empty xs), Cons(T y, Empty ys))
|
||||
*/
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import java.lang.Integer;
|
||||
import java.lang.Object;
|
||||
|
||||
public interface Base {
|
||||
Object value();
|
||||
}
|
||||
public record R(Integer a) implements Base {
|
||||
public Object value() { return this.a; }
|
||||
}
|
||||
|
||||
public class PatternMatchingCaptures {
|
||||
public test1(Base R(a)@r) {
|
||||
return r.value();
|
||||
}
|
||||
|
||||
public test2(Base R(a)) {
|
||||
return a;
|
||||
}
|
||||
|
||||
public test3(R(a)@r) {
|
||||
return r.a;
|
||||
}
|
||||
|
||||
public test4(R(a)) {
|
||||
return a;
|
||||
}
|
||||
|
||||
public test5(R r) {
|
||||
return r.a;
|
||||
}
|
||||
|
||||
public test6(r) {
|
||||
return r.a;
|
||||
}
|
||||
}
|
||||
@@ -2,24 +2,18 @@ import java.lang.Object;
|
||||
import List;
|
||||
import Cons;
|
||||
import Empty;
|
||||
import Pair;
|
||||
import Tuple;
|
||||
|
||||
public class PatternMatchingJava {
|
||||
public <A, B> Cons<Pair<A, B>> zip(Cons<A> a, Cons<B> b) {
|
||||
public zip(a, b) {
|
||||
switch (a) {
|
||||
case Cons(x, Cons xs) -> {
|
||||
switch (b) {
|
||||
case Cons(y, Cons ys) -> { return new Cons<>(new Pair<>(x, y), zip(xs, ys)); }
|
||||
};
|
||||
}
|
||||
case Cons(x, Empty xs) -> {
|
||||
switch (b) {
|
||||
case Cons(y, Empty ys) -> { return new Cons<>(new Pair<>(x, y), zip(xs, ys)); }
|
||||
case Cons(y, Cons ys) -> { return new Cons<>(new Tuple<>(x, y), zip(xs, ys)); }
|
||||
case Cons(y, Empty()) -> { return new Empty<>(); }
|
||||
};
|
||||
}
|
||||
case Cons(x, Empty()) -> { return new Empty<>(); }
|
||||
};
|
||||
}
|
||||
public <A, B> Empty<Pair<A, B>> zip(Empty<A> a, Empty<B>) {
|
||||
return new Empty<>();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
public sealed interface List<T> permits Cons, Empty {}
|
||||
sealed interface List<T> permits Cons, Empty {}
|
||||
|
||||
public record Cons<T>(T a, List<T> l) implements List<T> {}
|
||||
public record Empty<T>() implements List<T> {}
|
||||
public record Pair<T1, T2>(T1 a, T2 b) {}
|
||||
public record Tuple<T1, T2>(T1 a, T2 b) {}
|
||||
@@ -1,7 +1,7 @@
|
||||
import java.lang.Boolean;
|
||||
import java.lang.Object;
|
||||
|
||||
public sealed interface List<T> permits Cons, Empty {}
|
||||
sealed interface List<T> permits Cons, Empty {}
|
||||
|
||||
public record Cons<T>(T a, List<T> l) implements List<T> {}
|
||||
public record Empty<T>() implements List<T> {}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import java.lang.Integer;
|
||||
import java.lang.Number;
|
||||
|
||||
public record R(Number n) {}
|
||||
|
||||
public class PatternMatchingSpecificity {
|
||||
public m(R(Number n)) { return 0; }
|
||||
public m(R(Integer i)) { return 1; }
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import java.lang.Integer;
|
||||
import java.lang.String;
|
||||
import java.lang.System;
|
||||
import java.lang.Boolean;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import LazyList;
|
||||
import Cons;
|
||||
import Empty;
|
||||
|
||||
public class Primzahlen {
|
||||
static LazyList from(Integer i) { return new Cons(i, () -> from(i+1)); }
|
||||
|
||||
LazyList filter(Fun1$$<Integer, Boolean> p, LazyList l) {
|
||||
return switch(l) {
|
||||
case Empty e -> e;
|
||||
case Cons(Integer x, Fun0$$<LazyList> l1) ->
|
||||
p.apply(x) ? new Cons(x, () -> filter(p, l1.apply())) : filter(p, l1.apply());
|
||||
};
|
||||
}
|
||||
|
||||
/*LazyList filter(Fun1$$<Integer, Boolean> p, Empty()@l) {
|
||||
return l;
|
||||
}
|
||||
|
||||
LazyList filter(Fun1$$<Integer, Boolean> p, Cons(Integer x, Fun0$$<LazyList> l1)) {
|
||||
return p.apply(x) ? new Cons(x, () -> filter(p, l1.apply())) : filter(p, l1.apply());
|
||||
}*/
|
||||
|
||||
LazyList dropMul(Integer x, LazyList xs) {
|
||||
return filter(y -> (y % x != 0), xs);
|
||||
}
|
||||
|
||||
LazyList del(LazyList xs) {
|
||||
return new Cons(xs.fst(), () -> del(dropMul(xs.fst(), xs.rest())));
|
||||
}
|
||||
|
||||
LazyList primes() {
|
||||
return del(from(2));
|
||||
}
|
||||
|
||||
LazyList take(Integer n, LazyList l) {
|
||||
if (n == 0) return new Empty();
|
||||
else return switch (l) {
|
||||
case Empty() -> l;
|
||||
case Cons(Integer x, Fun0$$<LazyList> l1) ->
|
||||
new Cons(x, () -> take(n-1, l1.apply()));
|
||||
};
|
||||
};
|
||||
|
||||
public static void main(args) {
|
||||
System.out.println(new Cons(1, () -> new Cons(2, () -> new Empty())).fst());
|
||||
LazyList l = new Cons(1, () -> new Cons(2, () -> new Cons(2, () -> new Empty())));
|
||||
System.out.println(new Primzahlen().filter(x -> x == 2, l));
|
||||
System.out.println(from(1).rest().fst());
|
||||
Primzahlen pz = new Primzahlen();
|
||||
System.out.println(pz.take(10, pz.from(2)));
|
||||
System.out.println(pz.take(14, pz.primes()));
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,23 @@
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.lang.Integer;
|
||||
import java.lang.String;
|
||||
|
||||
public class Sorting {
|
||||
List<Integer> merge(List<Integer> a, List<Integer> b) {
|
||||
var r = new ArrayList<>();
|
||||
for (var i = 0, j = 0; i < a.size() || j < b.size();)
|
||||
if (j == b.size() || (i < a.size() && a.get(i) <= b.get(j)))
|
||||
r.add(a.get(i++));
|
||||
else r.add(b.get(j++));
|
||||
return r;
|
||||
public class Sorting{
|
||||
merge(a, b){
|
||||
a.addAll(b);
|
||||
return a;
|
||||
}
|
||||
|
||||
split(list) {
|
||||
var mid = list.size() / 2;
|
||||
return List.of(list.subList(0, mid), list.subList(mid, list.size()));
|
||||
}
|
||||
|
||||
public sort(in) {
|
||||
if (in.size() <= 1) return in;
|
||||
var halves = split(in);
|
||||
return merge(sort(halves.get(0)), sort(halves.get(1)));
|
||||
}
|
||||
sort(in){
|
||||
var firstHalf = in;
|
||||
var secondHalf = in;
|
||||
return merge(sort(firstHalf), sort(secondHalf));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
void sort(a){
|
||||
a = merge(a,a);
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
@@ -658,7 +658,7 @@ primaryPattern
|
||||
;
|
||||
|
||||
recordPattern
|
||||
: type=typeType? ctor=typeType recordStructurePattern ('@' identifier)?
|
||||
: typeType recordStructurePattern identifier?
|
||||
//| recordStructurePattern identifier?
|
||||
;
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import de.dhbwstuttgart.core.JavaTXCompiler;
|
||||
import de.dhbwstuttgart.exceptions.NotImplementedException;
|
||||
import de.dhbwstuttgart.parser.scope.JavaClassName;
|
||||
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
|
||||
import de.dhbwstuttgart.syntaxtree.Pattern;
|
||||
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
|
||||
import de.dhbwstuttgart.target.tree.*;
|
||||
import de.dhbwstuttgart.target.tree.expression.*;
|
||||
@@ -350,8 +349,6 @@ public class Codegen {
|
||||
}
|
||||
|
||||
private TargetType largerType(TargetType left, TargetType right) {
|
||||
if (left instanceof TargetExtendsWildcard wc) left = wc.innerType();
|
||||
if (right instanceof TargetExtendsWildcard wc) right = wc.innerType();
|
||||
if (left.equals(TargetType.String) || right.equals(TargetType.String)) {
|
||||
return TargetType.String;
|
||||
} else if (left.equals(TargetType.Double) || right.equals(TargetType.Double)) {
|
||||
@@ -815,9 +812,7 @@ public class Codegen {
|
||||
private static TargetType removeGenerics(TargetType param) {
|
||||
return switch (param) {
|
||||
case null -> null;
|
||||
case TargetFunNType funNType -> new TargetFunNType(funNType.name(),
|
||||
funNType.funNParams().stream().map(Codegen::removeGenerics).toList(), List.of(),
|
||||
funNType.returnArguments(), funNType.isInterface());
|
||||
case TargetFunNType funNType -> new TargetFunNType(funNType.name(), funNType.funNParams().stream().map(Codegen::removeGenerics).toList(), List.of(), funNType.returnArguments());
|
||||
case TargetRefType refType -> new TargetRefType(refType.name());
|
||||
case TargetGenericType targetGenericType -> TargetType.Object;
|
||||
default -> param;
|
||||
@@ -1444,7 +1439,6 @@ public class Codegen {
|
||||
for (var i = 0; i < aSwitch.cases().size(); i++) {
|
||||
mv.visitLabel(caseLabels[i]);
|
||||
var cse = aSwitch.cases().get(i);
|
||||
state.enterScope();
|
||||
|
||||
if (cse.labels().size() == 1) {
|
||||
var label = cse.labels().get(0);
|
||||
@@ -1473,8 +1467,6 @@ public class Codegen {
|
||||
if (cse.isSingleExpression() && aSwitch.isExpression())
|
||||
yieldValue(state, cse.body().statements().get(0).type());
|
||||
if (aSwitch.isExpression()) mv.visitJumpInsn(GOTO, end);
|
||||
|
||||
state.exitScope();
|
||||
}
|
||||
|
||||
mv.visitLabel(defaultLabel);
|
||||
@@ -1506,14 +1498,12 @@ public class Codegen {
|
||||
state.exitScope();
|
||||
}
|
||||
|
||||
private void extractField(State state, TargetType ret, TargetType type, int i, ClassOrInterface clazz) {
|
||||
state.mv.visitTypeInsn(CHECKCAST, type.getInternalName());
|
||||
private void extractField(State state, TargetType type, int i, ClassOrInterface clazz) {
|
||||
if (i >= clazz.getFieldDecl().size())
|
||||
throw new CodeGenException("Couldn't find suitable field accessor for '" + type.name() + "'");
|
||||
var field = clazz.getFieldDecl().get(i);
|
||||
var fieldType = converter.convert(field.getType());
|
||||
state.mv.visitMethodInsn(INVOKEVIRTUAL, type.getInternalName(), field.getName(), "()" + fieldType.toDescriptor(), false);
|
||||
if (ret != null) convertTo(state, fieldType, ret);
|
||||
}
|
||||
|
||||
private void bindPattern(State state, TargetType type, TargetPattern pat, Label start, int index, int depth) {
|
||||
@@ -1568,7 +1558,7 @@ public class Codegen {
|
||||
state.mv.visitVarInsn(ASTORE, local.index);
|
||||
}
|
||||
|
||||
var clazz = findClass(new JavaClassName(cp.ctor().name()));
|
||||
var clazz = findClass(new JavaClassName(cp.type().name()));
|
||||
if (clazz == null) throw new CodeGenException("Class definition for '" + cp.type().name() + "' not found");
|
||||
// TODO Check if class is a Record
|
||||
|
||||
@@ -1576,7 +1566,7 @@ public class Codegen {
|
||||
var subPattern = cp.subPatterns().get(i);
|
||||
|
||||
state.mv.visitInsn(DUP);
|
||||
extractField(state, null, cp.ctor(), i, clazz);
|
||||
extractField(state, cp.type(), i, clazz);
|
||||
|
||||
if (subPattern.type() instanceof TargetRefType || subPattern.type() instanceof TargetExtendsWildcard) {
|
||||
state.mv.visitInsn(DUP);
|
||||
@@ -1669,7 +1659,7 @@ public class Codegen {
|
||||
private void bindLocalVariables(State state, TargetComplexPattern cp, int offset) {
|
||||
state.mv.visitVarInsn(ALOAD, offset);
|
||||
|
||||
var clazz = findClass(new JavaClassName(cp.ctor().name()));
|
||||
var clazz = findClass(new JavaClassName(cp.type().name()));
|
||||
if (clazz == null) throw new CodeGenException("Class definition for '" + cp.type().name() + "' not found");
|
||||
|
||||
for (var i = 0; i < cp.subPatterns().size(); i++) {
|
||||
@@ -1678,7 +1668,7 @@ public class Codegen {
|
||||
if (i < cp.subPatterns().size() - 1)
|
||||
state.mv.visitInsn(DUP);
|
||||
|
||||
extractField(state, subPattern.type(), cp.ctor(), i, clazz);
|
||||
extractField(state, cp.type(), i, clazz);
|
||||
if (subPattern.type() instanceof TargetRefType)
|
||||
state.mv.visitTypeInsn(CHECKCAST, subPattern.type().getInternalName());
|
||||
offset = state.createVariable(subPattern.name(), subPattern.type()).index;
|
||||
@@ -1918,7 +1908,7 @@ public class Codegen {
|
||||
bootstrapArgs[i + 2] = fieldRef;
|
||||
}
|
||||
|
||||
if (clazz.methods().stream().filter(m -> m.getDescriptor().equals("()I") && m.name().equals("hashCode")).findFirst().isEmpty()) { // hashCode
|
||||
{ // hashCode
|
||||
var mv = cw.visitMethod(ACC_PUBLIC, "hashCode", "()I", null, null);
|
||||
mv.visitCode();
|
||||
mv.visitVarInsn(ALOAD, 0);
|
||||
@@ -1927,7 +1917,7 @@ public class Codegen {
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
}
|
||||
if (clazz.methods().stream().filter(m -> m.getDescriptor().equals("(Ljava/lang/Object;)Z") && m.name().equals("equals")).findFirst().isEmpty()) { // equals
|
||||
{ // equals
|
||||
var mv = cw.visitMethod(ACC_PUBLIC, "equals", "(Ljava/lang/Object;)Z", null, null);
|
||||
mv.visitCode();
|
||||
mv.visitVarInsn(ALOAD, 0);
|
||||
@@ -1937,7 +1927,7 @@ public class Codegen {
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
}
|
||||
if (clazz.methods().stream().filter(m -> m.getDescriptor().equals("()Ljava/lang/String;") && m.name().equals("toString")).findFirst().isEmpty()) { // toString
|
||||
{ // toString
|
||||
var mv = cw.visitMethod(ACC_PUBLIC, "toString", "()Ljava/lang/String;", null, null);
|
||||
mv.visitCode();
|
||||
mv.visitVarInsn(ALOAD, 0);
|
||||
|
||||
@@ -33,7 +33,6 @@ class Args {
|
||||
|
||||
public class ConsoleInterface {
|
||||
public static Logger.LogLevel logLevel = Logger.LogLevel.ERROR;
|
||||
public static boolean writeToConsole = true;
|
||||
public static boolean writeLogFiles = false;
|
||||
public static boolean inferTogether = false;
|
||||
public static Optional<String> unifyServerUrl = Optional.empty();
|
||||
|
||||
@@ -5,9 +5,8 @@ import de.dhbwstuttgart.bytecode.Codegen;
|
||||
import de.dhbwstuttgart.bytecode.FunNGenerator;
|
||||
import de.dhbwstuttgart.environment.CompilationEnvironment;
|
||||
import de.dhbwstuttgart.environment.DirectoryClassLoader;
|
||||
import de.dhbwstuttgart.exceptions.CompilerWarning;
|
||||
import de.dhbwstuttgart.exceptions.DebugException;
|
||||
import de.dhbwstuttgart.exceptions.WarningsException;
|
||||
import de.dhbwstuttgart.languageServerInterface.model.LanguageServerTransferObject;
|
||||
import de.dhbwstuttgart.parser.JavaTXParser;
|
||||
import de.dhbwstuttgart.parser.NullToken;
|
||||
import de.dhbwstuttgart.parser.antlr.Java17Parser;
|
||||
@@ -21,10 +20,14 @@ import de.dhbwstuttgart.server.SocketFuture;
|
||||
import de.dhbwstuttgart.server.packet.SetAutoclosePacket;
|
||||
import de.dhbwstuttgart.server.packet.UnifyRequestPacket;
|
||||
import de.dhbwstuttgart.server.packet.UnifyResultPacket;
|
||||
import de.dhbwstuttgart.syntaxtree.*;
|
||||
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
|
||||
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
|
||||
import de.dhbwstuttgart.syntaxtree.Method;
|
||||
import de.dhbwstuttgart.syntaxtree.ParameterList;
|
||||
import de.dhbwstuttgart.syntaxtree.SourceFile;
|
||||
import de.dhbwstuttgart.syntaxtree.GenericDeclarationList;
|
||||
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
|
||||
import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory;
|
||||
import de.dhbwstuttgart.syntaxtree.statement.Block;
|
||||
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
|
||||
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
|
||||
import de.dhbwstuttgart.syntaxtree.type.RefType;
|
||||
@@ -32,12 +35,9 @@ import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
|
||||
import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
|
||||
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
|
||||
import de.dhbwstuttgart.syntaxtree.type.TypeVisitor;
|
||||
import de.dhbwstuttgart.syntaxtree.type.Void;
|
||||
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
|
||||
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
|
||||
import de.dhbwstuttgart.target.generate.GenericsResult;
|
||||
import de.dhbwstuttgart.target.tree.*;
|
||||
import de.dhbwstuttgart.target.tree.type.*;
|
||||
import de.dhbwstuttgart.typeinference.constraints.Constraint;
|
||||
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
|
||||
import de.dhbwstuttgart.typeinference.constraints.Pair;
|
||||
@@ -62,9 +62,7 @@ import de.dhbwstuttgart.typeinference.unify.UnifyTaskModel;
|
||||
|
||||
import de.dhbwstuttgart.util.Logger;
|
||||
import java.io.*;
|
||||
import java.lang.Record;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Array;
|
||||
import java.util.*;
|
||||
@@ -84,9 +82,7 @@ public class JavaTXCompiler {
|
||||
// public static JavaTXCompiler INSTANCE;
|
||||
final CompilationEnvironment environment;
|
||||
Boolean resultmodel = true;
|
||||
|
||||
private final List<File> sources;
|
||||
public final Map<File, SourceFile> sourceFiles = new LinkedHashMap<>();
|
||||
public final Map<File, SourceFile> sourceFiles = new HashMap<>();
|
||||
public final Set<JavaClassName> input = new HashSet<>();
|
||||
|
||||
public volatile UnifyTaskModel usedTasks = new UnifyTaskModel();
|
||||
@@ -104,7 +100,6 @@ public class JavaTXCompiler {
|
||||
public DirectoryClassLoader getClassLoader() {
|
||||
return classLoader;
|
||||
}
|
||||
public final List<CompilerWarning> generatedWarnings = new ArrayList<>();
|
||||
|
||||
public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException {
|
||||
this(Collections.singletonList(sourceFile), List.of(), new File("."), ConsoleInterface.inferTogether);
|
||||
@@ -129,23 +124,7 @@ public class JavaTXCompiler {
|
||||
environment = new CompilationEnvironment(sources, classLoader);
|
||||
classPath = path;
|
||||
this.outputPath = outputPath;
|
||||
this.sources = sources;
|
||||
// INSTANCE = this;
|
||||
}
|
||||
|
||||
public void warn(CompilerWarning warning) {
|
||||
this.generatedWarnings.add(warning);
|
||||
}
|
||||
public void checkWarnings() {
|
||||
for (var warning : this.generatedWarnings) {
|
||||
defaultLogger.error("[Warning] " + warning.getMessage());
|
||||
}
|
||||
if (!generatedWarnings.isEmpty()) {
|
||||
throw new WarningsException(generatedWarnings.size() + " warnings in code, aborting!", this.generatedWarnings);
|
||||
}
|
||||
}
|
||||
|
||||
private List<SourceFileContext> generateSources(List<File> sources) throws IOException, ClassNotFoundException {
|
||||
// TODO This should maybe be moved elsewhere
|
||||
var treeList = new ArrayList<SourceFileContext>(sources.size());
|
||||
for (var s : sources) {
|
||||
@@ -175,7 +154,11 @@ public class JavaTXCompiler {
|
||||
input.add(classRegistry.getName(className));
|
||||
}
|
||||
}
|
||||
return treeList;
|
||||
|
||||
for (var i = 0; i < sources.size(); i++) {
|
||||
parse(treeList.get(i), sources.get(i));
|
||||
}
|
||||
// INSTANCE = this;
|
||||
}
|
||||
|
||||
private void addSourceFile(File file, SourceFile sf) {
|
||||
@@ -439,7 +422,42 @@ public class JavaTXCompiler {
|
||||
return typeInference(List.of(file));
|
||||
}
|
||||
|
||||
public ConstraintSet<?> lastConstraints;
|
||||
public static String constraintSetToDot(ConstraintSet<Pair> c){
|
||||
|
||||
Iterator<String> colors = List.of(
|
||||
"#FF0000", "#FF7F00", "#FFFF00", "#7FFF00", "#00FF00", "#00FF7F", "#00FFFF", "#007FFF",
|
||||
"#0000FF", "#7F00FF", "#FF00FF", "#FF007F", "#BF0000", "#BF5F00", "#BFBF00", "#5FBF00",
|
||||
"#00BF00", "#00BF5F", "#00BFBF", "#005FBF", "#0000BF", "#5F00BF", "#BF00BF", "#BF005F",
|
||||
"#800000", "#804000", "#808000", "#408000", "#008000", "#008040", "#008080", "#004080",
|
||||
"#000080", "#400080", "#800080", "#800040", "#FF4040", "#FF8040", "#FFFF40", "#80FF40",
|
||||
"#40FF40", "#40FF80", "#40FFFF", "#4080FF", "#4040FF", "#8040FF", "#FF40FF", "#FF4080",
|
||||
"#BF4040", "#BF8040", "#BFBF40", "#80BF40", "#40BF40", "#40BF80", "#40BFBF", "#4080BF",
|
||||
"#4040BF", "#8040BF", "#BF40BF", "#BF4080", "#FF8080", "#FFBF80", "#FFFF80", "#BFFF80",
|
||||
"#80FF80", "#80FFBF", "#80FFFF", "#80BFFF", "#8080FF", "#BF80FF", "#FF80FF", "#FF80BF").iterator();
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
sb.append("diagraph G{");
|
||||
|
||||
//and constraints to dot
|
||||
sb.append(c.getUndConstraints().stream().map(Pair::toDot).collect(Collectors.joining("\n")));
|
||||
|
||||
//or constraints to dot
|
||||
for (var orConstSet : c.getOderConstraints()){
|
||||
for(var cons : orConstSet){
|
||||
String color = colors.next();
|
||||
sb.append(cons.stream().map(x -> x.toDot(color)).collect(Collectors.joining("\n")));
|
||||
}
|
||||
}
|
||||
|
||||
sb.append("}");
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String q(String s) {
|
||||
return "\"" + s.replace("\"", "\\\"") + "\"";
|
||||
}
|
||||
|
||||
public List<ResultSet> typeInference(List<File> files) throws ClassNotFoundException, IOException {
|
||||
Set<ClassOrInterface> allClasses = new HashSet<>();
|
||||
@@ -456,12 +474,44 @@ public class JavaTXCompiler {
|
||||
|
||||
TYPE ty = new TYPE(definedClasses, allClasses);
|
||||
var cons = ty.getConstraints();
|
||||
lastConstraints = cons;
|
||||
|
||||
var ANDconstraints = cons.getUndConstraints();
|
||||
var ORConstraints = cons.getOderConstraints();
|
||||
|
||||
var orIterator = ORConstraints.iterator();
|
||||
|
||||
while(orIterator.hasNext()){
|
||||
Set<Constraint<Pair>> y = orIterator.next();
|
||||
if (y.isEmpty()) orIterator.remove();
|
||||
else if (y.size() == 1){
|
||||
ANDconstraints.addAll(y.iterator().next()); // add the OR constraint to the AND constraint since we only have one option
|
||||
orIterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
String dot = constraintSetToDot(cons);
|
||||
|
||||
|
||||
ANDconstraints.forEach(System.out::println);
|
||||
|
||||
for (var orc : ORConstraints){
|
||||
System.out.println();
|
||||
System.out.println("------");
|
||||
System.out.println();
|
||||
for(var hashs : orc){
|
||||
System.out.print(hashs);
|
||||
System.out.print("\n | \n");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Set<Set<UnifyPair>> results = new HashSet<>();
|
||||
PlaceholderRegistry placeholderRegistry = new PlaceholderRegistry();
|
||||
|
||||
Logger logger = new Logger("TypeInference");
|
||||
var logFolder = new File(System.getProperty("user.dir") + "/logFiles/");
|
||||
if (ConsoleInterface.writeLogFiles && !logFolder.mkdirs()) throw new RuntimeException("Could not create directory for log files: " + logFolder);
|
||||
Writer logFile = ConsoleInterface.writeLogFiles ? new FileWriter(new File(logFolder, "log_" + sourceFiles.keySet().iterator().next().getName())) : new OutputStreamWriter(new NullOutputStream());
|
||||
Logger logger = new Logger(logFile, "TypeInference");
|
||||
|
||||
FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses.stream().toList(), logger, classLoader, this, placeholderRegistry);
|
||||
logger.info(finiteClosure.toString());
|
||||
@@ -565,6 +615,87 @@ public class JavaTXCompiler {
|
||||
return results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons), placeholderRegistry)))).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* TEMPORARY - Only for Language Server Usage
|
||||
*/
|
||||
public LanguageServerTransferObject getResultSetAndAbstractSyntax(File file) throws IOException, ClassNotFoundException {
|
||||
var sf = sourceFiles.get(file);
|
||||
if(sf == null){
|
||||
sf = sourceFiles.values().stream().findFirst().get();
|
||||
}
|
||||
Set<ClassOrInterface> allClasses = new HashSet<>();
|
||||
allClasses.addAll(getAvailableClasses(sf));
|
||||
allClasses.addAll(sf.getClasses());
|
||||
var newClasses = CompilationEnvironment.loadDefaultPackageClasses(sf.getPkgName(), file, this).stream().map(ASTFactory::createClass).collect(Collectors.toSet());
|
||||
for (var clazz : newClasses) {
|
||||
// Don't load classes that get recompiled
|
||||
if (sf.getClasses().stream().anyMatch(nf -> nf.getClassName().equals(clazz.getClassName())))
|
||||
continue;
|
||||
if (allClasses.stream().noneMatch(old -> old.getClassName().equals(clazz.getClassName())))
|
||||
allClasses.add(clazz);
|
||||
}
|
||||
|
||||
final ConstraintSet<Pair> cons = getConstraints(file);
|
||||
Set<Set<UnifyPair>> results = new HashSet<>();
|
||||
|
||||
Writer logFile = new OutputStreamWriter(new NullOutputStream());
|
||||
Logger logger = new Logger(logFile, "TypeInferenceAsync");
|
||||
UnifyContext context = new UnifyContext(logger, false, null, usedTasks, defaultClientPlaceholderRegistry);
|
||||
try {
|
||||
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses.stream().toList(), logger, classLoader, this, context.placeholderRegistry());
|
||||
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, cons, context.placeholderRegistry());
|
||||
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
|
||||
UnifyType lhs, rhs;
|
||||
if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
|
||||
((PlaceholderType) lhs).setInnerType(true);
|
||||
((PlaceholderType) rhs).setInnerType(true);
|
||||
}
|
||||
return x;
|
||||
|
||||
};
|
||||
|
||||
|
||||
unifyCons = unifyCons.map(distributeInnerVars);
|
||||
Set<PlaceholderType> varianceTPHold;
|
||||
Set<PlaceholderType> varianceTPH = new HashSet<>();
|
||||
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
|
||||
|
||||
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints();
|
||||
|
||||
if (resultmodel) {
|
||||
/* UnifyResultModel Anfang */
|
||||
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
|
||||
UnifyResultListenerImpl li = new UnifyResultListenerImpl();
|
||||
urm.addUnifyResultListener(li);
|
||||
TypeUnify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
|
||||
generateBytecode(sf, li.getResults());
|
||||
return new LanguageServerTransferObject(li.getResults(), sf, ASTTypePrinter.print(sf), generatedGenerics);
|
||||
}
|
||||
/* UnifyResultModel End */
|
||||
else {
|
||||
Set<Set<UnifyPair>> result = TypeUnify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
|
||||
results.addAll(result);
|
||||
|
||||
results = results.stream().map(x -> {
|
||||
Optional<Set<UnifyPair>> res = new RuleSet(context.placeholderRegistry()).subst(x.stream().map(y -> {
|
||||
if (y.getPairOp() == PairOperator.SMALLERDOTWC)
|
||||
y.setPairOp(PairOperator.EQUALSDOT);
|
||||
return y; // alle Paare a <.? b erden durch a =. b ersetzt
|
||||
}).collect(Collectors.toCollection(HashSet::new)));
|
||||
if (res.isPresent()) {// wenn subst ein Erg liefert wurde was veraendert
|
||||
return new TypeUnifyTask(context).applyTypeUnificationRules(res.get(), finiteClosure);
|
||||
} else
|
||||
return x; // wenn nichts veraendert wurde wird x zurueckgegeben
|
||||
}).collect(Collectors.toCollection(HashSet::new));
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
}
|
||||
generateBytecode(sf, results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons), context.placeholderRegistry())))).collect(Collectors.toList()));
|
||||
return new LanguageServerTransferObject(results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons), context.placeholderRegistry())))).collect(Collectors.toList()), sf, ASTTypePrinter.print(sf), generatedGenerics);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine Variance !=0 hat auf alle Typvariablen in Theta.
|
||||
*
|
||||
@@ -622,7 +753,7 @@ public class JavaTXCompiler {
|
||||
|
||||
public final JavaClassRegistry classRegistry = new JavaClassRegistry();
|
||||
|
||||
private void parse(SourceFileContext tree, File sourceFile) throws IOException, ClassNotFoundException {
|
||||
private void parse(SourceFileContext tree, File sourceFile) throws IOException, java.lang.ClassNotFoundException {
|
||||
SyntaxTreeGenerator generator = new SyntaxTreeGenerator(this, classRegistry, new GenericsRegistry(null), sourceFile.getName());
|
||||
environment.addClassesToRegistry(classRegistry, tree, sourceFile, this);
|
||||
var classes = new ArrayList<ClassOrInterface>();
|
||||
@@ -633,45 +764,29 @@ public class JavaTXCompiler {
|
||||
sf.imports.addAll(generator.imports);
|
||||
}
|
||||
|
||||
public void parseAll() throws IOException, ClassNotFoundException {
|
||||
var treeList = generateSources(sources);
|
||||
for (var i = 0; i < sources.size(); i++) {
|
||||
parse(treeList.get(i), sources.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
public void generateBytecode() throws ClassNotFoundException, IOException {
|
||||
// The compiler has two modes, one is to infer all files together and the other one is to do them in sequence
|
||||
if (inferTogether) {
|
||||
parseAll();
|
||||
|
||||
var files = sourceFiles.keySet().stream().toList();
|
||||
var typeinferenceResult = this.typeInference(files);
|
||||
for (var file : files) {
|
||||
var sf = sourceFiles.get(file);
|
||||
if (sf.isGenerated()) continue;
|
||||
var classes = generateBytecode(sf, typeinferenceResult);
|
||||
checkWarnings();
|
||||
sf.setGenerated();
|
||||
writeClassFile(classes, file);
|
||||
writeClassFile(classes, outputPath == null ? file.getParentFile() : outputPath, outputPath == null);
|
||||
}
|
||||
} else {
|
||||
var treeList = generateSources(sources);
|
||||
for (var i = 0; i < sources.size(); i++) {
|
||||
var file = sources.get(i);
|
||||
parse(treeList.get(i), file);
|
||||
|
||||
for (var file : sourceFiles.keySet()) {
|
||||
var sf = sourceFiles.get(file);
|
||||
if (sf.isGenerated()) continue;
|
||||
var classes = generateBytecode(file);
|
||||
checkWarnings();
|
||||
sf.setGenerated();
|
||||
writeClassFile(classes, file);
|
||||
writeClassFile(classes, outputPath == null ? file.getParentFile() : outputPath, outputPath == null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Map<JavaClassName, byte[]> generateBytecode(File sourceFile) throws ClassNotFoundException, IOException {
|
||||
public Map<JavaClassName, byte[]> generateBytecode(File sourceFile) throws ClassNotFoundException, IOException {
|
||||
var sf = sourceFiles.get(sourceFile);
|
||||
if (sf.isGenerated()) return null;
|
||||
List<ResultSet> typeinferenceResult = this.typeInference(sourceFile);
|
||||
@@ -705,95 +820,11 @@ public class JavaTXCompiler {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO Maybe move this elsewhere it doesn't really belong here
|
||||
private static RefTypeOrTPHOrWildcardOrGeneric toRefType(TargetType type) {
|
||||
return switch(type) {
|
||||
case TargetExtendsWildcard targetExtendsWildcard ->
|
||||
new ExtendsWildcardType(toRefType(targetExtendsWildcard.innerType()), new NullToken());
|
||||
case TargetSuperWildcard targetSuperWildcard ->
|
||||
new SuperWildcardType(toRefType(targetSuperWildcard.innerType()), new NullToken());
|
||||
case TargetGenericType targetGenericType -> new GenericRefType(targetGenericType.name(), new NullToken());
|
||||
case TargetPrimitiveType targetPrimitiveType -> toRefType(TargetType.toWrapper(targetPrimitiveType));
|
||||
case TargetFunNType targetFunNType ->
|
||||
new RefType(new JavaClassName(FunNGenerator.getSuperClassName(targetFunNType.funNParams().size() - 1, targetFunNType.returnArguments())),
|
||||
targetFunNType.funNParams().stream().map(JavaTXCompiler::toRefType).toList(), new NullToken());
|
||||
case TargetSpecializedType targetSpecializedType ->
|
||||
new RefType(new JavaClassName(targetSpecializedType.name()),
|
||||
targetSpecializedType.params().stream().map(JavaTXCompiler::toRefType).toList(), new NullToken()
|
||||
);
|
||||
case null -> new Void(new NullToken());
|
||||
};
|
||||
}
|
||||
|
||||
private static ParameterList toParameterList(List<MethodParameter> params) {
|
||||
return new ParameterList(params.stream().map(mp
|
||||
-> (Pattern) new FormalParameter(mp.pattern().name(), toRefType(mp.pattern().type()), new NullToken())).toList(),
|
||||
new NullToken()
|
||||
);
|
||||
}
|
||||
|
||||
private static GenericDeclarationList toGenerics(Set<TargetGeneric> generics) {
|
||||
return new GenericDeclarationList(
|
||||
generics.stream().map(g
|
||||
-> new GenericTypeVar(g.name(), List.of(toRefType(g.bound())), new NullToken(), new NullToken())
|
||||
).toList(), new NullToken()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* This writes back the compiled target structure into the loadedClasses map so that it can be used
|
||||
* as an input in further processing
|
||||
* @param target
|
||||
*/
|
||||
private void writeBackToClass(TargetStructure target) {
|
||||
var fielddecl = new ArrayList<Field>();
|
||||
for (var field : target.fields()) {
|
||||
fielddecl.add(new Field(field.name(), toRefType(field.type()), field.access(), new NullToken()));
|
||||
}
|
||||
|
||||
var methods = new ArrayList<Method>();
|
||||
for (var method : target.methods()) {
|
||||
methods.add(new Method(method.access(), method.name(), toRefType(method.signature().returnType()),
|
||||
toParameterList(method.signature().parameters()), new Block(new ArrayList<>(), new NullToken()), toGenerics(method.signature().generics()), new NullToken())
|
||||
);
|
||||
}
|
||||
|
||||
var constructors = new ArrayList<Constructor>();
|
||||
for (var ctor : target.constructors()) {
|
||||
constructors.add(new Constructor(ctor.access(), target.getName(), new RefType(target.qualifiedName(), new NullToken()),
|
||||
toParameterList(ctor.parameters()), new Block(new ArrayList<>(), new NullToken()), toGenerics(ctor.generics()), new NullToken())
|
||||
);
|
||||
}
|
||||
|
||||
var isInterface = target instanceof TargetInterface;
|
||||
var generics = new GenericDeclarationList(toGenerics(target.generics()), new NullToken());
|
||||
var superClass = isInterface ? ASTFactory.createObjectType() : (RefType) toRefType(target.superType());
|
||||
var isFunctionalInterface = false; // TODO We might actually want to generate those
|
||||
var implementedInterfaces = target.implementingInterfaces().stream()
|
||||
.map(t -> (RefType) toRefType(t)).toList();
|
||||
List<RefType> permittedSubtypes = null;
|
||||
if (target instanceof TargetInterface tinf && tinf.permittedSubtypes() != null) {
|
||||
permittedSubtypes = tinf.permittedSubtypes().stream().map(t -> (RefType) toRefType(t)).toList();
|
||||
}
|
||||
|
||||
var clazz = new ClassOrInterface(
|
||||
target.modifiers(), target.qualifiedName(),
|
||||
fielddecl, Optional.empty(), Optional.empty(),
|
||||
methods, constructors, generics, superClass,
|
||||
isInterface, isFunctionalInterface, implementedInterfaces,
|
||||
permittedSubtypes, new NullToken(), ""
|
||||
);
|
||||
loadedClasses.put(target.qualifiedName(), clazz);
|
||||
}
|
||||
|
||||
public synchronized Map<JavaClassName, byte[]> generateBytecode(SourceFile sf, List<ResultSet> typeInferenceResult) {
|
||||
this.generatedWarnings.clear();
|
||||
var converter = new ASTToTargetAST(this, typeInferenceResult, sf, classLoader);
|
||||
var generatedClasses = new HashMap<JavaClassName, byte[]>();
|
||||
for (var clazz : sf.getClasses()) {
|
||||
var target = converter.convert(clazz);
|
||||
writeBackToClass(target);
|
||||
var codegen = new Codegen(target, this, converter);
|
||||
var codegen = new Codegen(converter.convert(clazz), this, converter);
|
||||
var code = codegen.generate();
|
||||
generatedClasses.put(clazz.getClassName(), code);
|
||||
}
|
||||
@@ -805,10 +836,6 @@ public class JavaTXCompiler {
|
||||
return generatedClasses;
|
||||
}
|
||||
|
||||
public void writeClassFile(Map<JavaClassName, byte[]> classFiles, File file) throws IOException {
|
||||
writeClassFile(classFiles, outputPath == null ? file.getParentFile() : outputPath, outputPath == null);
|
||||
}
|
||||
|
||||
public synchronized void writeClassFile(Map<JavaClassName, byte[]> classFiles, File path, boolean preserveHierarchy) throws IOException {
|
||||
FileOutputStream output;
|
||||
for (JavaClassName name : classFiles.keySet()) {
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
package de.dhbwstuttgart.exceptions;
|
||||
|
||||
import org.antlr.v4.runtime.Token;
|
||||
|
||||
public class CompilerWarning extends RuntimeException {
|
||||
private final Token offset;
|
||||
|
||||
public CompilerWarning(Token offset, String message) {
|
||||
super(message);
|
||||
this.offset = offset;
|
||||
}
|
||||
|
||||
public Token getOffset() {
|
||||
return this.offset;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,6 @@ package de.dhbwstuttgart.exceptions;
|
||||
public class DebugException extends RuntimeException {
|
||||
|
||||
public DebugException(String message) {
|
||||
super(message);
|
||||
System.err.print(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
package de.dhbwstuttgart.exceptions;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class WarningsException extends RuntimeException {
|
||||
|
||||
public final List<CompilerWarning> compilerWarnings;
|
||||
|
||||
public WarningsException(String message, List<CompilerWarning> warnings) {
|
||||
super(message);
|
||||
this.compilerWarnings = Collections.unmodifiableList(warnings);
|
||||
}
|
||||
}
|
||||
+6
-21
@@ -2,11 +2,8 @@ package de.dhbwstuttgart.languageServerInterface;
|
||||
|
||||
|
||||
import de.dhbwstuttgart.bytecode.Codegen;
|
||||
import de.dhbwstuttgart.core.ConsoleInterface;
|
||||
import de.dhbwstuttgart.core.JavaTXCompiler;
|
||||
import de.dhbwstuttgart.environment.IByteArrayClassLoader;
|
||||
import de.dhbwstuttgart.exceptions.CompilerWarning;
|
||||
import de.dhbwstuttgart.exceptions.WarningsException;
|
||||
import de.dhbwstuttgart.languageServerInterface.model.LanguageServerTransferObject;
|
||||
import de.dhbwstuttgart.parser.scope.JavaClassName;
|
||||
import de.dhbwstuttgart.syntaxtree.SourceFile;
|
||||
@@ -14,7 +11,6 @@ import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
|
||||
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
|
||||
import de.dhbwstuttgart.target.generate.GenericsResult;
|
||||
import de.dhbwstuttgart.target.tree.TargetStructure;
|
||||
import de.dhbwstuttgart.util.Logger;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
import java.io.*;
|
||||
@@ -35,7 +31,7 @@ import java.util.stream.Stream;
|
||||
public class LanguageServerInterface {
|
||||
|
||||
|
||||
public LanguageServerTransferObject getResultSetAndAbstractSyntax(String path, String resetNamesTo) throws IOException, URISyntaxException, ClassNotFoundException {
|
||||
public LanguageServerTransferObject getResultSetAndAbastractSyntax(String path, String resetNamesTo) throws IOException, URISyntaxException, ClassNotFoundException {
|
||||
NameGenerator.resetTo(resetNamesTo);
|
||||
return getResultSetAndAbstractSyntax(path);
|
||||
|
||||
@@ -56,32 +52,21 @@ public class LanguageServerInterface {
|
||||
*/
|
||||
public LanguageServerTransferObject getResultSetAndAbstractSyntax(String pathAsString){
|
||||
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
|
||||
ConsoleInterface.logLevel = Logger.LogLevel.DEBUG;
|
||||
ConsoleInterface.writeLogFiles = true;
|
||||
ConsoleInterface.writeToConsole = false;
|
||||
Logger.resetLogs();
|
||||
|
||||
try {
|
||||
var uri = new URI(pathAsString);
|
||||
var path = Path.of(uri);
|
||||
var file = path.toFile();
|
||||
Files.createDirectories(path.getParent().resolve("out"));
|
||||
var compiler = new JavaTXCompiler(List.of(file), List.of(path.getParent().toFile()), path.getParent().resolve("out").toFile(), true);
|
||||
compiler.parseAll();
|
||||
var compiler = new JavaTXCompiler(List.of(file), List.of(path.getParent().toFile()), path.getParent().resolve("out").toFile(), false);
|
||||
|
||||
List<CompilerWarning> warnings = List.of();
|
||||
var parsedSource = compiler.sourceFiles.get(file);
|
||||
var tiResults = compiler.typeInference(file);
|
||||
var classFiles = compiler.generateBytecode(parsedSource, tiResults);
|
||||
|
||||
try {
|
||||
compiler.checkWarnings();
|
||||
compiler.writeClassFile(classFiles, file);
|
||||
} catch(WarningsException e) {
|
||||
warnings = e.compilerWarnings;
|
||||
}
|
||||
Map<JavaClassName, byte[]> bytecode = compiler.generateBytecode(parsedSource, tiResults);
|
||||
Files.createDirectories(path.getParent().resolve("out"));
|
||||
compiler.writeClassFile(bytecode, path.getParent().resolve("out").toFile(), false);
|
||||
|
||||
return new LanguageServerTransferObject(parsedSource, "", compiler.lastConstraints, compiler.getGeneratedGenerics(), warnings);
|
||||
return new LanguageServerTransferObject(tiResults, parsedSource, "", compiler.getGeneratedGenerics());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e.getMessage(), e);
|
||||
}
|
||||
|
||||
+5
-9
@@ -2,10 +2,8 @@ package de.dhbwstuttgart.languageServerInterface.model;
|
||||
|
||||
|
||||
|
||||
import de.dhbwstuttgart.exceptions.CompilerWarning;
|
||||
import de.dhbwstuttgart.syntaxtree.SourceFile;
|
||||
import de.dhbwstuttgart.target.generate.GenericsResult;
|
||||
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
|
||||
import de.dhbwstuttgart.typeinference.result.ResultSet;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -13,23 +11,21 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class LanguageServerTransferObject {
|
||||
List<ResultSet> resultSets;
|
||||
SourceFile Ast;
|
||||
String printedAst;
|
||||
Map<SourceFile, List<GenericsResult>> generatedGenerics = new HashMap<>();
|
||||
List<CompilerWarning> warnings;
|
||||
ConstraintSet<?> constraints;
|
||||
|
||||
public LanguageServerTransferObject(SourceFile Ast, String printedAst, ConstraintSet<?> constraints, Map<SourceFile, List<GenericsResult>> generatedGenerics, List<CompilerWarning> warnings) {
|
||||
|
||||
public LanguageServerTransferObject(List<ResultSet> resultSets, SourceFile Ast, String printedAst, Map<SourceFile, List<GenericsResult>> generatedGenerics) {
|
||||
this.resultSets = resultSets;
|
||||
this.Ast = Ast;
|
||||
this.printedAst = printedAst;
|
||||
this.constraints = constraints;
|
||||
this.generatedGenerics = generatedGenerics;
|
||||
this.warnings = warnings;
|
||||
}
|
||||
|
||||
public List<ResultSet> getResultSets() {return resultSets;}
|
||||
public SourceFile getAst() {return Ast;}
|
||||
public String getPrintedAst() {return printedAst;}
|
||||
public Map<SourceFile, List<GenericsResult>> getGeneratedGenerics() {return generatedGenerics;}
|
||||
public List<CompilerWarning> getWarnings() { return warnings; };
|
||||
public ConstraintSet<?> getConstraints() { return constraints; };
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ public class FCGenerator {
|
||||
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();
|
||||
|
||||
@@ -149,7 +149,9 @@ public class StatementGenerator {
|
||||
if (fp.typeType() != null) {
|
||||
type = TypeGenerator.convert(fp.typeType(), reg, generics);
|
||||
} else {
|
||||
type = TypePlaceholder.fresh(fp.getStart(), 1, false);
|
||||
type = methodparameters?
|
||||
TypePlaceholder.fresh(fp.getStart(), 1, false)
|
||||
: TypePlaceholder.fresh(fp.getStart(), 1, false);
|
||||
}
|
||||
ret.add(new FormalParameter(paramName, type, fp.getStart()));
|
||||
localVars.put(paramName, type);
|
||||
@@ -482,10 +484,9 @@ public class StatementGenerator {
|
||||
IdentifierContext identifierCtx = recordPatternCtx.identifier();
|
||||
var text = (identifierCtx != null) ? identifierCtx.getText() : null;
|
||||
//Hier evtl. Typ anpassen -> wenn kein Typ bekannt ist push neuen Typ auf Hashtable
|
||||
var ctor = TypeGenerator.convert(recordPatternCtx.ctor, reg, generics);
|
||||
var type = recordPatternCtx.type == null ? ctor : TypeGenerator.convert(recordPatternCtx.type, reg, generics);
|
||||
var type = recordPatternCtx.typeType() == null ? TypePlaceholder.fresh(recordPatternCtx.getStart()) : TypeGenerator.convert(recordPatternCtx.typeType(), reg, generics);
|
||||
if (text != null) localVars.put(text, type);
|
||||
var ret = new RecordPattern(subPattern, text, type, (RefType)ctor, recordPatternCtx.getStart());
|
||||
var ret = new RecordPattern(subPattern, text, type, recordPatternCtx.getStart());
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -699,7 +700,7 @@ public class StatementGenerator {
|
||||
case ConditionalassignexpressionContext condassign:
|
||||
return convert(condassign);
|
||||
default:
|
||||
throw new NotImplementedException(expression.getClass().toString());
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -982,11 +983,8 @@ public class StatementGenerator {
|
||||
} else if (op.getText().equals("!")) {
|
||||
ret = new UnaryExpr(UnaryExpr.Operation.NOT, expr, TypePlaceholder.fresh(op), op);
|
||||
return ret;
|
||||
} else if (op.getText().equals("-")) {
|
||||
ret = new UnaryExpr(UnaryExpr.Operation.MINUS, expr, TypePlaceholder.fresh(op), op);
|
||||
return ret;
|
||||
} else {
|
||||
throw new NotImplementedException(op.getText());
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -204,7 +204,7 @@ public class SyntaxTreeGenerator {
|
||||
Boolean isInterface = false;
|
||||
Boolean isFunctionalInterface = false;
|
||||
List<RefType> implementedInterfaces = new ArrayList<>();
|
||||
List<RefType> permittedSubtypes = null;
|
||||
List<RefType> permittedSubtypes = new ArrayList<>();
|
||||
for (ClassBodyDeclarationContext clsbodydecl : ctx.classBody().classBodyDeclaration()) {
|
||||
convert(clsbodydecl, fielddecl, constructors, methods, name, superClass, generics);
|
||||
}
|
||||
@@ -218,7 +218,7 @@ public class SyntaxTreeGenerator {
|
||||
if ((modifiers & 4096) != 0) {
|
||||
if (!Objects.isNull(ctx.PERMITS())) {
|
||||
// permitted subtypes sind letzte typeList (siehe Grammatikregel 'classDeclaration')
|
||||
permittedSubtypes = new ArrayList<>(convert(ctx.typeList(ctx.typeList().size() - 1), generics));
|
||||
permittedSubtypes.addAll(convert(ctx.typeList(ctx.typeList().size() - 1), generics));
|
||||
} else {
|
||||
// falls sealed modifier ohne 'permits'-List oder umgekehrt
|
||||
throw new NotImplementedException("Invalid sealed class declaration");
|
||||
|
||||
@@ -64,8 +64,6 @@ public class TypeGenerator {
|
||||
switch (typeContext.primitiveType().getText()) {
|
||||
case "boolean":
|
||||
return new RefType(ASTFactory.createClass(Boolean.class).getClassName(), typeContext.getStart());
|
||||
case "char":
|
||||
return new RefType(ASTFactory.createClass(Character.class).getClassName(), typeContext.getStart());
|
||||
case "int":
|
||||
return new RefType(ASTFactory.createClass(Integer.class).getClassName(), typeContext.getStart());
|
||||
case "double":
|
||||
@@ -73,7 +71,7 @@ public class TypeGenerator {
|
||||
case "float":
|
||||
return new RefType(ASTFactory.createClass(Float.class).getClassName(), typeContext.getStart());
|
||||
default:
|
||||
throw new NotImplementedException(typeContext.primitiveType().getText());
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
} else if (!typeContext.LBRACK().isEmpty()) { // ArrayType über eckige Klammer prüfen
|
||||
// JavaTXParser.logger.info(unannTypeContext.getText());
|
||||
|
||||
@@ -14,6 +14,6 @@ import javax.swing.text.html.Option;
|
||||
public class Record extends ClassOrInterface {
|
||||
|
||||
public Record(int modifiers, JavaClassName name, List<Field> fielddecl, Optional<Constructor> fieldInitializations, Optional<Method> staticInitializer, List<Method> methods, List<Constructor> constructors, GenericDeclarationList genericClassParameters, RefType superClass, Boolean isInterface, List<RefType> implementedInterfaces, Token offset, String fileName) {
|
||||
super(modifiers, name, fielddecl, fieldInitializations, staticInitializer, methods, constructors, genericClassParameters, superClass, isInterface, methods.size() == 1 ? true : false, implementedInterfaces, null, offset, fileName);
|
||||
super(modifiers, name, fielddecl, fieldInitializations, staticInitializer, methods, constructors, genericClassParameters, superClass, isInterface, methods.size() == 1 ? true : false, implementedInterfaces, new ArrayList<>(), offset, fileName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package de.dhbwstuttgart.syntaxtree;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import de.dhbwstuttgart.syntaxtree.type.RefType;
|
||||
import org.antlr.v4.runtime.Token;
|
||||
|
||||
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
|
||||
@@ -11,22 +10,21 @@ import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
|
||||
public class RecordPattern extends FormalParameter {
|
||||
|
||||
private final List<Pattern> subPattern;
|
||||
private final RefType ctor;
|
||||
|
||||
public RecordPattern(List<Pattern> subPattern, String name, RefTypeOrTPHOrWildcardOrGeneric type, RefType ctor, Token offset) {
|
||||
public RecordPattern(String name, RefTypeOrTPHOrWildcardOrGeneric type, Token offset) {
|
||||
super(name, type, offset);
|
||||
subPattern = new ArrayList<>();
|
||||
}
|
||||
|
||||
public RecordPattern(List<Pattern> subPattern, String name, RefTypeOrTPHOrWildcardOrGeneric type, Token offset) {
|
||||
super(name, type, offset);
|
||||
this.subPattern = subPattern;
|
||||
this.ctor = ctor;
|
||||
}
|
||||
|
||||
public List<Pattern> getSubPattern() {
|
||||
return this.subPattern;
|
||||
}
|
||||
|
||||
public RefType getCtor() {
|
||||
return ctor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(ASTVisitor visitor) {
|
||||
visitor.visit(this);
|
||||
|
||||
@@ -229,6 +229,9 @@ public class ASTFactory {
|
||||
public static Method createMethod(java.lang.reflect.Method jreMethod, String signature, java.lang.Class inClass, Boolean isInherited, Boolean isImplemented) {
|
||||
String name = jreMethod.getName();
|
||||
RefTypeOrTPHOrWildcardOrGeneric returnType;
|
||||
if (inClass.getName().equals("Swap")){
|
||||
System.out.println();
|
||||
}
|
||||
Type jreRetType;
|
||||
if (jreMethod.getGenericReturnType() != null) {
|
||||
jreRetType = jreMethod.getGenericReturnType();
|
||||
|
||||
@@ -27,10 +27,9 @@ public class MethodCall extends Statement
|
||||
public RefTypeOrTPHOrWildcardOrGeneric receiverType;
|
||||
|
||||
//sind Tphs, repraesentieren im Resultset die Signatur der aufgerufenen Methoden, letztes Element ist der Returntyp
|
||||
public final ArrayList<TypePlaceholder> signature;
|
||||
public int modifiers;
|
||||
public final ArrayList<TypePlaceholder> signature;
|
||||
|
||||
public MethodCall(RefTypeOrTPHOrWildcardOrGeneric retType, Receiver receiver, String methodName, ArgumentList argumentList,
|
||||
public MethodCall(RefTypeOrTPHOrWildcardOrGeneric retType, Receiver receiver, String methodName, ArgumentList argumentList,
|
||||
RefTypeOrTPHOrWildcardOrGeneric receiverType, ArrayList<TypePlaceholder> signature, Token offset){
|
||||
super(retType,offset);
|
||||
this.arglist = argumentList;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,9 +0,0 @@
|
||||
package de.dhbwstuttgart.target.generate;
|
||||
|
||||
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class DiscardResultSet extends RuntimeException {
|
||||
public DiscardResultSet() {}
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import java.util.stream.Stream;
|
||||
public abstract class GenerateGenerics implements IGenerics {
|
||||
|
||||
private final JavaTXCompiler compiler;
|
||||
private final ResultSet constraints;
|
||||
|
||||
public class TPH {
|
||||
private final TypePlaceholder wrap;
|
||||
@@ -130,7 +129,7 @@ public abstract class GenerateGenerics implements IGenerics {
|
||||
final Map<Method, Set<Pair>> computedGenericsOfMethods = new HashMap<>();
|
||||
final Map<ClassOrInterface, Set<Pair>> computedGenericsOfClasses = new HashMap<>();
|
||||
|
||||
final Map<Method, Set<TPH>> usedTPHsOfMethodSignatures = new HashMap<>();
|
||||
final Map<Method, Set<TPH>> usedTPHsOfMethods = new HashMap<>();
|
||||
final Map<Method, Set<Pair>> familyOfMethods = new HashMap<>();
|
||||
|
||||
final Set<PairLT> simplifiedConstraints = new HashSet<>();
|
||||
@@ -139,7 +138,6 @@ public abstract class GenerateGenerics implements IGenerics {
|
||||
|
||||
GenerateGenerics(JavaTXCompiler compiler, ResultSet constraints) {
|
||||
this.compiler = compiler;
|
||||
this.constraints = constraints;
|
||||
for (var constraint : constraints.results) {
|
||||
if (constraint instanceof PairTPHsmallerTPH p) {
|
||||
Target.logger.info(p.left + " " + p.left.getVariance());
|
||||
@@ -585,7 +583,7 @@ public abstract class GenerateGenerics implements IGenerics {
|
||||
referenced.addAll(typeVariablesOfClass);
|
||||
|
||||
generics(owner, method, result, referenced);
|
||||
usedTPHsOfMethodSignatures.put(method, usedTphs);
|
||||
usedTPHsOfMethods.put(method, usedTphs);
|
||||
|
||||
normalize(result, classGenerics, usedTphs);
|
||||
|
||||
@@ -784,7 +782,7 @@ public abstract class GenerateGenerics implements IGenerics {
|
||||
}
|
||||
doIterationForMethods(classOrInterface);
|
||||
for (var method : classOrInterface.getMethods()) {
|
||||
var usedTPHs = usedTPHsOfMethodSignatures.get(method);
|
||||
var usedTPHs = usedTPHsOfMethods.get(method);
|
||||
if (usedTPHs != null)
|
||||
referenced.addAll(usedTPHs);
|
||||
}
|
||||
@@ -983,11 +981,6 @@ public abstract class GenerateGenerics implements IGenerics {
|
||||
} while (foundInfima);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultSet getResultSet() {
|
||||
return this.constraints;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypePlaceholder getEqualType(TypePlaceholder tph) {
|
||||
return this.equality.getOrDefault(tph, tph);
|
||||
@@ -1008,9 +1001,7 @@ public abstract class GenerateGenerics implements IGenerics {
|
||||
public TargetType getTargetType(RefTypeOrTPHOrWildcardOrGeneric in) {
|
||||
if (in instanceof TypePlaceholder tph) {
|
||||
if (equality.containsKey(tph)) {
|
||||
var tph2 = equality.get(tph);
|
||||
// Sanity check, they should not be equal!
|
||||
if (!Objects.equals(in, tph2)) return getTargetType(tph2);
|
||||
return getTargetType(equality.get(tph));
|
||||
}
|
||||
var type = concreteTypes.get(new TPH(tph));
|
||||
if (type == null) return new TargetGenericType(tph.getName());
|
||||
|
||||
@@ -15,10 +15,6 @@ public class GenericsResult {
|
||||
this.generics = generics;
|
||||
}
|
||||
|
||||
public IGenerics getGenerics() {
|
||||
return this.generics;
|
||||
}
|
||||
|
||||
public GenericsResultSet get(ClassOrInterface clazz) {
|
||||
var generics = this.generics.generics(clazz);
|
||||
return new GenericsResultSet(generics, this.generics);
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package de.dhbwstuttgart.target.generate;
|
||||
|
||||
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetType;
|
||||
import de.dhbwstuttgart.typeinference.result.PairTPHequalRefTypeOrWildcardType;
|
||||
import de.dhbwstuttgart.typeinference.result.PairTPHsmallerTPH;
|
||||
import de.dhbwstuttgart.typeinference.result.ResultPair;
|
||||
import org.antlr.v4.codegen.model.decl.ContextRuleListIndexedGetterDecl;
|
||||
import org.jspecify.annotations.NonNull;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@@ -20,12 +18,7 @@ public class GenericsResultSet extends AbstractSet<GenerateGenerics.Pair> {
|
||||
this.generics = generics;
|
||||
}
|
||||
|
||||
public IGenerics getGenerics() {
|
||||
return this.generics;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public Iterator<GenerateGenerics.Pair> iterator() {
|
||||
return backing.iterator();
|
||||
}
|
||||
@@ -35,8 +28,17 @@ public class GenericsResultSet extends AbstractSet<GenerateGenerics.Pair> {
|
||||
return backing.size();
|
||||
}
|
||||
|
||||
public Optional<GenerateGenerics.Pair> getResultPairFor(TypePlaceholder tph) {
|
||||
public Optional<ResultPair<?, ?>> getResultPairFor(TypePlaceholder tph) {
|
||||
var tph2 = generics.getEqualType(tph);
|
||||
return this.stream().filter(pair -> pair.left.resolve().equals(tph2)).findFirst();
|
||||
return this.stream().filter(pair -> {
|
||||
return pair.left.resolve().equals(tph2);
|
||||
}).findFirst().map(pair -> {
|
||||
ResultPair<?, ?> res = null;
|
||||
if (pair instanceof GenerateGenerics.PairLT lt)
|
||||
res = new PairTPHsmallerTPH(lt.left.resolve(), lt.right.resolve());
|
||||
else if (pair instanceof GenerateGenerics.PairEQ eq)
|
||||
res = new PairTPHequalRefTypeOrWildcardType(eq.left.resolve(), eq.right);
|
||||
return res;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import de.dhbwstuttgart.syntaxtree.Method;
|
||||
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
|
||||
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetType;
|
||||
import de.dhbwstuttgart.typeinference.result.ResultSet;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@@ -20,6 +19,4 @@ public interface IGenerics {
|
||||
TypePlaceholder getEqualType(TypePlaceholder tph);
|
||||
|
||||
TargetType getTargetType(RefTypeOrTPHOrWildcardOrGeneric in);
|
||||
|
||||
ResultSet getResultSet();
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
|
||||
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetGenericType;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetType;
|
||||
import de.dhbwstuttgart.typeinference.result.ResultSet;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@@ -58,9 +57,4 @@ public class OverlayGenerics implements IGenerics {
|
||||
}
|
||||
return ASTToTargetAST.convert(in, this, converter.compiler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultSet getResultSet() {
|
||||
return wrapped.getResultSet();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package de.dhbwstuttgart.target.generate;
|
||||
|
||||
import com.google.common.collect.Iterables;
|
||||
import de.dhbwstuttgart.core.JavaTXCompiler;
|
||||
import de.dhbwstuttgart.exceptions.DebugException;
|
||||
import de.dhbwstuttgart.exceptions.NotImplementedException;
|
||||
@@ -217,10 +216,6 @@ public class StatementToTargetExpression implements ASTVisitor {
|
||||
return ASTToTargetAST.findMethod(converter.compiler.getClass(className), name, args, generics, compiler);
|
||||
}
|
||||
|
||||
Optional<Method> findMethod(JavaClassName className, String name, List<TargetType> args, JavaTXCompiler compiler) {
|
||||
return ASTToTargetAST.findMethod(converter.compiler.getClass(className), name, args, compiler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(MethodCall methodCall) {
|
||||
var receiverType = converter.convert(methodCall.receiver.getType(), generics);
|
||||
@@ -231,8 +226,6 @@ public class StatementToTargetExpression implements ASTVisitor {
|
||||
var argList = methodCall.signature.stream().map(sig -> converter.convert(sig, generics)).toList();
|
||||
argList = argList.subList(0, argList.size() - 1);
|
||||
|
||||
var receiverClass = converter.compiler.getClass(receiverName);
|
||||
|
||||
Method foundMethod = null;
|
||||
var isStatic = false;
|
||||
var isInterface = true;
|
||||
@@ -244,6 +237,7 @@ public class StatementToTargetExpression implements ASTVisitor {
|
||||
converter.addSignaturePair(methodCall.signatureArguments().get(i), methodCall.arglist.getArguments().get(i).getType());
|
||||
}
|
||||
|
||||
var receiverClass = converter.compiler.getClass(receiverName);
|
||||
if (methodCall.receiver instanceof ExpressionReceiver expressionReceiver && expressionReceiver.expr instanceof This) {
|
||||
if (receiverClass == null) throw new DebugException("Class " + receiverName + " does not exist!");
|
||||
var thisMethod = ASTToTargetAST.findMethod(receiverClass, methodCall.name, signature, generics, converter.compiler);
|
||||
@@ -252,60 +246,18 @@ public class StatementToTargetExpression implements ASTVisitor {
|
||||
} else if (!isFunNType) {
|
||||
receiverClass = converter.compiler.getClass(receiverName);
|
||||
if (receiverClass == null) throw new DebugException("Class " + receiverName + " does not exist!");
|
||||
foundMethod = findMethod(receiverName, methodCall.name, signature, converter.compiler).orElseThrow(
|
||||
() -> new DebugException("Method " + methodCall.name + " not found (" + signature + ") on class " + receiverName)
|
||||
);
|
||||
foundMethod = findMethod(receiverName, methodCall.name, signature, generics, converter.compiler).orElseThrow();
|
||||
}
|
||||
|
||||
if (!isFunNType) {
|
||||
// NOTE Not using the direct conversion method on converter to bypass adding the TPH to the used TPH list
|
||||
returnType = ASTToTargetAST.convert(foundMethod.getReturnType(), generics, converter.compiler);
|
||||
argList = foundMethod.getParameterList().getFormalparalist().stream().map(e -> ASTToTargetAST.convert(e.getType(), generics, converter.compiler)).toList();
|
||||
returnType = converter.convert(foundMethod.getReturnType(), generics);
|
||||
argList = foundMethod.getParameterList().getFormalparalist().stream().map(e -> converter.convert(e.getType(), generics)).toList();
|
||||
isStatic = Modifier.isStatic(foundMethod.modifier);
|
||||
isPrivate = Modifier.isPrivate(foundMethod.modifier);
|
||||
isInterface = receiverClass.isInterface();
|
||||
}
|
||||
|
||||
// Filter out every case that has a different method signature for the current method
|
||||
// We only want to throw out cases when the method signature matches
|
||||
var conflicitGenerics = new ArrayList<ASTToTargetAST.Generics>();
|
||||
|
||||
if (converter.getCurrentMethod() != null) {
|
||||
var params = converter.convert(converter.getCurrentMethod().getParameterList(), generics);
|
||||
for (var g2 : converter.all) if (g2.javaGenerics() != generics) {
|
||||
var newParams = converter.convert(converter.getCurrentMethod().getParameterList(), g2.javaGenerics());
|
||||
if (Objects.equals(params, newParams)) conflicitGenerics.add(g2);
|
||||
}
|
||||
}
|
||||
|
||||
// If one of the receiver types is a super type of this one AND there is a method defined that matches the parameters, we discard this result
|
||||
if (!isStatic && receiverType instanceof TargetRefType) {
|
||||
for (var g2 : conflicitGenerics) {
|
||||
var otherReceiver = converter.convert(methodCall.receiver.getType(), g2.javaGenerics());
|
||||
if (!Objects.equals(receiverType, otherReceiver) && converter.isSubtype(receiverType, otherReceiver)) {
|
||||
ClassOrInterface clazz = converter.compiler.getClass(new JavaClassName(otherReceiver.name()));
|
||||
if (clazz != null) {
|
||||
var optMethod = ASTToTargetAST.findMethod(clazz, methodCall.name, argList, converter.compiler);
|
||||
if (optMethod.isPresent()) {
|
||||
throw new DiscardResultSet();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Look at the signature in all result sets and check if a more specific insertion exists.
|
||||
// If so, discard this result set by throwing an exception
|
||||
for (var g2 : conflicitGenerics) {
|
||||
for (var tph : Iterables.concat(methodCall.signatureArguments())) {
|
||||
var currentType = converter.convert(tph, generics);
|
||||
var type = converter.convert(tph, g2.javaGenerics());
|
||||
if (!Objects.equals(type, currentType) && converter.isSubtype(type, currentType)) {
|
||||
throw new DiscardResultSet();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//System.out.println(argList);
|
||||
result = new TargetMethodCall(
|
||||
converter.convert(methodCall.getType(), generics), returnType, argList,
|
||||
converter.convert(methodCall.receiver, generics),
|
||||
@@ -653,7 +605,6 @@ public class StatementToTargetExpression implements ASTVisitor {
|
||||
@Override
|
||||
public void visit(RecordPattern aRecordPattern) {
|
||||
result = new TargetComplexPattern(
|
||||
converter.convert(aRecordPattern.getCtor(), generics),
|
||||
converter.convert(aRecordPattern.getType(), generics),
|
||||
aRecordPattern.getName(),
|
||||
aRecordPattern.getSubPattern().stream().map(x -> (TargetPattern) converter.convert(x, generics)).toList()
|
||||
|
||||
@@ -3,9 +3,4 @@ package de.dhbwstuttgart.target.tree;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetType;
|
||||
|
||||
public record TargetGeneric(String name, TargetType bound) {
|
||||
@Override
|
||||
public String toString() {
|
||||
if (bound.equals(TargetType.Object)) return "'" + name;
|
||||
else return "'" + name + " < " + bound;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
package de.dhbwstuttgart.target.tree;
|
||||
|
||||
import de.dhbwstuttgart.parser.scope.JavaClassName;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetRefType;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetType;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public record TargetInterface(int modifiers, JavaClassName qualifiedName, Set<TargetGeneric> generics, Set<TargetGeneric> txGenerics, List<TargetMethod> methods, List<TargetType> implementingInterfaces, TargetMethod staticConstructor, List<TargetRefType> permittedSubtypes) implements TargetStructure {
|
||||
public record TargetInterface(int modifiers, JavaClassName qualifiedName, Set<TargetGeneric> generics, Set<TargetGeneric> txGenerics, List<TargetMethod> methods, List<TargetType> implementingInterfaces, TargetMethod staticConstructor) implements TargetStructure {
|
||||
@Override
|
||||
public TargetType superType() {
|
||||
return null;
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
package de.dhbwstuttgart.target.tree;
|
||||
|
||||
import de.dhbwstuttgart.syntaxtree.Method;
|
||||
import de.dhbwstuttgart.target.generate.IGenerics;
|
||||
import de.dhbwstuttgart.target.tree.expression.TargetBlock;
|
||||
import de.dhbwstuttgart.target.tree.expression.TargetPattern;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetType;
|
||||
@@ -11,11 +9,7 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
public record TargetMethod(int access, String name, TargetBlock block, Signature signature, Signature txSignature, Method base, IGenerics generics) {
|
||||
public TargetMethod(int access, String name, TargetBlock block, Signature signature, Signature txSignature) {
|
||||
this(access, name, block, signature, txSignature, null, null);
|
||||
}
|
||||
|
||||
public record TargetMethod(int access, String name, TargetBlock block, Signature signature, Signature txSignature) {
|
||||
public record Signature(Set<TargetGeneric> generics, List<MethodParameter> parameters, TargetType returnType) {
|
||||
public String getSignature() {
|
||||
return TargetMethod.getSignature(generics, parameters, returnType);
|
||||
|
||||
@@ -4,15 +4,15 @@ import de.dhbwstuttgart.target.tree.type.TargetType;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record TargetComplexPattern(TargetType ctor, TargetType type, String name, List<TargetPattern> subPatterns) implements TargetPattern {
|
||||
public record TargetComplexPattern(TargetType type, String name, List<TargetPattern> subPatterns) implements TargetPattern {
|
||||
@Override
|
||||
public TargetComplexPattern withType(TargetType type) {
|
||||
return new TargetComplexPattern(ctor, type, name, subPatterns);
|
||||
return new TargetComplexPattern(type, name, subPatterns);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TargetComplexPattern withName(String name) {
|
||||
return new TargetComplexPattern(ctor, type, name, subPatterns);
|
||||
return new TargetComplexPattern(type, name, subPatterns);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -3,17 +3,16 @@ package de.dhbwstuttgart.target.tree.type;
|
||||
import de.dhbwstuttgart.bytecode.FunNGenerator;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record TargetFunNType(String name, List<TargetType> funNParams, List<TargetType> params, int returnArguments, boolean isInterface) implements TargetSpecializedType {
|
||||
public record TargetFunNType(String name, List<TargetType> funNParams, List<TargetType> params, int returnArguments) implements TargetSpecializedType {
|
||||
|
||||
public static TargetFunNType fromParams(List<TargetType> params, int returnArguments, boolean isInterface) {
|
||||
return fromParams(params, params, returnArguments, isInterface);
|
||||
public static TargetFunNType fromParams(List<TargetType> params, int returnArguments) {
|
||||
return fromParams(params, params, returnArguments);
|
||||
}
|
||||
|
||||
public static TargetFunNType fromParams(List<TargetType> params, List<TargetType> realParams, int returnArguments, boolean isInterface) {
|
||||
public static TargetFunNType fromParams(List<TargetType> params, List<TargetType> realParams, int returnArguments) {
|
||||
var name = FunNGenerator.getSpecializedClassName(FunNGenerator.getArguments(params), FunNGenerator.getReturnType(params));
|
||||
return new TargetFunNType(name, params, realParams, returnArguments, isInterface);
|
||||
return new TargetFunNType(name, params, realParams, returnArguments);
|
||||
}
|
||||
|
||||
public String toMethodDescriptor() {
|
||||
@@ -40,9 +39,4 @@ public record TargetFunNType(String name, List<TargetType> funNParams, List<Targ
|
||||
var args = FunNGenerator.getArguments(funNParams);
|
||||
return "LFun" + args.size() + "$$" + TargetSpecializedType.signatureParameters(funNParams) + ";";
|
||||
}
|
||||
|
||||
public boolean equals(Object other) {
|
||||
if (!(other instanceof TargetFunNType otfn)) return false;
|
||||
return Objects.equals(name, otfn.name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,14 +187,14 @@ class TypeToInsertString implements ResultSetVisitor{
|
||||
|
||||
@Override
|
||||
public void visit(TypePlaceholder typePlaceholder) {
|
||||
GenerateGenerics.Pair resultPair = null;
|
||||
ResultPair<?, ?> resultPair = null;
|
||||
if (constraints != null)
|
||||
resultPair = constraints.getResultPairFor(typePlaceholder).orElse(null);
|
||||
if (resultPair == null)
|
||||
resultPair = classConstraints.getResultPairFor(typePlaceholder).orElse(null);
|
||||
|
||||
if (resultPair != null)
|
||||
insert += resultPair.left.toString();
|
||||
insert += ((TypePlaceholder)resultPair.getLeft()).getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -85,11 +85,12 @@ public class Constraint<A extends IConstraintElement> extends HashSet<A> impleme
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return super.toString() + "\nisInherited = " + isInherited
|
||||
+ " isOveridden = " + isImplemented
|
||||
+ " msc[" + methodSignatureConstraint.size() + "] = " + methodSignatureConstraint
|
||||
//" + extendsContraint: " + (extendConstraint != null ? extendConstraint.toStringBase() : "null" )
|
||||
+ "\n";
|
||||
return super.toString();
|
||||
// + "\nisInherited = " + isInherited
|
||||
// + " isOveridden = " + isImplemented
|
||||
// + " msc[" + methodSignatureConstraint.size() + "] = " + methodSignatureConstraint
|
||||
// //" + extendsContraint: " + (extendConstraint != null ? extendConstraint.toStringBase() : "null" )
|
||||
// + "\n";
|
||||
}
|
||||
|
||||
public String toStringBase() {
|
||||
|
||||
@@ -4,6 +4,7 @@ import de.dhbwstuttgart.server.packet.dataContainers.ISerializableData;
|
||||
import de.dhbwstuttgart.server.packet.dataContainers.KeyStorage;
|
||||
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialMap;
|
||||
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@@ -13,58 +14,60 @@ import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
|
||||
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
|
||||
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
|
||||
|
||||
import static de.dhbwstuttgart.core.JavaTXCompiler.q;
|
||||
|
||||
|
||||
public class Pair implements Serializable, IConstraintElement, ISerializableData {
|
||||
public final RefTypeOrTPHOrWildcardOrGeneric TA1;
|
||||
public final RefTypeOrTPHOrWildcardOrGeneric TA2;
|
||||
public final RefTypeOrTPHOrWildcardOrGeneric TA1;
|
||||
public final RefTypeOrTPHOrWildcardOrGeneric TA2;
|
||||
|
||||
private SourceLoc location;
|
||||
private SourceLoc location;
|
||||
|
||||
private PairOperator eOperator = PairOperator.SMALLER;
|
||||
private boolean noUnification = false;
|
||||
private PairOperator eOperator = PairOperator.SMALLER;
|
||||
private boolean noUnification = false;
|
||||
|
||||
|
||||
private Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2) {
|
||||
this.TA1 = TA1;
|
||||
this.TA2 = TA2;
|
||||
if (TA1 == null || TA2 == null)
|
||||
throw new NullPointerException();
|
||||
eOperator = PairOperator.SMALLER;
|
||||
}
|
||||
private Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2) {
|
||||
this.TA1 = TA1;
|
||||
this.TA2 = TA2;
|
||||
if (TA1 == null || TA2 == null)
|
||||
throw new NullPointerException();
|
||||
eOperator = PairOperator.SMALLER;
|
||||
}
|
||||
|
||||
public Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2, PairOperator eOp) {
|
||||
// Konstruktor
|
||||
this(TA1, TA2);
|
||||
this.eOperator = eOp;
|
||||
}
|
||||
public Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2, PairOperator eOp) {
|
||||
// Konstruktor
|
||||
this(TA1, TA2);
|
||||
this.eOperator = eOp;
|
||||
}
|
||||
|
||||
public Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2, PairOperator e0p, SourceLoc location) {
|
||||
this(TA1, TA2, e0p);
|
||||
this.location = location;
|
||||
}
|
||||
public Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2, PairOperator e0p, SourceLoc location) {
|
||||
this(TA1, TA2, e0p);
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
public Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2, PairOperator eOp, boolean noUnification) {
|
||||
// Konstruktor
|
||||
this(TA1, TA2);
|
||||
this.eOperator = eOp;
|
||||
this.noUnification = noUnification;
|
||||
}
|
||||
public Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2, PairOperator eOp, boolean noUnification) {
|
||||
// Konstruktor
|
||||
this(TA1, TA2);
|
||||
this.eOperator = eOp;
|
||||
this.noUnification = noUnification;
|
||||
}
|
||||
|
||||
public SourceLoc getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
public SourceLoc getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
// otth: Gibt ein Paar als String aus --> zum Debuggen und Vergleichen
|
||||
String strElement1 = "NULL";
|
||||
String strElement2 = "NULL";
|
||||
String Operator = "<.";
|
||||
public String toString() {
|
||||
// otth: Gibt ein Paar als String aus --> zum Debuggen und Vergleichen
|
||||
String strElement1 = "NULL";
|
||||
String strElement2 = "NULL";
|
||||
String Operator = "<.";
|
||||
|
||||
if (TA1 != null)
|
||||
strElement1 = TA1.toString();
|
||||
if (TA1 != null)
|
||||
strElement1 = TA1.toString();
|
||||
|
||||
if (TA2 != null)
|
||||
strElement2 = TA2.toString();
|
||||
if (TA2 != null)
|
||||
strElement2 = TA2.toString();
|
||||
|
||||
/* PL ausskommentiert 2018-05-24
|
||||
if(OperatorEqual())
|
||||
@@ -75,103 +78,125 @@ public class Pair implements Serializable, IConstraintElement, ISerializableData
|
||||
Operator = "<?";
|
||||
*/
|
||||
|
||||
return "\n(P: " + strElement1 + " " + eOperator.toString() + " " + strElement2 + ")";
|
||||
return "\n(P: " + strElement1 + " " + eOperator.toString() + " " + strElement2 + ")";
|
||||
|
||||
/*- Equals: " + bEqual*/
|
||||
}
|
||||
/*- Equals: " + bEqual*/
|
||||
}
|
||||
|
||||
/**
|
||||
* <br/>Author: J�rg B�uerle
|
||||
*
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public boolean equals(Object obj) {
|
||||
return (
|
||||
(obj instanceof Pair pairObj) &&
|
||||
pairObj.TA1.equals(this.TA1) &&
|
||||
pairObj.TA2.equals(this.TA2)
|
||||
);
|
||||
}
|
||||
/**
|
||||
* <br/>Author: J�rg B�uerle
|
||||
*
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public boolean equals(Object obj) {
|
||||
return (
|
||||
(obj instanceof Pair pairObj) &&
|
||||
pairObj.TA1.equals(this.TA1) &&
|
||||
pairObj.TA2.equals(this.TA2)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Author: Arne Lüdtke<br/>
|
||||
* Abfrage, ob Operator vom Typ Equal ist.
|
||||
*/
|
||||
public boolean OperatorEqual() {
|
||||
return eOperator == PairOperator.EQUALSDOT;
|
||||
}
|
||||
/**
|
||||
* Author: Arne Lüdtke<br/>
|
||||
* Abfrage, ob Operator vom Typ Equal ist.
|
||||
*/
|
||||
public boolean OperatorEqual() {
|
||||
return eOperator == PairOperator.EQUALSDOT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Author: Arne Lüdtke<br/>
|
||||
* Abfrage, ob Operator vom Typ Smaller ist.
|
||||
*/
|
||||
public boolean OperatorSmaller() {
|
||||
return eOperator == PairOperator.SMALLER;
|
||||
}
|
||||
/**
|
||||
* Author: Arne Lüdtke<br/>
|
||||
* Abfrage, ob Operator vom Typ Smaller ist.
|
||||
*/
|
||||
public boolean OperatorSmaller() {
|
||||
return eOperator == PairOperator.SMALLER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Author: Arne Lüdtke<br/>
|
||||
* Abfrage, ob Operator vom Typ SmallerExtends ist.
|
||||
*/
|
||||
public boolean OperatorSmallerExtends() {
|
||||
return eOperator == PairOperator.SMALLERDOTWC;
|
||||
}
|
||||
/**
|
||||
* Author: Arne Lüdtke<br/>
|
||||
* Abfrage, ob Operator vom Typ SmallerExtends ist.
|
||||
*/
|
||||
public boolean OperatorSmallerExtends() {
|
||||
return eOperator == PairOperator.SMALLERDOTWC;
|
||||
}
|
||||
|
||||
/**
|
||||
* Author: Arne Lüdtke<br/>
|
||||
* Gibt den Operator zurück.
|
||||
*/
|
||||
public PairOperator GetOperator() {
|
||||
return eOperator;
|
||||
}
|
||||
/**
|
||||
* Author: Arne Lüdtke<br/>
|
||||
* Gibt den Operator zurück.
|
||||
*/
|
||||
public PairOperator GetOperator() {
|
||||
return eOperator;
|
||||
}
|
||||
|
||||
public boolean OperatorSmallerDot() {
|
||||
return eOperator == PairOperator.SMALLERDOT;
|
||||
}
|
||||
public boolean OperatorSmallerDot() {
|
||||
return eOperator == PairOperator.SMALLERDOT;
|
||||
}
|
||||
|
||||
|
||||
static public Map<String, TypePlaceholder> generateTPHMap(ConstraintSet<Pair> constraints) {
|
||||
HashMap<String, TypePlaceholder> ret = new HashMap<>();
|
||||
constraints.map((Pair p) -> {
|
||||
if (p.TA1 instanceof TypePlaceholder) {
|
||||
ret.put(((TypePlaceholder) p.TA1).getName(), (TypePlaceholder) p.TA1);
|
||||
}
|
||||
if (p.TA2 instanceof TypePlaceholder) {
|
||||
ret.put(((TypePlaceholder) p.TA2).getName(), (TypePlaceholder) p.TA2);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return ret;
|
||||
}
|
||||
static public Map<String, TypePlaceholder> generateTPHMap(ConstraintSet<Pair> constraints) {
|
||||
HashMap<String, TypePlaceholder> ret = new HashMap<>();
|
||||
constraints.map((Pair p) -> {
|
||||
if (p.TA1 instanceof TypePlaceholder) {
|
||||
ret.put(((TypePlaceholder) p.TA1).getName(), (TypePlaceholder) p.TA1);
|
||||
}
|
||||
if (p.TA2 instanceof TypePlaceholder) {
|
||||
ret.put(((TypePlaceholder) p.TA2).getName(), (TypePlaceholder) p.TA2);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SerialMap toSerial(KeyStorage keyStorage) {
|
||||
// because toString() will output TA1 and TA2 recursively, we can ignore potential infinite recursion here too
|
||||
SerialMap serialized = new SerialMap();
|
||||
serialized.put("ta1", this.TA1.toSerial(keyStorage));
|
||||
serialized.put("ta2", this.TA2.toSerial(keyStorage));
|
||||
serialized.put("op", this.eOperator.toString());
|
||||
serialized.put("noUnification", this.noUnification ? 1 : 0);
|
||||
serialized.put("location", this.location == null ? null : this.location.toSerial(keyStorage));
|
||||
return serialized;
|
||||
}
|
||||
@Override
|
||||
public SerialMap toSerial(KeyStorage keyStorage) {
|
||||
// because toString() will output TA1 and TA2 recursively, we can ignore potential infinite recursion here too
|
||||
SerialMap serialized = new SerialMap();
|
||||
serialized.put("ta1", this.TA1.toSerial(keyStorage));
|
||||
serialized.put("ta2", this.TA2.toSerial(keyStorage));
|
||||
serialized.put("op", this.eOperator.toString());
|
||||
serialized.put("noUnification", this.noUnification ? 1 : 0);
|
||||
serialized.put("location", this.location == null ? null : this.location.toSerial(keyStorage));
|
||||
return serialized;
|
||||
}
|
||||
|
||||
public static Pair fromSerial(SerialMap data, UnifyContext context) {
|
||||
String op = data.getValue("op").getOf(String.class);
|
||||
SerialMap ta1 = data.getMap("ta1");
|
||||
SerialMap ta2 = data.getMap("ta2");
|
||||
boolean noUnification = data.getValue("noUnification").getOf(Integer.class) == 1;
|
||||
SerialMap location = data.getMapOrNull("location");
|
||||
public static Pair fromSerial(SerialMap data, UnifyContext context) {
|
||||
String op = data.getValue("op").getOf(String.class);
|
||||
SerialMap ta1 = data.getMap("ta1");
|
||||
SerialMap ta2 = data.getMap("ta2");
|
||||
boolean noUnification = data.getValue("noUnification").getOf(Integer.class) == 1;
|
||||
SerialMap location = data.getMapOrNull("location");
|
||||
|
||||
var pair = new Pair(
|
||||
RefTypeOrTPHOrWildcardOrGeneric.fromSerial(ta1, context),
|
||||
RefTypeOrTPHOrWildcardOrGeneric.fromSerial(ta2, context),
|
||||
PairOperator.fromString(op),
|
||||
noUnification
|
||||
);
|
||||
if (location != null) pair.location = SourceLoc.fromSerial(location);
|
||||
return pair;
|
||||
}
|
||||
var pair = new Pair(
|
||||
RefTypeOrTPHOrWildcardOrGeneric.fromSerial(ta1, context),
|
||||
RefTypeOrTPHOrWildcardOrGeneric.fromSerial(ta2, context),
|
||||
PairOperator.fromString(op),
|
||||
noUnification
|
||||
);
|
||||
if (location != null) pair.location = SourceLoc.fromSerial(location);
|
||||
return pair;
|
||||
}
|
||||
|
||||
public String toDot(String color) {
|
||||
|
||||
return q(this.TA1.toString()) +
|
||||
" -> " +
|
||||
q(this.TA2.toString()) +
|
||||
" [label=" +
|
||||
q(this.GetOperator().toString()) +
|
||||
",color=" + q(color) + "]" +
|
||||
";\n";
|
||||
}
|
||||
|
||||
public String toDot() {
|
||||
|
||||
return q(this.TA1.toString()) +
|
||||
" -> " +
|
||||
q(this.TA2.toString()) +
|
||||
" [label=" +
|
||||
q(this.GetOperator().toString()) +
|
||||
"]" +
|
||||
";\n";
|
||||
}
|
||||
}
|
||||
// ino.end
|
||||
|
||||
@@ -35,8 +35,8 @@ public class TYPE {
|
||||
this.definedClasses = definedClasses;
|
||||
}
|
||||
|
||||
public ConstraintSet getConstraints() {
|
||||
ConstraintSet ret = new ConstraintSet();
|
||||
public ConstraintSet<Pair> getConstraints() {
|
||||
ConstraintSet<Pair> ret = new ConstraintSet<>();
|
||||
for (ClassOrInterface cl : definedClasses) {
|
||||
Set<ClassOrInterface> allClasses = TypeUnifyTaskHelper.getPresizedHashSet(allAvailableClasses.size());
|
||||
allClasses.addAll(allAvailableClasses);
|
||||
@@ -45,9 +45,9 @@ public class TYPE {
|
||||
return ret;
|
||||
}
|
||||
|
||||
private ConstraintSet getConstraintsClass(ClassOrInterface cl, TypeInferenceInformation info) {
|
||||
ConstraintSet ret = new ConstraintSet();
|
||||
ConstraintSet methConstrains;
|
||||
private ConstraintSet<Pair> getConstraintsClass(ClassOrInterface cl, TypeInferenceInformation info) {
|
||||
ConstraintSet<Pair> ret = new ConstraintSet<>();
|
||||
ConstraintSet<Pair> methConstrains;
|
||||
for(Method m : cl.getMethods()){
|
||||
ret.addAll(methConstrains = getConstraintsMethod(m,info, cl));
|
||||
m.constraints.addAll(methConstrains);
|
||||
@@ -86,11 +86,11 @@ public class TYPE {
|
||||
}
|
||||
*/
|
||||
|
||||
private ConstraintSet getConstraintsMethod(Method m, TypeInferenceInformation info, ClassOrInterface currentClass) {
|
||||
if(m.block == null)return new ConstraintSet(); //Abstrakte Methoden generieren keine Constraints
|
||||
private ConstraintSet<Pair> getConstraintsMethod(Method m, TypeInferenceInformation info, ClassOrInterface currentClass) {
|
||||
if(m.block == null)return new ConstraintSet<Pair>(); //Abstrakte Methoden generieren keine Constraints
|
||||
TypeInferenceBlockInformation blockInfo = new TypeInferenceBlockInformation(info.getAvailableClasses(), currentClass, m);
|
||||
TYPEStmt methodScope = new TYPEStmt(blockInfo);
|
||||
ConstraintSet constraintSet = new ConstraintSet();
|
||||
ConstraintSet<Pair> constraintSet = new ConstraintSet<>();
|
||||
|
||||
if (m.name.equals("main") && Modifier.isStatic(m.modifier) && m.getParameterList().getFormalparalist().size() == 1) {
|
||||
// Add constraint for main method
|
||||
@@ -120,12 +120,10 @@ public class TYPE {
|
||||
|
||||
var subPatternList = recordPattern.getSubPattern();
|
||||
var resolver = new GenericsResolverSameName();
|
||||
var ctorType = recordPattern.getCtor();
|
||||
|
||||
constraintSet.addUndConstraint(new Pair(ctorType, recordPattern.getType(), PairOperator.SMALLERDOT));
|
||||
var refType = (RefType) recordPattern.getType();
|
||||
|
||||
var allClasses = blockInformation.getAvailableClasses();
|
||||
var typename = ctorType.getName().getClassName();
|
||||
var typename = refType.getName().getClassName();
|
||||
|
||||
ClassOrInterface allClass = allClasses.stream().filter(c -> c.getClassName().getClassName().equals(typename)).findFirst().orElseThrow();
|
||||
|
||||
@@ -138,12 +136,12 @@ public class TYPE {
|
||||
FieldAssumption assumption = new FieldAssumption(param.getName(), allClass, param.getType(), blockInformation.getCurrentTypeScope());
|
||||
|
||||
var fieldCons = new Pair(el.getType(), assumption.getType(resolver), PairOperator.SMALLERDOT);
|
||||
var recvCons = new Pair(ctorType, assumption.getReceiverType(resolver), PairOperator.EQUALSDOT);
|
||||
var recvCons = new Pair(refType, assumption.getReceiverType(resolver), PairOperator.EQUALSDOT);
|
||||
constraintSet.addUndConstraint(fieldCons);
|
||||
constraintSet.addUndConstraint(recvCons);
|
||||
|
||||
for (var i = 0; i < ctorType.getParaList().size(); i++) {
|
||||
constraintSet.addUndConstraint(new Pair(ctorType.getParaList().get(i),
|
||||
for (var i = 0; i < refType.getParaList().size(); i++) {
|
||||
constraintSet.addUndConstraint(new Pair(refType.getParaList().get(i),
|
||||
((RefType)assumption.getReceiverType(resolver)).getParaList().get(i),
|
||||
PairOperator.EQUALSDOT));
|
||||
}
|
||||
|
||||
@@ -254,9 +254,6 @@ public class TYPEStmt implements StatementVisitor {
|
||||
} else if (unaryExpr.operation == UnaryExpr.Operation.NOT) {
|
||||
constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), unaryExpr.getType(), PairOperator.EQUALSDOT, loc(unaryExpr.getOffset())));
|
||||
constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), new RefType(ASTFactory.createClass(java.lang.Boolean.class).getClassName(), new NullToken()), PairOperator.EQUALSDOT, loc(unaryExpr.getOffset())));
|
||||
} else if (unaryExpr.operation == UnaryExpr.Operation.MINUS) {
|
||||
constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), number, PairOperator.SMALLERDOT, loc(unaryExpr.getOffset())));
|
||||
constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), unaryExpr.getType(), PairOperator.EQUALSDOT, loc(unaryExpr.getOffset())));
|
||||
} else {
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
@@ -395,8 +392,6 @@ public class TYPEStmt implements StatementVisitor {
|
||||
|
||||
@Override
|
||||
public void visit(BoolExpression expr) {
|
||||
expr.lexpr.accept(this);
|
||||
expr.rexpr.accept(this);
|
||||
|
||||
constraintsSet.addUndConstraint(new Pair(bool, expr.getType(), PairOperator.EQUALSDOT, loc(expr.getOffset())));
|
||||
constraintsSet.addUndConstraint(new Pair(bool, expr.lexpr.getType(), PairOperator.EQUALSDOT, loc(expr.getOffset())));
|
||||
@@ -741,12 +736,12 @@ public class TYPEStmt implements StatementVisitor {
|
||||
|
||||
for (int i = 0; i < foMethod.arglist.getArguments().size(); i++) {
|
||||
// Zuordnung von MethoCall.signature (Argumenttypen) zu der Argumenttypen der ausgewaehlten Methode (assumption.params)
|
||||
ret.add(new Pair(resolver.resolve(foMethod.signature.get(i)), resolver.resolve(assumption.getArgTypes().get(i)), PairOperator.EQUALSDOT));
|
||||
ret.add(new Pair(foMethod.signature.get(i), assumption.getArgTypes().get(i), PairOperator.EQUALSDOT));
|
||||
|
||||
}
|
||||
|
||||
// Zuordnung von MethodCall.signature(ReturnType) zu dem ReturnType der ausgewaehlten Methode (assumption.returnType)
|
||||
ret.add(new Pair(resolver.resolve(foMethod.signature.getLast()), resolver.resolve(assumption.getReturnType()), PairOperator.EQUALSDOT));
|
||||
ret.add(new Pair(foMethod.signature.getLast(), assumption.getReturnType(), PairOperator.EQUALSDOT));
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
@@ -755,7 +755,7 @@ public class RuleSet implements IRuleSet{
|
||||
|
||||
UnifyType lhsType = pair.getLhsType();
|
||||
UnifyType rhsType = pair.getRhsType();
|
||||
if((!(lhsType instanceof ReferenceType) && !(lhsType instanceof FunNType)) || !(rhsType instanceof ExtendsType))
|
||||
if(!(lhsType instanceof ReferenceType) || !(rhsType instanceof ExtendsType))
|
||||
return Optional.empty();
|
||||
|
||||
return Optional.of(new UnifyPair(lhsType, ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
|
||||
@@ -781,7 +781,7 @@ public class RuleSet implements IRuleSet{
|
||||
|
||||
UnifyType lhsType = pair.getLhsType();
|
||||
UnifyType rhsType = pair.getRhsType();
|
||||
if((!(lhsType instanceof ReferenceType) && !(lhsType instanceof FunNType)) || !(rhsType instanceof SuperType))
|
||||
if(!(lhsType instanceof ReferenceType) || !(rhsType instanceof SuperType))
|
||||
return Optional.empty();
|
||||
|
||||
return Optional.of(new UnifyPair(((SuperType) rhsType).getSuperedType(), lhsType, PairOperator.SMALLERDOTWC, pair.getSubstitution(), pair.getBasePair()));
|
||||
@@ -904,7 +904,7 @@ public class RuleSet implements IRuleSet{
|
||||
|
||||
var fiArgs = intf.getFunctionalInterfaceTypeArguments(refType);
|
||||
var retType = fiArgs.getFirst();
|
||||
var lhsArgs = intf.getFunctionalInterfaceTypeArguments(lhsType); //FALSCHRUM????
|
||||
var lhsArgs = intf.getFunctionalInterfaceTypeArguments(lhsType);
|
||||
var lhsRet = lhsArgs.getFirst();
|
||||
|
||||
Set<UnifyPair> result = new HashSet<>();
|
||||
@@ -972,65 +972,15 @@ public class RuleSet implements IRuleSet{
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Set<UnifyPair>> smallerFunN(UnifyPair pair, IFiniteClosure fc) {
|
||||
public Optional<Set<UnifyPair>> smallerFunN(UnifyPair pair) {
|
||||
if(pair.getPairOp() != PairOperator.SMALLERDOT)
|
||||
return Optional.empty();
|
||||
|
||||
UnifyType lhsType = pair.getLhsType();
|
||||
UnifyType rhsType = pair.getRhsType();
|
||||
|
||||
if(!(rhsType instanceof FunNType))
|
||||
if(!(lhsType instanceof PlaceholderType) || !(rhsType instanceof FunNType))
|
||||
return Optional.empty();
|
||||
|
||||
/* muss nach angepasst werden */
|
||||
//FunN$$<...> <. FunctinalInterface<...> wird umgewandelt in FunN$$<...> <. FunN$$<... args aus FuntionalInterface ...>
|
||||
if (lhsType instanceof ReferenceType) {
|
||||
UnifyType typeFI = pair.getLhsType();
|
||||
|
||||
Optional<UnifyType> opt = fc.getRightHandedFunctionalInterfaceType(typeFI.getName());
|
||||
if(!opt.isPresent())
|
||||
return Optional.empty();
|
||||
|
||||
if (!(typeFI instanceof ReferenceType refType) || !(refType instanceof FunInterfaceType intf))
|
||||
return Optional.empty();
|
||||
|
||||
var fiArgs = intf.getFunctionalInterfaceTypeArguments(refType);
|
||||
var retType = fiArgs.getFirst();
|
||||
var rhsArgs = intf.getFunctionalInterfaceTypeArguments(rhsType);
|
||||
var rhsRet = rhsArgs.getFirst();
|
||||
|
||||
Set<UnifyPair> result = new HashSet<>();
|
||||
//if (retType instanceof ExtendsType) {
|
||||
result.add(new UnifyPair(retType, rhsRet, PairOperator.SMALLER));
|
||||
//} else if (retType instanceof SuperType) {
|
||||
// return Optional.empty();
|
||||
//} else {
|
||||
// result.add(new UnifyPair(lhsRet, retType, PairOperator.EQUALSDOT));
|
||||
//}
|
||||
|
||||
for (var i = 1; i < fiArgs.size(); i++) {
|
||||
var rh = rhsArgs.get(i);
|
||||
var lh = fiArgs.get(i);
|
||||
|
||||
//if (rh instanceof SuperType) {
|
||||
result.add(new UnifyPair(rh, lh, PairOperator.SMALLER));
|
||||
//} else if (rh instanceof ExtendsType) {
|
||||
// return Optional.empty();
|
||||
//} else {
|
||||
// result.add(new UnifyPair(lh, rh, PairOperator.EQUALSDOT));
|
||||
//}
|
||||
}
|
||||
|
||||
return Optional.of(result);
|
||||
}
|
||||
|
||||
else {
|
||||
if(!(lhsType instanceof PlaceholderType))
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
FunNType funNRhsType = (FunNType) rhsType;
|
||||
|
||||
@@ -1067,122 +1017,7 @@ public class RuleSet implements IRuleSet{
|
||||
|
||||
return Optional.of(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Set<UnifyPair>> reduceFIFunN(UnifyPair pair, IFiniteClosure fc) {
|
||||
if(pair.getPairOp() != PairOperator.EQUALSDOT)
|
||||
return Optional.empty();
|
||||
|
||||
UnifyType lhsType = pair.getLhsType();
|
||||
UnifyType rhsType = pair.getRhsType();
|
||||
|
||||
if(!(rhsType instanceof FunNType))
|
||||
return Optional.empty();
|
||||
|
||||
/* muss nach angepasst werden */
|
||||
//FunN$$<...> <. FunctinalInterface<...> wird umgewandelt in FunN$$<...> <. FunN$$<... args aus FuntionalInterface ...>
|
||||
if (lhsType instanceof ReferenceType) {
|
||||
UnifyType typeFI = pair.getLhsType();
|
||||
|
||||
Optional<UnifyType> opt = fc.getRightHandedFunctionalInterfaceType(typeFI.getName());
|
||||
if(!opt.isPresent())
|
||||
return Optional.empty();
|
||||
|
||||
if (!(typeFI instanceof ReferenceType refType) || !(refType instanceof FunInterfaceType intf))
|
||||
return Optional.empty();
|
||||
|
||||
var fiArgs = intf.getFunctionalInterfaceTypeArguments(refType);
|
||||
var retType = fiArgs.getFirst();
|
||||
var rhsArgs = intf.getFunctionalInterfaceTypeArguments(rhsType);
|
||||
var rhsRet = rhsArgs.getFirst();
|
||||
|
||||
Set<UnifyPair> result = new HashSet<>();
|
||||
//if (retType instanceof ExtendsType) {
|
||||
result.add(new UnifyPair(retType, rhsRet, PairOperator.EQUALSDOT));
|
||||
//} else if (retType instanceof SuperType) {
|
||||
// return Optional.empty();
|
||||
//} else {
|
||||
// result.add(new UnifyPair(lhsRet, retType, PairOperator.EQUALSDOT));
|
||||
//}
|
||||
|
||||
for (var i = 1; i < fiArgs.size(); i++) {
|
||||
var rh = rhsArgs.get(i);
|
||||
var lh = fiArgs.get(i);
|
||||
|
||||
//if (rh instanceof SuperType) {
|
||||
result.add(new UnifyPair(rh, lh, PairOperator.EQUALSDOT));
|
||||
//} else if (rh instanceof ExtendsType) {
|
||||
// return Optional.empty();
|
||||
//} else {
|
||||
// result.add(new UnifyPair(lh, rh, PairOperator.EQUALSDOT));
|
||||
//}
|
||||
}
|
||||
|
||||
return Optional.of(result);
|
||||
}
|
||||
else {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Set<UnifyPair>> reduceFunNFi(UnifyPair pair, IFiniteClosure fc) {
|
||||
if(pair.getPairOp() != PairOperator.EQUALSDOT)
|
||||
return Optional.empty();
|
||||
|
||||
UnifyType lhsType = pair.getLhsType();
|
||||
UnifyType rhsType = pair.getRhsType();
|
||||
|
||||
if(!(lhsType instanceof FunNType))
|
||||
return Optional.empty();
|
||||
|
||||
//FunN$$<...> <. FunctinalInterface<...> wird umgewandelt in FunN$$<...> <. FunN$$<... args aus FuntionalInterface ...>
|
||||
if (rhsType instanceof ReferenceType) {
|
||||
UnifyType typeFI = pair.getRhsType();
|
||||
|
||||
Optional<UnifyType> opt = fc.getRightHandedFunctionalInterfaceType(typeFI.getName());
|
||||
if(!opt.isPresent())
|
||||
return Optional.empty();
|
||||
|
||||
if (!(typeFI instanceof ReferenceType refType) || !(refType instanceof FunInterfaceType intf))
|
||||
return Optional.empty();
|
||||
|
||||
var fiArgs = intf.getFunctionalInterfaceTypeArguments(refType);
|
||||
var retType = fiArgs.getFirst();
|
||||
var lhsArgs = intf.getFunctionalInterfaceTypeArguments(lhsType);
|
||||
var lhsRet = lhsArgs.getFirst();
|
||||
|
||||
Set<UnifyPair> result = new HashSet<>();
|
||||
//if (retType instanceof ExtendsType) {
|
||||
// result.add(new UnifyPair(lhsRet, retType, PairOperator.SMALLERDOTWC));
|
||||
//} else if (retType instanceof SuperType) {
|
||||
// return Optional.empty();
|
||||
//} else {
|
||||
result.add(new UnifyPair(lhsRet, retType, PairOperator.EQUALSDOT));
|
||||
//}
|
||||
|
||||
for (var i = 1; i < fiArgs.size(); i++) {
|
||||
var lh = lhsArgs.get(i);
|
||||
var rh = fiArgs.get(i);
|
||||
|
||||
//if (rh instanceof SuperType) {
|
||||
// result.add(new UnifyPair(lh, rh, PairOperator.SMALLERDOTWC));
|
||||
//} else if (rh instanceof ExtendsType) {
|
||||
// return Optional.empty();
|
||||
//} else {
|
||||
result.add(new UnifyPair(lh, rh, PairOperator.EQUALSDOT));
|
||||
//}
|
||||
}
|
||||
|
||||
return Optional.of(result);
|
||||
}
|
||||
|
||||
else {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Optional<UnifyPair> reduceTph(UnifyPair pair) {
|
||||
if(pair.getPairOp() != PairOperator.SMALLERDOTWC)
|
||||
@@ -1190,7 +1025,7 @@ public class RuleSet implements IRuleSet{
|
||||
|
||||
UnifyType lhsType = pair.getLhsType();
|
||||
UnifyType rhsType = pair.getRhsType();
|
||||
if(!(lhsType instanceof PlaceholderType) || (!(rhsType instanceof ReferenceType) && !(rhsType instanceof FunNType)))
|
||||
if(!(lhsType instanceof PlaceholderType) || !(rhsType instanceof ReferenceType))
|
||||
return Optional.empty();
|
||||
|
||||
return Optional.of(new UnifyPair(lhsType, rhsType, PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
|
||||
|
||||
@@ -29,7 +29,6 @@ import de.dhbwstuttgart.util.Logger;
|
||||
import de.dhbwstuttgart.util.Pair;
|
||||
import de.dhbwstuttgart.util.Tuple;
|
||||
import java.io.Serial;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
@@ -151,15 +150,12 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
|
||||
this.fc = fc;
|
||||
this.oup = new OrderingUnifyPair(fc, context);
|
||||
|
||||
if (!ConsoleInterface.writeLogFiles || context.logger() instanceof ServerTaskLogger) this.context = context;
|
||||
else {
|
||||
var baseFolder = Path.of(System.getProperty("user.dir"), "logFiles");
|
||||
this.context = context.newWithLogger(
|
||||
Logger.forFile(
|
||||
baseFolder.resolve("Thread_" + Thread.currentThread().hashCode() + ".txt").toString(), "Unify"
|
||||
)
|
||||
);
|
||||
}
|
||||
this.context = (!ConsoleInterface.writeLogFiles || context.logger() instanceof ServerTaskLogger) ? context : context.newWithLogger(
|
||||
Logger.forFile(
|
||||
System.getProperty("user.dir") + "/logFiles/" + "Thread",
|
||||
"Unify"
|
||||
)
|
||||
);
|
||||
|
||||
/*Abbruchtest
|
||||
if (thNo > 10) {
|
||||
@@ -1243,7 +1239,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
|
||||
// FunN Rules
|
||||
optSet = optSet.isPresent() ? optSet : rules.reduceFunN(pair);
|
||||
optSet = optSet.isPresent() ? optSet : rules.greaterFunN(pair, fc);
|
||||
optSet = optSet.isPresent() ? optSet : rules.smallerFunN(pair, fc);
|
||||
optSet = optSet.isPresent() ? optSet : rules.smallerFunN(pair);
|
||||
|
||||
// One of the rules has been applied
|
||||
if (optSet.isPresent()) {
|
||||
|
||||
@@ -39,8 +39,7 @@ public class UnifyResultModel {
|
||||
public void notify(Set<Set<UnifyPair>> eqPrimePrimeSet, UnifyContext context) {
|
||||
Set<Set<UnifyPair>> eqPrimePrimeSetRet = eqPrimePrimeSet.stream().map(x -> {
|
||||
Optional<Set<UnifyPair>> res = new RuleSet(context.placeholderRegistry()).subst(x.stream().map(y -> {
|
||||
if (y.getPairOp() == PairOperator.SMALLERDOTWC)
|
||||
y.setPairOp(PairOperator.EQUALSDOT);
|
||||
if (y.getPairOp() == PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT);
|
||||
return y; //alle Paare a <.? b erden durch a =. b ersetzt
|
||||
}).collect(Collectors.toCollection(HashSet::new)));
|
||||
if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert
|
||||
|
||||
@@ -61,9 +61,7 @@ public interface IRuleSet {
|
||||
*/
|
||||
public Optional<Set<UnifyPair>> reduceFunN(UnifyPair pair);
|
||||
public Optional<Set<UnifyPair>> greaterFunN(UnifyPair pair, IFiniteClosure fc);
|
||||
public Optional<Set<UnifyPair>> smallerFunN(UnifyPair pair, IFiniteClosure fc);
|
||||
public Optional<Set<UnifyPair>> reduceFIFunN(UnifyPair pair, IFiniteClosure fc);
|
||||
public Optional<Set<UnifyPair>> reduceFunNFi(UnifyPair pair, IFiniteClosure fc);
|
||||
public Optional<Set<UnifyPair>> smallerFunN(UnifyPair pair);
|
||||
|
||||
/**
|
||||
* Checks whether the erase1-Rule applies to the pair.
|
||||
|
||||
@@ -684,7 +684,6 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Set<UnifyType> getAncestors(UnifyType t) {
|
||||
|
||||
@@ -3,13 +3,11 @@ package de.dhbwstuttgart.util;
|
||||
import com.diogonunes.jcolor.Attribute;
|
||||
import de.dhbwstuttgart.core.ConsoleInterface;
|
||||
import de.dhbwstuttgart.server.SocketServer;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.output.NullOutputStream;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.Writer;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Arrays;
|
||||
@@ -21,42 +19,12 @@ import static com.diogonunes.jcolor.Ansi.colorize;
|
||||
|
||||
public class Logger {
|
||||
|
||||
public static final Logger NULL_LOGGER = new NullLogger();
|
||||
private static final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
protected final Writer writer;
|
||||
protected final String prefix;
|
||||
|
||||
private static final File logFolder = new File(System.getProperty("user.dir") + "/logFiles/");
|
||||
public static final Logger NULL_LOGGER = new NullLogger();
|
||||
|
||||
private static Writer defaultWriter;
|
||||
private static void initLogger() {
|
||||
if (defaultWriter != null) return;
|
||||
if (!ConsoleInterface.writeLogFiles) return;
|
||||
try {
|
||||
Files.createDirectories(logFolder.toPath());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Could not create directory for log files: " + logFolder, e);
|
||||
}
|
||||
var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
|
||||
var currentTimestamp = LocalDateTime.now().format(formatter);
|
||||
try {
|
||||
defaultWriter = new FileWriter(new File(logFolder, currentTimestamp + ".txt"));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void resetLogs() {
|
||||
defaultWriter = null;
|
||||
try {
|
||||
FileUtils.cleanDirectory(logFolder);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
initLogger();
|
||||
}
|
||||
|
||||
public Logger() {
|
||||
this(null, "");
|
||||
}
|
||||
@@ -67,15 +35,9 @@ public class Logger {
|
||||
|
||||
public Logger(Writer writer, String prefix) {
|
||||
this.prefix = (Objects.equals(prefix, "")) ? "" : "["+prefix+"] ";
|
||||
initLogger();
|
||||
this.writer = writer;
|
||||
}
|
||||
|
||||
private Writer getWriter() {
|
||||
if (writer != null) return writer;
|
||||
return defaultWriter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new logger object from the path provided
|
||||
*
|
||||
@@ -125,7 +87,6 @@ public class Logger {
|
||||
* @param logLevel If logLevel == error, then print to stderr or print to stdout otherwise
|
||||
*/
|
||||
protected void print(String s, LogLevel logLevel) {
|
||||
if (!ConsoleInterface.writeToConsole) return;
|
||||
String coloredPrefix = this.getPrefix(logLevel);
|
||||
|
||||
// if we are running the server, prepend the timestamp
|
||||
@@ -152,13 +113,11 @@ public class Logger {
|
||||
* @param s The string to print
|
||||
*/
|
||||
protected void write(String s) {
|
||||
var writer = getWriter();
|
||||
if (writer != null && ConsoleInterface.writeLogFiles) {
|
||||
// writing to file should only be done when necessary
|
||||
synchronized (writer) {
|
||||
try {
|
||||
writer.write(s + "\n");
|
||||
writer.flush();
|
||||
writer.write(s);
|
||||
}
|
||||
catch (IOException exception) {
|
||||
throw new RuntimeException("Failed writing to file", exception);
|
||||
|
||||
@@ -14,9 +14,7 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import de.dhbwstuttgart.core.ConsoleInterface;
|
||||
import de.dhbwstuttgart.core.JavaTXCompiler;
|
||||
import de.dhbwstuttgart.util.Logger.LogLevel;
|
||||
|
||||
public class AllgemeinTest {
|
||||
|
||||
@@ -31,7 +29,6 @@ public class AllgemeinTest {
|
||||
|
||||
@Test
|
||||
public void test() throws Exception {
|
||||
ConsoleInterface.logLevel = LogLevel.DEBUG;
|
||||
//String className = "GenTest";
|
||||
//String className = "Overloading_Generics";
|
||||
//String className = "Generics";
|
||||
@@ -58,7 +55,6 @@ public class AllgemeinTest {
|
||||
//String className = "WildcardCaptureConversionTest";
|
||||
//String className = "CaptureConversion";
|
||||
//String className = "Pair";
|
||||
//String className = "DublicateWildcard";
|
||||
//String className = "UseWildcardPair";
|
||||
//String className = "Assign";
|
||||
//String className = "StreamTest";
|
||||
@@ -67,14 +63,11 @@ public class AllgemeinTest {
|
||||
//String className = "Cycle";
|
||||
//String className = "TripleTest";
|
||||
//String className = "WildcardList";
|
||||
//String className = "List";
|
||||
String className = "List";
|
||||
//String className = "Box";
|
||||
//String className = "GenBox";
|
||||
//String className = "InnerInf";
|
||||
//String className = "Foo";
|
||||
//String className = "Kombinatoren_failure";
|
||||
String className = "Kombinatoren_After_Lazy";
|
||||
//String className = "Parser";
|
||||
//PL 2019-10-24: genutzt fuer unterschiedliche Tests
|
||||
path = System.getProperty("user.dir")+"/resources/AllgemeinTest/" + className + ".jav";
|
||||
//path = System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/Overloading_Generics.jav";
|
||||
@@ -83,7 +76,7 @@ public class AllgemeinTest {
|
||||
///*
|
||||
compiler = new JavaTXCompiler(
|
||||
Lists.newArrayList(new File(path)),
|
||||
Lists.newArrayList(new File(System.getProperty("user.dir")+"/resources/AllgemeinTest/")),
|
||||
Lists.newArrayList(new File(System.getProperty("user.dir")+"/resources/bytecode/classFiles/")),
|
||||
new File(System.getProperty("user.dir")+"/resources/bytecode/classFiles/"), true);
|
||||
//*/
|
||||
compiler.generateBytecode();
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
|
||||
import de.dhbwstuttgart.core.ConsoleInterface;
|
||||
import de.dhbwstuttgart.util.Logger;
|
||||
import de.dhbwstuttgart.util.Logger.LogLevel;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
@@ -22,14 +17,8 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
import static targetast.TestCodegen.createClassLoader;
|
||||
import static targetast.TestCodegen.generateClassFiles;
|
||||
|
||||
@Execution(ExecutionMode.CONCURRENT)
|
||||
public class TestComplete {
|
||||
|
||||
@BeforeAll
|
||||
public static void setup() throws IOException {
|
||||
TestCodegen.outputPath.toFile().mkdirs();
|
||||
FileUtils.cleanDirectory(TestCodegen.outputPath.toFile());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyLambdaTest() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "applyLambda.jav");
|
||||
@@ -329,17 +318,9 @@ public class TestComplete {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortingTest() throws Exception {
|
||||
public void overloadingSortingTest() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "Sorting.jav");
|
||||
var Sorting = classFiles.get("Sorting");
|
||||
var instance = Sorting.getDeclaredConstructor().newInstance();
|
||||
|
||||
var unsorted = List.of(10, 2, 1, 20, -1, 5);
|
||||
var sorted = List.of(-1, 1, 2, 5, 10, 20);
|
||||
var sort = Sorting.getDeclaredMethod("sort", List.class);
|
||||
|
||||
var result = sort.invoke(instance, unsorted);
|
||||
assertEquals(sorted, result);
|
||||
var instance = classFiles.get("Sorting").getDeclaredConstructor().newInstance();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -783,8 +764,6 @@ public class TestComplete {
|
||||
assertEquals("Second Element is a Text", swtch.invoke(instance, r1));
|
||||
assertEquals("Second Element is a Number", swtch.invoke(instance, r2));
|
||||
}
|
||||
|
||||
@Disabled("Infinite loop in type inference")
|
||||
@Test
|
||||
public void testSwitchListRecord() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "SwitchRecordList.jav");
|
||||
@@ -974,83 +953,25 @@ public class TestComplete {
|
||||
var list1 = ConsCtor.newInstance(1, ConsCtor.newInstance(2, ConsCtor.newInstance(3, EmptyCtor.newInstance())));
|
||||
var list2 = ConsCtor.newInstance(4, ConsCtor.newInstance(5, ConsCtor.newInstance(6, EmptyCtor.newInstance())));
|
||||
|
||||
var append = clazz.getDeclaredMethod("append", List, List);
|
||||
var append = clazz.getDeclaredMethod("append", Cons, Cons);
|
||||
System.out.println(append.invoke(instance, list1, list2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPatternMatchingSpecificity() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "PatternMatchingSpecificity.jav");
|
||||
|
||||
var clazz = classFiles.get("PatternMatchingSpecificity");
|
||||
var instance = clazz.getDeclaredConstructor().newInstance();
|
||||
var R = classFiles.get("R");
|
||||
|
||||
Integer i = 20;
|
||||
var r = R.getDeclaredConstructor(Number.class).newInstance(i);
|
||||
|
||||
var m = clazz.getDeclaredMethod("m", R);
|
||||
assertEquals(1, m.invoke(instance, r));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPatternMatchingCaptures() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "PatternMatchingCaptures.jav");
|
||||
|
||||
var clazz = classFiles.get("PatternMatchingCaptures");
|
||||
var R = classFiles.get("R");
|
||||
var Base = classFiles.get("Base");
|
||||
var r = R.getDeclaredConstructor(Integer.class).newInstance(10);
|
||||
|
||||
var instance = clazz.getDeclaredConstructor().newInstance();
|
||||
var test1 = clazz.getDeclaredMethod("test1", Base);
|
||||
assertEquals(10, test1.invoke(instance, r));
|
||||
|
||||
var test2 = clazz.getDeclaredMethod("test2", Base);
|
||||
assertEquals(10, test1.invoke(instance, r));
|
||||
|
||||
var test3 = clazz.getDeclaredMethod("test3", R);
|
||||
assertEquals(10, test1.invoke(instance, r));
|
||||
|
||||
var test4 = clazz.getDeclaredMethod("test4", R);
|
||||
assertEquals(10, test1.invoke(instance, r));
|
||||
|
||||
var test5 = clazz.getDeclaredMethod("test5", R);
|
||||
assertEquals(10, test1.invoke(instance, r));
|
||||
|
||||
var test6 = clazz.getDeclaredMethod("test6", R);
|
||||
assertEquals(10, test1.invoke(instance, r));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPatternMatchingZip() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "PatternMatching.jav");
|
||||
var clazz = classFiles.get("PatternMatching");
|
||||
var instance = clazz.getDeclaredConstructor().newInstance();
|
||||
|
||||
var Cons = classFiles.get("Cons");
|
||||
var Empty = classFiles.get("Empty");
|
||||
var List = classFiles.get("List");
|
||||
|
||||
var ConsCtor = Cons.getDeclaredConstructor(Object.class, List);
|
||||
var EmptyCtor = Empty.getDeclaredConstructor();
|
||||
|
||||
var list1 = ConsCtor.newInstance(1, ConsCtor.newInstance(2, ConsCtor.newInstance(3, EmptyCtor.newInstance())));
|
||||
var list2 = ConsCtor.newInstance(4, ConsCtor.newInstance(5, ConsCtor.newInstance(6, EmptyCtor.newInstance())));
|
||||
|
||||
var zip = clazz.getDeclaredMethod("zip", List, List);
|
||||
System.out.println(zip.invoke(instance, list1, list2));
|
||||
}
|
||||
|
||||
@Disabled("Invalid file, check this later")
|
||||
@Test
|
||||
public void testPatternMatchingZipJava() throws Exception {
|
||||
ConsoleInterface.logLevel = Logger.LogLevel.DEBUG;
|
||||
var classFiles = generateClassFiles(createClassLoader(), false, "PatternMatchingJava.jav", "PatternMatchingJava2.jav");
|
||||
var clazz = classFiles.get("PatternMatchingJava");
|
||||
var instance = clazz.getDeclaredConstructor().newInstance();
|
||||
}
|
||||
|
||||
@Disabled("Feature nicht implementiert")
|
||||
@Test
|
||||
public void testOverloadSwitch() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "SwitchOverload.jav");
|
||||
@@ -1304,14 +1225,6 @@ public class TestComplete {
|
||||
m.invoke(null, List.of("foo", "bar", "baz"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLazy() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), false, "LazyList.jav", "Primzahlen.jav");
|
||||
var clazz = classFiles.get("Primzahlen");
|
||||
var main = clazz.getDeclaredMethod("main", List.class);
|
||||
main.invoke(null, List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBug122() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "Bug122.jav");
|
||||
@@ -1475,7 +1388,6 @@ public class TestComplete {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled("too slow")
|
||||
public void testBug325() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "Bug325.jav");
|
||||
var clazz = classFiles.get("Bug325");
|
||||
@@ -1560,9 +1472,7 @@ public class TestComplete {
|
||||
var m = clazz.getDeclaredMethod("ex1");
|
||||
assertEquals("ABC", m.invoke(instance));
|
||||
var ex2 = clazz.getDeclaredMethod("ex2");
|
||||
assertEquals("CBA", ex2.invoke(instance));
|
||||
var ex3 = clazz.getDeclaredMethod("ex3");
|
||||
assertEquals("BA", ex3.invoke(instance));
|
||||
assertEquals("BAC", ex2.invoke(instance));
|
||||
}
|
||||
@Test
|
||||
public void testBug366() throws Exception {
|
||||
@@ -1626,18 +1536,10 @@ public class TestComplete {
|
||||
// TODO This logs output that we should validate
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBug389() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), true, "Bug389.jav", "Bug389Main.jav");
|
||||
var clazz = classFiles.get("Bug389Main");
|
||||
clazz.getDeclaredMethod("main", List.class).invoke(null, List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBug390() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "Bug390.jav");
|
||||
var clazz = classFiles.get("Bug390");
|
||||
clazz.getDeclaredMethod("main", List.class).invoke(null, List.of());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -19,11 +19,14 @@ public class TestTypeDeployment {
|
||||
var path = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Cycle.jav");
|
||||
var file = path.toFile();
|
||||
var compiler = new JavaTXCompiler(file);
|
||||
compiler.generateBytecode();
|
||||
var parsedSource = compiler.sourceFiles.get(file);
|
||||
var tiResults = compiler.typeInference(file);
|
||||
Set<TypeInsert> tips = new HashSet<>();
|
||||
|
||||
for (var sf : compiler.sourceFiles.values()) {
|
||||
Map<JavaClassName, byte[]> bytecode = compiler.generateBytecode(sf, tiResults);
|
||||
}
|
||||
|
||||
System.out.println(compiler.getGeneratedGenerics());
|
||||
|
||||
for (int i = 0; i < tiResults.size(); i++) {
|
||||
|
||||
@@ -59,7 +59,6 @@ public class ServerTest {
|
||||
|
||||
// get information from the compiler
|
||||
JavaTXCompiler compiler = new JavaTXCompiler(List.of(file));
|
||||
compiler.parseAll();
|
||||
|
||||
// NOW: simulate the call to method typeInference. Once via server and once locally
|
||||
// if everything works, they should neither interfere with each other nor differ in their result
|
||||
|
||||
@@ -18,7 +18,7 @@ public class InheritTest {
|
||||
public static void setUpBeforeClass() throws Exception {
|
||||
var classLoader = TestCodegen.createClassLoader();
|
||||
|
||||
var classes = TestCodegen.generateClassFiles(classLoader, false, "AA.jav", "BB.jav", "CC.jav", "DD.jav", "Inherit.jav");
|
||||
var classes = TestCodegen.generateClassFiles(classLoader, "Inherit.jav", "AA.jav", "BB.jav", "CC.jav", "DD.jav");
|
||||
classToTest = classes.get("Inherit");
|
||||
classToTestAA = classes.get("AA");
|
||||
classToTestBB = classes.get("BB");
|
||||
@@ -52,7 +52,7 @@ public class InheritTest {
|
||||
public void testmainCC() throws Exception {
|
||||
Method m = classToTestCC.getDeclaredMethod("m", Integer.class);
|
||||
assertEquals("CC", m.invoke(instanceOfClassCC, 5));
|
||||
Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class);
|
||||
Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class);
|
||||
assertEquals("CC", main.invoke(instanceOfClass, instanceOfClassCC, 5));
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ public class InheritTest {
|
||||
public void testmainDD() throws Exception {
|
||||
Method m = classToTestCC.getDeclaredMethod("m", Integer.class);
|
||||
assertEquals("CC", m.invoke(instanceOfClassDD, 5));
|
||||
Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class);
|
||||
Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class);
|
||||
assertEquals("CC", main.invoke(instanceOfClass, instanceOfClassDD, 5));
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ public class PutTest {
|
||||
Method m = classToTest.getDeclaredMethod("putElement", Object.class, Stack.class);
|
||||
Stack<Integer> s_invoke = new Stack<>();
|
||||
m.invoke(instanceOfClass, 5, s_invoke);
|
||||
assertEquals(5, s_invoke.pop());
|
||||
assertEquals(new Integer(5), s_invoke.pop());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -53,6 +53,6 @@ public class PutTest {
|
||||
Method m = classToTest.getDeclaredMethod("main", Object.class, Stack.class);
|
||||
Stack<Integer> s_invoke = new Stack<>();
|
||||
m.invoke(instanceOfClass, 6, s_invoke);
|
||||
assertEquals(6, s_invoke.pop());
|
||||
assertEquals(new Integer(6), s_invoke.pop());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import de.dhbwstuttgart.bytecode.Codegen;
|
||||
import de.dhbwstuttgart.environment.DirectoryClassLoader;
|
||||
import de.dhbwstuttgart.environment.IByteArrayClassLoader;
|
||||
import de.dhbwstuttgart.parser.scope.JavaClassName;
|
||||
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
|
||||
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
|
||||
import de.dhbwstuttgart.target.tree.MethodParameter;
|
||||
import de.dhbwstuttgart.target.tree.TargetClass;
|
||||
@@ -15,7 +14,6 @@ import de.dhbwstuttgart.target.tree.expression.*;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetFunNType;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetRefType;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetType;
|
||||
import de.dhbwstuttgart.typeinference.result.ResultSet;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -32,7 +30,7 @@ import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class TestCodegen {
|
||||
public static final Path outputPath = Path.of(System.getProperty("user.dir"), "/targetTest");
|
||||
static final Path outputPath = Path.of(System.getProperty("user.dir"), "/targetTest");
|
||||
|
||||
private static void writeClassFile(String name, byte[] code) throws IOException {
|
||||
Files.createDirectories(outputPath);
|
||||
@@ -58,8 +56,7 @@ public class TestCodegen {
|
||||
try(var newClassLoader = new DirectoryClassLoader(List.of(outputPath.toFile()), (ClassLoader)classLoader)) {
|
||||
var result = new HashMap<String, Class<?>>();
|
||||
for (var file : filenames) {
|
||||
var sf = compiler.sourceFiles.get(file);
|
||||
var classes = sf.getClasses();
|
||||
var classes = compiler.sourceFiles.get(file).getClasses();
|
||||
|
||||
result.putAll(classes.stream().map(cli -> {
|
||||
try {
|
||||
@@ -74,8 +71,7 @@ public class TestCodegen {
|
||||
}
|
||||
|
||||
public static Class<?> generateClass(TargetStructure clazz, IByteArrayClassLoader classLoader) throws IOException, ClassNotFoundException {
|
||||
ASTToTargetAST converter = new ASTToTargetAST(List.of(new ResultSet(Set.of())), classLoader);
|
||||
Codegen codegen = new Codegen(clazz, new JavaTXCompiler(List.of()), converter);
|
||||
Codegen codegen = new Codegen(clazz, new JavaTXCompiler(List.of()), null);
|
||||
var code = codegen.generate();
|
||||
writeClassFile(clazz.qualifiedName().getClassName(), code);
|
||||
return classLoader.loadClass(code);
|
||||
@@ -276,7 +272,7 @@ public class TestCodegen {
|
||||
public void testLambda() throws Exception {
|
||||
var classLoader = createClassLoader();
|
||||
// var fun = classLoader.loadClass(Path.of(System.getProperty("user.dir"), "src/test/java/targetast/Fun1$$.class"));
|
||||
var interfaceType = TargetFunNType.fromParams(List.of(TargetType.Integer), 1, false);
|
||||
var interfaceType = TargetFunNType.fromParams(List.of(TargetType.Integer), 1);
|
||||
|
||||
var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("CGLambda"));
|
||||
targetClass.addConstructor(Opcodes.ACC_PUBLIC, List.of(), new TargetBlock(List.of(new TargetMethodCall(null, new TargetSuper(TargetType.Object), List.of(), TargetType.Object, "<init>", false, false, false))));
|
||||
|
||||
@@ -49,7 +49,6 @@ public class TestGenerics {
|
||||
private static Result computeGenerics(String filename) throws IOException, ClassNotFoundException {
|
||||
var file = Path.of(rootDirectory + filename).toFile();
|
||||
var compiler = new JavaTXCompiler(List.of(file), List.of(file.getParentFile()), new File(bytecodeDirectory), true);
|
||||
compiler.parseAll();
|
||||
var inference = compiler.typeInference(file);
|
||||
compiler.generateBytecode(new File(bytecodeDirectory), inference);
|
||||
var sf = compiler.sourceFiles.get(file);
|
||||
|
||||
Reference in New Issue
Block a user