Skip to content

Commit

Permalink
GH-556 Use autocasts as a base resource to determine the result of Ty…
Browse files Browse the repository at this point in the history
…pe#isAssignableFrom method, fix conditional parser, for-each parser and try-catch parser, [...]
  • Loading branch information
dzikoysk committed Dec 2, 2020
1 parent 36346ae commit 87ba211
Show file tree
Hide file tree
Showing 20 changed files with 122 additions and 212 deletions.
39 changes: 2 additions & 37 deletions examples/tests/current_test.panda
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,7 @@ main {
break // or just stop
}

// create TestArray instance and
TestArray testArray = new TestArray(7);
testArray.modify(test)

// print array and some logical expressions
log "Content of " + "array " + testArray.array.asString()
// logical expressions
log "OR v AND: " + (false || false) + ", " + false || true, true && false, true && true
log "Compare: " + 1 > 2, 1 > 2, 1 < 2, 2 < 1
log "Random", (false || false) + ", " + false || true, true && false, true && true, (false || false) + ", " + false || true, true && false, true && true
Expand All @@ -114,6 +109,7 @@ main {
log creaseValue

// create instance of class imported from another file
// should use generated default constructor
Required required = new Required()
required.hello()

Expand Down Expand Up @@ -276,37 +272,6 @@ internal type Test {

}

// array test
internal type TestArray {

// shared array
shared Array<String> array

// create TestArray and define array size
constructor (Int size) {
this.array = new Array<String>(size)
}

// modify some values in array
shared modify (Test test) {
// this.getArray()[Test.INDEX] = "Hello Array"
// array[6] = String.valueOf(this)

// log "Value at array[test.index]: " + this.getArray()[test.INDEX]
varargs(array)
}

shared varargs (String varargs) {
log varargs
}

// get array
internal getArray() -> Array<String> {
return array
}

}

internal type CustomThread : Thread {

constructor () {
Expand Down
2 changes: 2 additions & 0 deletions examples/tests/current_test_required.panda
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export org.panda_lang.utilities.commons.StringUtils
// shared class to test visibility access
shared type Required {

// should generate default empty constructor

shared hello() {
log "Required print"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.panda_lang.language.FrameworkController;
import org.panda_lang.language.architecture.module.ModulePath;
import org.panda_lang.language.architecture.module.TypeLoader;
import org.panda_lang.language.architecture.type.generator.TypeGenerator;
import org.panda_lang.language.interpreter.Interpreter;
import org.panda_lang.language.interpreter.logging.LoggerHolder;
import org.panda_lang.language.interpreter.source.SourceService;
Expand Down Expand Up @@ -51,6 +52,13 @@ public interface Environment extends LoggerHolder {
*/
TypeLoader getTypeLoader();

/**
* Get default type generator
*
* @return the type generator
*/
TypeGenerator getTypeGenerator();

/**
* Get sources used by this environment
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public static Result<Expression, String> equalize(Expression expression, Signatu
return Result.ok(expression);
}

if (expression.getSignature().isAssignableFrom(expected)) {
if (expected.isAssignableFrom(expression.getSignature())) {
return Result.ok(expression);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;

public class PandaType extends AbstractMetadata implements Type {
Expand Down Expand Up @@ -118,6 +117,7 @@ public void addBase(TypedSignature baseSignature) {
}

bases.add(baseSignature);
autocasts.put(baseSignature.fetchType(), (originalType, object, resultType) -> object);
}

@Override
Expand All @@ -142,10 +142,7 @@ public boolean equals(@Nullable Object to) {

@Override
public boolean isAssignableFrom(Type from) {
return this.equals(from)
|| from.getBases().stream().anyMatch(base -> isAssignableFrom(base.fetchType()))
|| from.getAutocasts().stream().anyMatch(this::isAssignableFrom)
|| from.getAutocast(this).isPresent();
return this.equals(from) || from.getAutocast(this).isDefined();
}

@Override
Expand Down Expand Up @@ -173,14 +170,26 @@ else if (TypeField.class.isAssignableFrom(propertyType)) {

@Override
public Option<Autocast<?, ?>> getAutocast(Type to) {
return PandaStream.of(autocasts.entrySet())
.find(autocastEntry -> to.isAssignableFrom(autocastEntry.getKey()))
.map(Entry::getValue);
Autocast<?, ?> autocast = autocasts.get(to);

if (autocast != null) {
return Option.of(autocast);
}

for (TypedSignature base : bases) {
Option<Autocast<?, ?>> baseAutocast = base.fetchType().getAutocast(to);

if (baseAutocast != null) {
return baseAutocast;
}
}

return Option.none();
}

@Override
public Collection<? extends Type> getAutocasts() {
return autocasts.keySet();
public Map<? extends Type, ? extends Autocast<?, ?>> getAutocasts() {
return autocasts;
}

@Override
Expand All @@ -205,7 +214,8 @@ public Collection<? extends TypedSignature> getBases() {

@Override
public Option<? extends TypedSignature> getSuperclass() {
return PandaStream.of(getBases()).find(base -> Kind.isClass(base.fetchType()));
return PandaStream.of(getBases())
.find(base -> Kind.isClass(base.fetchType()));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.panda_lang.utilities.commons.function.Option;

import java.util.Collection;
import java.util.Map;

/**
* Extensible owner of properties
Expand Down Expand Up @@ -124,14 +125,14 @@ default boolean is(String name) {
* @param to the type to search for
* @return the autocast
*/
Option<? extends Autocast<?, ?>> getAutocast(Type to);
Option<Autocast<?, ?>> getAutocast(Type to);

/**
* Get all of the supported autocasts
*
* @return collection of autocasts
*/
Collection<? extends Type> getAutocasts();
Map<? extends Type, ? extends Autocast<?, ?>> getAutocasts();

/**
* Get supertypes of type
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,15 @@

public final class TypeGenerator {

protected final Map<String, Type> initializedTypes = new HashMap<>();
protected final Map<Class<?>, Type> initializedTypes = new HashMap<>();
protected final FrameworkController frameworkController;

public TypeGenerator(FrameworkController frameworkController) {
this.frameworkController = frameworkController;
}

public Reference generate(Module module, String name, Class<?> javaType) {
String identifier = getId(module, name);

return Option.of(initializedTypes.get(identifier))
return Option.of(initializedTypes.get(javaType))
.map(Reference::new)
.orElse(() -> module.get(name))
.orElseGet(() -> {
Expand Down Expand Up @@ -85,6 +83,11 @@ public Reference generate(Module module, String name, Class<?> javaType) {
type.addBase(typeLoader.load(findOrGenerate(typeLoader, module, javaInterface)).getSignature());
}

if (!javaType.equals(Object.class) && type.getBases().isEmpty()) {
// type.addAutocast(typeLoader.requireType("panda::Object"), (originalType, object, resultType) -> object);
type.addBase(typeLoader.requireType("panda::Object").getSignature());
}

if (!Modifier.isPublic(javaType.getModifiers())) {
return;
}
Expand All @@ -100,7 +103,7 @@ public Reference generate(Module module, String name, Class<?> javaType) {

for (Constructor<?> constructor : ReflectionUtils.getByModifier(javaType.getDeclaredConstructors(), Modifier.PUBLIC)) {
ConstructorGenerator generator = new ConstructorGenerator(this, initializedType, constructor);
initializedType.getConstructors().declare(name, () -> generator.generate(typeLoader));
initializedType.getConstructors().declare(constructor.toString(), () -> generator.generate(typeLoader));
}

for (Method method : ReflectionUtils.getByModifier(javaType.getDeclaredMethods(), Modifier.PUBLIC)) {
Expand All @@ -109,7 +112,7 @@ public Reference generate(Module module, String name, Class<?> javaType) {
}
});

initializedTypes.put(identifier, type);
initializedTypes.put(javaType, type);
completableType.complete(type);

return new Reference(type);
Expand All @@ -127,7 +130,7 @@ protected Type findOrGenerate(TypeLoader typeLoader, Module module, Class<?> jav
return typeValue.get();
}

Type type = initializedTypes.get(getId(module, javaType.getSimpleName()));
Type type = initializedTypes.get(javaType);

if (type != null) {
return type;
Expand All @@ -136,12 +139,4 @@ protected Type findOrGenerate(TypeLoader typeLoader, Module module, Class<?> jav
return generate(module, javaType.getSimpleName(), javaType).fetchType();
}

protected void disposeCache() {
initializedTypes.clear();
}

private String getId(Module module, String name) {
return module.getName() + "::" + name;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -52,44 +52,15 @@ public Option<Adjustment<T>> match(Collection<? extends T> collection, Signature
}

// map arguments into parameters
int[] target = new int[requiredTypes.length];
int index = 0, required = 0, varArgs = 0;
int index = 0, required = 0;

// loop as long parameters and types are available
for (; (index < parameters.length) && (required < requiredTypes.length); index++) {
PropertyParameter parameter = parameters[index];

//if (!parameter.isVarargs()) {
target[required] = index;

if (!parameter.getSignature().isAssignableFrom(requiredTypes[required++])) {
return null;
}

continue;
//}

/*
// varargs parameter has to be array
Type type = ((ArrayType) parameter.getType()).getArrayType();
varArgs++;
// read vararg
while (required < requiredTypes.length) {
Signature nextType = requiredTypes[required];
if (!type.isAssignableFrom(nextType)) {
// array was directly passed to the varargs
if (nextType.isAssignableFrom(parameter.getType())) {
target[required++] = index;
}
break;
}
target[required++] = index;
if (!parameter.getSignature().isAssignableFrom(requiredTypes[required++])) {
return null;
}
*/
}

// return if does not match
Expand All @@ -103,54 +74,6 @@ public Option<Adjustment<T>> match(Collection<? extends T> collection, Signature
}

return new Adjustment<>(executable, arguments);

/*
// return result without varargs mappings
if (varArgs == 0) {
return new Adjustment<>(executable, arguments);
}
@SuppressWarnings("unchecked")
List<Expression>[] mapped = new List[parameters.length];
// group arguments
for (int targetIndex = 0; targetIndex < target.length; ) {
int targetParameter = target[targetIndex];
List<Expression> section = mapped[targetParameter];
if (section == null) {
section = (mapped[targetParameter] = new ArrayList<>(arguments.length - parameters.length - varArgs + 1));
}
section.add(arguments[targetIndex]);
targetIndex++;
}
Expression[] fixedArguments = new Expression[mapped.length];
// map arguments
for (int argumentIndex = 0; argumentIndex < mapped.length; argumentIndex++) {
List<Expression> expressions = mapped[argumentIndex];
if (expressions.size() == 1) {
fixedArguments[argumentIndex] = expressions.get(0);
continue;
}
Expression[] expressionsArray = expressions.toArray(new Expression[0]);
// generate varargs array expression
fixedArguments[argumentIndex] = new AbstractDynamicExpression(((ArrayType) parameters[argumentIndex].getType()).getArrayType()) {
@Override
@SuppressWarnings("unchecked")
public Object evaluate(ProcessStack stack, Object instance) throws Exception {
return ExpressionUtils.evaluate(stack, instance, expressionsArray);
}
}.toExpression();
}
return new Adjustment<>(executable, fixedArguments);
*/
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ public final class Keywords {

public static final Keyword ELSE = add(VALUES, new Keyword("else"));

public static final Keyword ELSE_IF = add(VALUES, new Keyword("else if"));

public static final Keyword EXPORT = add(VALUES, new Keyword("export"));

public static final Keyword FOREACH = add(VALUES, new Keyword("foreach"));
Expand Down
Loading

0 comments on commit 87ba211

Please sign in to comment.