36 lines
1.5 KiB
Java
36 lines
1.5 KiB
Java
package io.gitlab.jfronny.muscript.data.dynamic.type;
|
|
|
|
import io.gitlab.jfronny.commons.data.ImmCollection;
|
|
|
|
import java.util.*;
|
|
|
|
public record DTypeSum(Set<DType> elements) implements DType {
|
|
public DTypeSum(Set<DType> elements) {
|
|
if (elements.isEmpty()) throw new IllegalArgumentException("Cannot create sum type without elements");
|
|
|
|
Set<DType> simple = new LinkedHashSet<>();
|
|
Set<DType> list = new LinkedHashSet<>();
|
|
Set<DType> object = new LinkedHashSet<>();
|
|
|
|
Queue<DType> toProcess = new LinkedList<>(elements);
|
|
while (!toProcess.isEmpty()) {
|
|
DType type = toProcess.remove();
|
|
//TODO replace with pattern match
|
|
if (type instanceof DTypePrimitive || type instanceof DTypeAnd || type instanceof DTypeCallable) simple.add(type);
|
|
else if (type instanceof DTypeList u) list.add(u.entryType());
|
|
else if (type instanceof DTypeObject u) object.add(u.entryType());
|
|
else if (type instanceof DTypeSum u) toProcess.addAll(u.elements);
|
|
else throw new IllegalArgumentException("Unexpected DType implementation: " + type.getClass());
|
|
}
|
|
|
|
if (!list.isEmpty()) simple.add(new DTypeList(list.contains(null) ? null : new DTypeSum(list)));
|
|
if (!object.isEmpty()) simple.add(new DTypeObject(object.contains(null) ? null : new DTypeSum(object)));
|
|
this.elements = ImmCollection.copyOf(simple);
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
return DType.toString(this);
|
|
}
|
|
}
|