" argument.
-//
-// Note however, that you may define your own "run" and "debug" task if you
-// prefer. In this case NetBeans will not add these tasks but you may rely on
-// your own implementation.
-if (!hasProperty('mainClass')) {
- ext.mainClass = ''
+plugins {
+ id 'zencode-common'
+ id 'zencode-publish'
}
dependencies {
- compile project(':Shared')
+ api project(':Shared')
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/AccessScope.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/AccessScope.java
deleted file mode 100644
index 287a661b4..000000000
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/AccessScope.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.openzen.zenscript.codemodel;
-
-import java.util.Objects;
-
-/**
- *
- * @author Hoofdgebruiker
- */
-public final class AccessScope {
- public final Module module;
- public final HighLevelDefinition definition;
-
- public AccessScope(Module module, HighLevelDefinition definition) {
- this.module = module;
- this.definition = definition;
- }
-
- public boolean hasAccessTo(AccessScope other, int access) {
- if (Modifiers.isPublic(access))
- return true;
- if (definition == null)
- return false;
- if (definition == other.definition || definition.isOuterOf(other.definition) || other.definition.isOuterOf(definition))
- return true;
- if (Modifiers.isPrivate(access))
- return false;
- if (Modifiers.isInternal(access))
- return module == other.module;
- if (Modifiers.isProtected(access))
- return definition.isSubclassOf(other.definition);
-
- return false;
- }
-
- @Override
- public int hashCode() {
- int hash = 7;
- hash = 79 * hash + Objects.hashCode(this.module);
- hash = 79 * hash + Objects.hashCode(this.definition);
- return hash;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null || getClass() != obj.getClass())
- return false;
-
- final AccessScope other = (AccessScope) obj;
- return module == other.module && definition == other.definition;
- }
-}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/CompareType.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/CompareType.java
index 4e0d90775..1591c23d2 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/CompareType.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/CompareType.java
@@ -2,8 +2,6 @@
/**
* Used to indicate comparison types.
- *
- * @author Stan Hebben
*/
public enum CompareType {
LT("<"),
@@ -12,9 +10,9 @@ public enum CompareType {
NE("!="),
LE("<="),
GE(">=");
-
+
public final String str;
-
+
CompareType(String str) {
this.str = str;
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/FunctionHeader.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/FunctionHeader.java
index 385dda32d..38267ed14 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/FunctionHeader.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/FunctionHeader.java
@@ -1,114 +1,140 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-import java.util.*;
-
import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zenscript.codemodel.compilation.ExpressionCompiler;
+import org.openzen.zenscript.codemodel.compilation.ResolvedType;
+import org.openzen.zenscript.codemodel.compilation.TypeResolver;
import org.openzen.zenscript.codemodel.expression.CallArguments;
-import org.openzen.zenscript.codemodel.expression.Expression;
import org.openzen.zenscript.codemodel.generic.TypeParameter;
-import org.openzen.zenscript.codemodel.type.ArrayTypeID;
-import org.openzen.zenscript.codemodel.type.BasicTypeID;
-import org.openzen.zenscript.codemodel.type.GlobalTypeRegistry;
-import org.openzen.zenscript.codemodel.scope.TypeScope;
-import org.openzen.zenscript.codemodel.type.TypeID;
-
-/**
- *
- * @author Hoofdgebruiker
- */
+import org.openzen.zenscript.codemodel.type.*;
+
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Stream;
+
public class FunctionHeader {
+ public static final FunctionHeader PLACEHOLDER = new FunctionHeader(BasicTypeID.VOID);
+ public static final FunctionHeader EMPTY = new FunctionHeader(BasicTypeID.VOID);
+
public final TypeParameter[] typeParameters;
- private TypeID returnType;
public final FunctionParameter[] parameters;
public final TypeID thrownType;
-
public final int minParameters;
public final int maxParameters;
public final boolean hasUnknowns;
-
+ private TypeID returnType;
+
public FunctionHeader(TypeID returnType) {
if (returnType == null)
throw new NullPointerException();
-
+
this.typeParameters = TypeParameter.NONE;
this.returnType = returnType;
this.parameters = FunctionParameter.NONE;
this.thrownType = null;
-
+
minParameters = 0;
maxParameters = 0;
hasUnknowns = returnType == BasicTypeID.UNDETERMINED;
}
-
+
public FunctionHeader(TypeID returnType, TypeID... parameterTypes) {
if (returnType == null)
- throw new NullPointerException();
-
+ throw new NullPointerException("The function needs a return type");
+
this.typeParameters = TypeParameter.NONE;
this.returnType = returnType;
this.parameters = new FunctionParameter[parameterTypes.length];
this.thrownType = null;
-
+
for (int i = 0; i < parameterTypes.length; i++)
- parameters[i] = new FunctionParameter(parameterTypes[i], null);
-
+ parameters[i] = new FunctionParameter(parameterTypes[i], "param" + i);
+
minParameters = parameterTypes.length;
maxParameters = parameterTypes.length;
hasUnknowns = hasUnknowns(parameterTypes, returnType);
}
-
+
public FunctionHeader(TypeID returnType, FunctionParameter... parameters) {
if (returnType == null)
- throw new NullPointerException();
-
+ throw new NullPointerException("The function needs a return type");
+
this.typeParameters = TypeParameter.NONE;
this.returnType = returnType;
this.parameters = parameters;
this.thrownType = null;
-
+
minParameters = getMinParameters(parameters);
maxParameters = getMaxParameters(parameters);
hasUnknowns = hasUnknowns(parameters, returnType);
}
-
+
public FunctionHeader(TypeParameter[] typeParameters, TypeID returnType, TypeID thrownType, FunctionParameter... parameters) {
if (returnType == null)
throw new NullPointerException();
if (typeParameters == null)
throw new NullPointerException();
-
+
this.typeParameters = typeParameters;
this.returnType = returnType;
this.parameters = parameters;
this.thrownType = thrownType;
-
+
minParameters = getMinParameters(parameters);
maxParameters = getMaxParameters(parameters);
hasUnknowns = hasUnknowns(parameters, returnType);
}
-
- public boolean isVariadic() {
- return parameters.length > 0 && parameters[parameters.length - 1].variadic;
+
+ public FunctionHeader withReturnType(TypeID returnType) {
+ return new FunctionHeader(typeParameters, returnType, thrownType, parameters);
}
-
- public boolean isVariadicCall(CallArguments arguments, TypeScope scope) {
- if (!isVariadic())
- return false;
- if (arguments.arguments.length < parameters.length - 1)
- return false;
- if (arguments.arguments.length != parameters.length)
+
+ public FunctionHeader withThrownType(TypeID thrownType) {
+ return new FunctionHeader(typeParameters, returnType, thrownType, parameters);
+ }
+
+ private static int getMinParameters(FunctionParameter[] parameters) {
+ for (int i = 0; i < parameters.length; i++)
+ if (parameters[i].defaultValue != null || parameters[i].variadic)
+ return i;
+
+ return parameters.length;
+ }
+
+ private static int getMaxParameters(FunctionParameter[] parameters) {
+ if (parameters.length == 0)
+ return 0;
+
+ return parameters[parameters.length - 1].variadic ? Integer.MAX_VALUE : parameters.length;
+ }
+
+ private static boolean hasUnknowns(TypeID[] types, TypeID returnType) {
+ if (returnType == BasicTypeID.UNDETERMINED)
return true;
- if (scope.getTypeMembers(arguments.arguments[arguments.arguments.length - 1].type).canCastImplicit(parameters[parameters.length - 1].type))
- return false;
-
- return true;
+
+ for (TypeID type : types)
+ if (type == BasicTypeID.UNDETERMINED)
+ return true;
+
+ return false;
+ }
+
+ private static boolean hasUnknowns(FunctionParameter[] parameters, TypeID returnType) {
+ if (returnType == BasicTypeID.UNDETERMINED)
+ return true;
+
+ for (FunctionParameter parameter : parameters)
+ if (parameter.type == BasicTypeID.UNDETERMINED)
+ return true;
+
+ return false;
+ }
+
+ public boolean isVariadic() {
+ return parameters.length > 0 && parameters[parameters.length - 1].variadic;
}
-
+
public boolean isVariadicCall(CallArguments arguments) {
if (!isVariadic())
return false;
@@ -118,37 +144,36 @@ public boolean isVariadicCall(CallArguments arguments) {
return true;
if (arguments.arguments[arguments.arguments.length - 1].type.equals(parameters[parameters.length - 1].type))
return false;
-
+
return true;
}
-
+
public boolean[] useTypeParameters() {
boolean[] useTypeParameters = new boolean[typeParameters.length];
- for (int i = 0; i < useTypeParameters.length; i++)
- useTypeParameters[i] = true;
-
+ Arrays.fill(useTypeParameters, true);
+
return useTypeParameters;
}
-
+
public TypeID getReturnType() {
return returnType;
}
-
+
public void setReturnType(TypeID returnType) {
if (returnType == null)
- throw new NullPointerException();
-
+ throw new NullPointerException("The function needs a return type");
+
this.returnType = returnType;
}
-
+
public TypeID getParameterType(boolean isVariadic, int index) {
return getParameter(isVariadic, index).type;
}
-
+
public FunctionParameter getParameter(boolean isVariadic, int index) {
if (isVariadic && index >= parameters.length - 1) {
final FunctionParameter parameter = parameters[parameters.length - 1];
- if(parameter.type instanceof ArrayTypeID) {
+ if (parameter.type instanceof ArrayTypeID) {
return new FunctionParameter(((ArrayTypeID) parameter.type).elementType, parameter.name);
}
return parameter;
@@ -156,40 +181,20 @@ public FunctionParameter getParameter(boolean isVariadic, int index) {
return parameters[index];
}
}
-
- public boolean isDenormalized() {
- if (!returnType.getNormalized().equals(returnType))
- return true;
- for (FunctionParameter parameter : parameters)
- if (parameter.type.getNormalized() != parameter.type)
- return true;
-
- return false;
- }
-
- public FunctionHeader normalize(GlobalTypeRegistry registry) {
- if (!isDenormalized())
- return this;
-
- FunctionParameter[] normalizedParameters = new FunctionParameter[parameters.length];
- for (int i = 0; i < normalizedParameters.length; i++)
- normalizedParameters[i] = parameters[i].normalize(registry);
- return new FunctionHeader(typeParameters, returnType.getNormalized(), thrownType == null ? null : thrownType.getNormalized(), normalizedParameters);
- }
-
+
public int getNumberOfTypeParameters() {
return typeParameters.length;
}
-
+
public boolean hasAnyDefaultValues() {
for (FunctionParameter parameter : parameters)
if (parameter.defaultValue != null)
return true;
-
+
return false;
}
-
- public FunctionHeader inferFromOverride(GlobalTypeRegistry registry, FunctionHeader overridden) {
+
+ public FunctionHeader inferFromOverride(FunctionHeader overridden) {
TypeParameter[] resultTypeParameters = typeParameters;
TypeID resultReturnType = this.returnType;
if (resultReturnType == BasicTypeID.UNDETERMINED)
@@ -198,7 +203,7 @@ public FunctionHeader inferFromOverride(GlobalTypeRegistry registry, FunctionHea
TypeID resultThrownType = this.thrownType;
if (resultThrownType == null && overridden.thrownType != null)
resultThrownType = overridden.thrownType;
-
+
FunctionParameter[] resultParameters = Arrays.copyOf(parameters, parameters.length);
for (int i = 0; i < resultParameters.length; i++) {
if (resultParameters[i].type == BasicTypeID.UNDETERMINED) {
@@ -207,50 +212,10 @@ public FunctionHeader inferFromOverride(GlobalTypeRegistry registry, FunctionHea
resultParameters[i] = new FunctionParameter(original.type, parameter.name, parameter.defaultValue, original.variadic);
}
}
-
+
return new FunctionHeader(resultTypeParameters, resultReturnType, resultThrownType, resultParameters);
}
-
- public boolean matchesExactly(CodePosition position, CallArguments arguments, TypeScope scope) {
- if (arguments.arguments.length < minParameters || arguments.arguments.length > maxParameters)
- return false;
-
- FunctionHeader header = fillGenericArguments(position, scope, arguments.typeArguments);
- final boolean variadicCall = header.isVariadicCall(arguments, scope);
- for(int i = 0; i < arguments.arguments.length; i++) {
- if(!arguments.arguments[i].type.equals(header.getParameterType(variadicCall, i)))
- return false;
- }
-
- return true;
- }
-
- public boolean matchesImplicitly(CodePosition position, CallArguments arguments, TypeScope scope) {
- if (!accepts(arguments.arguments.length))
- return false;
-
- FunctionHeader header = fillGenericArguments(position, scope, arguments.typeArguments);
- if(isVariadic()) {
- boolean matches = true;
- for (int i = 0; i < arguments.arguments.length; i++) {
- if (!scope.getTypeMembers(arguments.arguments[i].type).canCastImplicit(header.getParameterType(true, i))) {
- matches = false;
- break;
- }
- }
- if(matches) {
- return true;
- }
- }
-
- for (int i = 0; i < arguments.arguments.length; i++) {
- if (!scope.getTypeMembers(arguments.arguments[i].type).canCastImplicit(header.parameters[i].type))
- return false;
- }
-
- return true;
- }
-
+
public String getCanonicalWithoutReturnType() {
StringBuilder result = new StringBuilder();
if (getNumberOfTypeParameters() > 0) {
@@ -271,84 +236,77 @@ public String getCanonicalWithoutReturnType() {
result.append(')');
return result.toString();
}
-
+
public String getCanonical() {
return getCanonicalWithoutReturnType() + returnType.toString();
}
-
+
public boolean hasInferenceBlockingTypeParameters(TypeParameter[] parameters) {
+ InferenceBlockingTypeParameterVisitor inferenceBlockingVisitor = new InferenceBlockingTypeParameterVisitor(parameters);
for (int i = 0; i < this.parameters.length; i++)
- if (this.parameters[i].type.hasInferenceBlockingTypeParameters(parameters))
+ if (this.parameters[i].type.accept(inferenceBlockingVisitor))
return true;
-
+
return false;
}
-
- public boolean accepts(TypeScope scope, Expression... arguments) {
- if (parameters.length != arguments.length)
- return false;
-
- for (int i = 0; i < arguments.length; i++) {
- if (!scope.getTypeMembers(arguments[i].type).canCastImplicit(parameters[i].type))
- return false;
- }
-
- return true;
- }
-
- public boolean canOverride(TypeScope scope, FunctionHeader other) {
+
+ public boolean canOverride(TypeResolver resolver, FunctionHeader other) {
if (other == null)
throw new NullPointerException();
if (parameters.length != other.parameters.length)
return false;
- if (returnType != BasicTypeID.UNDETERMINED && !scope.getTypeMembers(returnType).canCastImplicit(other.returnType))
+ if (returnType != BasicTypeID.UNDETERMINED
+ && !returnType.equals(other.returnType)
+ && !resolver.resolve(returnType).canCastImplicitlyTo(other.returnType))
return false;
-
+
for (int i = 0; i < parameters.length; i++) {
if (parameters[i].type == BasicTypeID.UNDETERMINED)
continue;
-
+
if (parameters[i].variadic != other.parameters[i].variadic)
return false;
- if (!scope.getTypeMembers(other.parameters[i].type).canCastImplicit(parameters[i].type))
+ if (other.parameters[i].type.equals(parameters[i].type))
+ continue;
+ if (!resolver.resolve(other.parameters[i].type).canCastImplicitlyTo(parameters[i].type))
return false;
}
-
+
return true;
}
-
+
/**
* Checks if two function headers are equivalent. Functions headers are
* equivalent if their types are the same.
- *
+ *
* @param other
- * @return
+ * @return
*/
public boolean isEquivalentTo(FunctionHeader other) {
if (parameters.length != other.parameters.length)
return false;
-
+
for (int i = 0; i < parameters.length; i++) {
if (!parameters[i].type.equals(other.parameters[i].type))
return false;
}
-
+
return true;
}
-
+
/**
* Checks if two function headers are similar. "similar" means that there
* exists a set of parameters for which there is no way to determine which
* one to call.
- *
+ *
* Note that this does not mean that there is never confusion about which
* method to call. There can be confusion due to implicit conversions. This
* can be resolved by performing the conversions explicitly.
- *
+ *
* It is illegal to have two similar methods with the same name.
- *
+ *
* @param other
- * @return
+ * @return
*/
public boolean isSimilarTo(FunctionHeader other) {
int common = Math.min(parameters.length, other.parameters.length);
@@ -364,26 +322,26 @@ public boolean isSimilarTo(FunctionHeader other) {
if (other.parameters[i].defaultValue == null)
return false;
}
-
+
return true;
}
-
- public FunctionHeader instanceForCall(CodePosition position, GlobalTypeRegistry registry, CallArguments arguments) {
+
+ public FunctionHeader instanceForCall(CallArguments arguments) {
if (arguments.getNumberOfTypeArguments() > 0) {
Map typeParameters = TypeID.getMapping(this.typeParameters, arguments.typeArguments);
- return instance(new GenericMapper(position, registry, typeParameters));
+ return instance(new GenericMapper(typeParameters, arguments.expansionTypeArguments));
} else {
return this;
}
}
-
+
public FunctionHeader withGenericArguments(GenericMapper mapper) {
if (typeParameters.length > 0)
- mapper = mapper.getInner(mapper.position, mapper.registry, TypeID.getSelfMapping(mapper.registry, typeParameters));
-
+ mapper = mapper.getInner(TypeID.getSelfMapping(typeParameters));
+
return instance(mapper);
}
-
+
private FunctionHeader instance(GenericMapper mapper) {
TypeID returnType = this.returnType.instance(mapper);
FunctionParameter[] parameters = new FunctionParameter[this.parameters.length];
@@ -392,13 +350,13 @@ private FunctionHeader instance(GenericMapper mapper) {
}
return new FunctionHeader(typeParameters, returnType, thrownType == null ? null : thrownType.instance(mapper), parameters);
}
-
- public FunctionHeader fillGenericArguments(CodePosition position, TypeScope scope, TypeID[] arguments) {
+
+ /*public FunctionHeader fillGenericArguments(TypeScope scope, TypeID[] arguments) {
if (arguments == null || arguments.length == 0)
return this;
-
+
Map typeArguments = TypeID.getMapping(typeParameters, arguments);
- GenericMapper mapper = scope.getLocalTypeParameters().getInner(position, scope.getTypeRegistry(), typeArguments);
+ GenericMapper mapper = scope.getLocalTypeParameters().getInner(typeArguments);
TypeID returnType = this.returnType.instance(mapper);
FunctionParameter[] parameters = new FunctionParameter[this.parameters.length];
@@ -406,45 +364,50 @@ public FunctionHeader fillGenericArguments(CodePosition position, TypeScope scop
parameters[i] = this.parameters[i].withGenericArguments(mapper);
}
return new FunctionHeader(TypeParameter.NONE, returnType, thrownType == null ? null : thrownType.instance(mapper), parameters);
- }
-
+ }*/
+
public FunctionHeader forTypeParameterInference() {
return new FunctionHeader(BasicTypeID.UNDETERMINED, parameters);
}
-
+
public FunctionHeader forLambda(FunctionHeader lambdaHeader) {
FunctionParameter[] parameters = new FunctionParameter[lambdaHeader.parameters.length];
for (int i = 0; i < lambdaHeader.parameters.length; i++)
parameters[i] = new FunctionParameter(this.parameters[i].type, lambdaHeader.parameters[i].name);
-
+
return new FunctionHeader(typeParameters, returnType, thrownType, parameters);
}
-
- public FunctionParameter getVariadicParameter() {
+
+ public Optional getVariadicParameter() {
if (parameters.length == 0)
- return null;
- if (parameters[parameters.length - 1].variadic)
- return parameters[parameters.length - 1];
-
- return null;
- }
-
- public String explainWhyIncompatible(TypeScope scope, CallArguments arguments) {
+ return Optional.empty();
+ else if (parameters[parameters.length - 1].variadic)
+ return Optional.of(parameters[parameters.length - 1]);
+ else
+ return Optional.empty();
+ }
+
+ public Optional getVariadicParameterType() {
+ return getVariadicParameter().map(p -> p.type);
+ }
+
+ public String explainWhyIncompatible(ExpressionCompiler compiler, CodePosition position, CallArguments arguments) {
if (this.parameters.length != arguments.arguments.length)
return parameters.length + " parameters expected but " + arguments.arguments.length + " given.";
-
+
if (getNumberOfTypeParameters() != arguments.getNumberOfTypeArguments())
return getNumberOfTypeParameters() + " type parameters expected but " + arguments.getNumberOfTypeArguments() + " given.";
-
+
for (int i = 0; i < parameters.length; i++) {
- if (!scope.getTypeMembers(arguments.arguments[i].type).canCastImplicit(parameters[i].type)) {
+ ResolvedType resolved = compiler.resolve(arguments.arguments[i].type);
+ if (!resolved.canCastImplicitlyTo(parameters[i].type)) {
return "Parameter " + i + ": cannot cast " + arguments.arguments[i].type + " to " + parameters[i].type;
}
}
-
+
return "Method should be compatible";
}
-
+
@Override
public String toString() {
StringBuilder result = new StringBuilder();
@@ -463,85 +426,52 @@ public String toString() {
result.append(", ");
result.append(parameters[i].toString());
}
- result.append(") as ");
+ result.append("): ");
result.append(returnType.toString());
return result.toString();
}
- private static int getMinParameters(FunctionParameter[] parameters) {
- for (int i = 0; i < parameters.length; i++)
- if (parameters[i].defaultValue != null || parameters[i].variadic)
- return i;
-
- return parameters.length;
- }
-
- private static int getMaxParameters(FunctionParameter[] parameters) {
- if (parameters.length == 0)
- return 0;
-
- return parameters[parameters.length - 1].variadic ? Integer.MAX_VALUE : parameters.length;
- }
-
- private static boolean hasUnknowns(TypeID[] types, TypeID returnType) {
- if (returnType == BasicTypeID.UNDETERMINED)
- return true;
-
- for (TypeID type : types)
- if (type == BasicTypeID.UNDETERMINED)
- return true;
-
- return false;
+ public boolean accepts(int arguments) {
+ return arguments >= this.minParameters && arguments <= this.maxParameters;
}
-
- private static boolean hasUnknowns(FunctionParameter[] parameters, TypeID returnType) {
- if (returnType == BasicTypeID.UNDETERMINED)
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
return true;
-
- for (FunctionParameter parameter : parameters)
- if (parameter.type == BasicTypeID.UNDETERMINED)
- return true;
-
- return false;
+ if (o == null || getClass() != o.getClass())
+ return false;
+
+ FunctionHeader that = (FunctionHeader) o;
+
+ if (minParameters != that.minParameters)
+ return false;
+ if (maxParameters != that.maxParameters)
+ return false;
+ if (hasUnknowns != that.hasUnknowns)
+ return false;
+ if (!Arrays.equals(typeParameters, that.typeParameters))
+ return false;
+ if (!returnType.equals(that.returnType))
+ return false;
+ if (!Arrays.equals(parameters, that.parameters))
+ return false;
+ return thrownType == that.thrownType;
}
- public boolean accepts(int arguments) {
- return arguments >= this.minParameters && arguments <= this.maxParameters;
+ @Override
+ public int hashCode() {
+ int result = Arrays.hashCode(typeParameters);
+ result = 31 * result + returnType.hashCode();
+ result = 31 * result + Arrays.hashCode(parameters);
+ result = 31 * result + (thrownType != null ? thrownType.hashCode() : 0);
+ result = 31 * result + minParameters;
+ result = 31 * result + maxParameters;
+ result = 31 * result + (hasUnknowns ? 1 : 0);
+ return result;
}
-
- @Override
- public boolean equals(Object o) {
- if(this == o)
- return true;
- if(o == null || getClass() != o.getClass())
- return false;
-
- FunctionHeader that = (FunctionHeader) o;
-
- if(minParameters != that.minParameters)
- return false;
- if(maxParameters != that.maxParameters)
- return false;
- if(hasUnknowns != that.hasUnknowns)
- return false;
- if(!Arrays.equals(typeParameters, that.typeParameters))
- return false;
- if(!returnType.equals(that.returnType))
- return false;
- if(!Arrays.equals(parameters, that.parameters))
- return false;
- return thrownType == that.thrownType;
+
+ public boolean hasInvalidTypes() {
+ return Stream.of(parameters).anyMatch(p -> p.type.isInvalid());
}
-
- @Override
- public int hashCode() {
- int result = Arrays.hashCode(typeParameters);
- result = 31 * result + returnType.hashCode();
- result = 31 * result + Arrays.hashCode(parameters);
- result = 31 * result + (thrownType != null ? thrownType.hashCode() : 0);
- result = 31 * result + minParameters;
- result = 31 * result + maxParameters;
- result = 31 * result + (hasUnknowns ? 1 : 0);
- return result;
- }
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/FunctionParameter.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/FunctionParameter.java
index 424e82c77..07e44c647 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/FunctionParameter.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/FunctionParameter.java
@@ -1,30 +1,20 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-import java.util.Objects;
import org.openzen.zencode.shared.Taggable;
-import org.openzen.zenscript.codemodel.expression.Expression;
-import org.openzen.zenscript.codemodel.type.GlobalTypeRegistry;
import org.openzen.zenscript.codemodel.annotations.ParameterAnnotation;
+import org.openzen.zenscript.codemodel.expression.Expression;
import org.openzen.zenscript.codemodel.type.TypeID;
-/**
- *
- * @author Hoofdgebruiker
- */
+import java.util.Objects;
+
public class FunctionParameter extends Taggable {
public static final FunctionParameter[] NONE = new FunctionParameter[0];
-
- public ParameterAnnotation[] annotations;
public final TypeID type;
public final String name;
- public Expression defaultValue;
public final boolean variadic;
-
+ public ParameterAnnotation[] annotations;
+ public Expression defaultValue;
+
public FunctionParameter(TypeID type) {
this.annotations = ParameterAnnotation.NONE;
this.type = type;
@@ -32,7 +22,7 @@ public FunctionParameter(TypeID type) {
this.defaultValue = null;
this.variadic = false;
}
-
+
public FunctionParameter(TypeID type, String name) {
this.annotations = ParameterAnnotation.NONE;
this.type = type;
@@ -40,7 +30,7 @@ public FunctionParameter(TypeID type, String name) {
this.defaultValue = null;
this.variadic = false;
}
-
+
public FunctionParameter(TypeID type, String name, Expression defaultValue, boolean variadic) {
this.annotations = ParameterAnnotation.NONE;
this.type = type;
@@ -48,27 +38,25 @@ public FunctionParameter(TypeID type, String name, Expression defaultValue, bool
this.defaultValue = defaultValue;
this.variadic = variadic;
}
-
- public FunctionParameter normalize(GlobalTypeRegistry registry) {
- FunctionParameter result = new FunctionParameter(type.getNormalized(), name, defaultValue, variadic);
- result.annotations = this.annotations;
- return result;
+
+ public FunctionParameter(TypeID type, String name, boolean variadic) {
+ this(type, name, null, variadic);
}
-
+
public FunctionParameter withGenericArguments(GenericMapper mapper) {
TypeID instanced = type.instance(mapper);
- if (instanced.equals(type))
+ if (Objects.equals(instanced,type))
return this;
-
+
FunctionParameter result = new FunctionParameter(instanced, name, defaultValue, variadic);
result.annotations = annotations;
result.addAllTagsFrom(this); // TODO: this will cause trouble -> references?
return result;
}
-
+
@Override
public String toString() {
- return name + " as " + type.toString();
+ return name + ": " + type.toString();
}
@Override
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/GenericMapper.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/GenericMapper.java
index 8f6980e1a..267004dc1 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/GenericMapper.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/GenericMapper.java
@@ -1,104 +1,121 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-import org.openzen.zencode.shared.*;
-import org.openzen.zenscript.codemodel.generic.*;
-import org.openzen.zenscript.codemodel.type.*;
+import org.openzen.zenscript.codemodel.generic.TypeParameter;
+import org.openzen.zenscript.codemodel.identifiers.FieldSymbol;
+import org.openzen.zenscript.codemodel.identifiers.MethodSymbol;
+import org.openzen.zenscript.codemodel.identifiers.instances.FieldInstance;
+import org.openzen.zenscript.codemodel.identifiers.instances.MethodInstance;
+import org.openzen.zenscript.codemodel.type.GenericTypeID;
+import org.openzen.zenscript.codemodel.type.TypeID;
-import java.util.*;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
-/**
- * @author Hoofdgebruiker
- */
public class GenericMapper {
-
- public static final GenericMapper EMPTY = new GenericMapper(CodePosition.BUILTIN, null, Collections
- .emptyMap());
-
- public final CodePosition position;
- public final GlobalTypeRegistry registry;
- private final Map mapping;
-
- public GenericMapper(CodePosition position, GlobalTypeRegistry registry, Map mapping) {
- if(mapping == null)
- throw new IllegalArgumentException();
-
- this.position = position;
- this.registry = registry;
- this.mapping = mapping;
- }
-
+
+ public static final GenericMapper EMPTY = new GenericMapper(Collections.emptyMap(), TypeID.NONE);
+
+ private final Map mapping;
+ private final TypeID[] expansionTypeArguments;
+
+ public GenericMapper(Map mapping, TypeID[] expansionTypeArguments) {
+ if (mapping == null)
+ throw new IllegalArgumentException();
+
+ this.mapping = mapping;
+ this.expansionTypeArguments = expansionTypeArguments;
+ }
+
+ public static GenericMapper create(TypeParameter[] typeParameters, TypeID[] typeArguments) {
+ if (typeParameters.length != typeArguments.length)
+ throw new IllegalArgumentException("Number of type parameters is different from number of type arguments");
+
+ Map mapping = new HashMap<>();
+ for (int i = 0; i < typeParameters.length; i++) {
+ mapping.put(typeParameters[i], typeArguments[i]);
+ }
+ return new GenericMapper(mapping, TypeID.NONE);
+ }
+
+ public static GenericMapper single(TypeParameter parameter, TypeID argument) {
+ return new GenericMapper(Collections.singletonMap(parameter, argument), TypeID.NONE);
+ }
+
public Map getMapping() {
- return mapping;
- }
-
- public TypeID map(TypeID original) {
- return mapping.isEmpty() ? original : original.instance(this);
- }
-
- public TypeID[] map(TypeID[] original) {
- if(mapping.isEmpty() || original.length == 0)
- return original;
-
- TypeID[] mapped = new TypeID[original.length];
- for(int i = 0; i < original.length; i++)
- mapped[i] = original[i].instance(this);
- return mapped;
- }
-
- public TypeID mapGeneric(GenericTypeID type) {
- //if (!mapping.containsKey(type.parameter))
- // throw new IllegalStateException("No mapping found for type " + type);
-
- return mapping.getOrDefault(type.parameter, type);
- }
-
- public FunctionHeader map(FunctionHeader original) {
- return mapping.isEmpty() ? original : original.withGenericArguments(this);
- }
-
- public GenericMapper getInner(CodePosition position, GlobalTypeRegistry registry, Map mapping) {
- Map resultMap = new HashMap<>(this.mapping);
- mapping.forEach((typeParameter, storedType) -> {
- if(resultMap.containsKey(typeParameter)) {
- if(storedType instanceof GenericTypeID && ((GenericTypeID) storedType).parameter == typeParameter) {
- return;
- }
- }
- resultMap.put(typeParameter, storedType);
- });
-
- return new GenericMapper(position, registry, resultMap);
- }
-
- public GenericMapper getInner(CodePosition position, GlobalTypeRegistry registry, TypeParameter[] parameters) {
- Map resultMap = new HashMap<>(this.mapping);
- for(TypeParameter parameter : parameters)
- resultMap.put(parameter, registry.getGeneric(parameter));
- return new GenericMapper(position, registry, resultMap);
- }
-
- @Override
- public String toString() {
- if(mapping.isEmpty())
- return "{}";
-
- StringBuilder result = new StringBuilder();
- result.append('{');
- boolean first = true;
- for(Map.Entry entry : mapping.entrySet()) {
- if(first) {
- first = false;
- } else {
- result.append(", ");
- }
- result.append(entry.getKey().toString()).append(": ").append(entry.getValue());
- }
- result.append('}');
- return result.toString();
- }
+ return mapping;
+ }
+
+ public TypeID map(TypeID original) {
+ return mapping.isEmpty() ? original : original.instance(this);
+ }
+
+ public TypeID[] map(TypeID[] original) {
+ if (mapping.isEmpty() || original.length == 0)
+ return original;
+
+ TypeID[] mapped = new TypeID[original.length];
+ for (int i = 0; i < original.length; i++)
+ mapped[i] = original[i].instance(this);
+ return mapped;
+ }
+
+ public TypeID mapGeneric(GenericTypeID type) {
+ //if (!mapping.containsKey(type.parameter))
+ // throw new IllegalStateException("No mapping found for type " + type);
+
+ return mapping.getOrDefault(type.parameter, type);
+ }
+
+ public FunctionHeader map(FunctionHeader original) {
+ return mapping.isEmpty() ? original : original.withGenericArguments(this);
+ }
+
+ public FieldInstance map(FieldSymbol field) {
+ return new FieldInstance(field, map(field.getType()));
+ }
+
+ public MethodInstance map(TypeID target, MethodSymbol method) {
+ return new MethodInstance(method, map(method.getHeader()), target, expansionTypeArguments);
+ }
+
+ public GenericMapper getInner(Map mapping) {
+ Map resultMap = new HashMap<>(this.mapping);
+ mapping.forEach((typeParameter, type) -> {
+ if (resultMap.containsKey(typeParameter)) {
+ if (type.asGeneric().map(generic -> generic.parameter == typeParameter).orElse(false))
+ return;
+ }
+ resultMap.put(typeParameter, type);
+ });
+
+ return new GenericMapper(resultMap, expansionTypeArguments);
+ }
+
+ public GenericMapper getInner(TypeParameter[] parameters) {
+ Map resultMap = new HashMap<>(this.mapping);
+ for (TypeParameter parameter : parameters)
+ resultMap.put(parameter, new GenericTypeID(parameter));
+ return new GenericMapper(resultMap, expansionTypeArguments);
+ }
+
+ @Override
+ public String toString() {
+ if (mapping.isEmpty())
+ return "{}";
+
+ StringBuilder result = new StringBuilder();
+ result.append('{');
+ boolean first = true;
+ for (Map.Entry entry : mapping.entrySet()) {
+ if (first) {
+ first = false;
+ } else {
+ result.append(", ");
+ }
+ result.append(entry.getKey().toString()).append(": ").append(entry.getValue());
+ }
+ result.append('}');
+ return result.toString();
+ }
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/GenericName.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/GenericName.java
index 99e4a3cf3..068ab0b8b 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/GenericName.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/GenericName.java
@@ -1,58 +1,57 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-import java.util.List;
+import org.openzen.zenscript.codemodel.compilation.ResolvedType;
+import org.openzen.zenscript.codemodel.identifiers.ExpansionSymbol;
import org.openzen.zenscript.codemodel.type.DefinitionTypeID;
-import org.openzen.zenscript.codemodel.type.GlobalTypeRegistry;
import org.openzen.zenscript.codemodel.type.TypeID;
-/**
- *
- * @author Hoofdgebruiker
- */
+import java.util.List;
+import java.util.Optional;
+
public class GenericName {
public final String name;
public final TypeID[] arguments;
-
+
public GenericName(String name) {
this(name, TypeID.NONE);
}
-
+
public GenericName(String name, TypeID[] arguments) {
if (arguments == null)
throw new NullPointerException("Arguments cannot be null");
-
+
this.name = name;
this.arguments = arguments;
}
-
+
+ public static Optional getInnerType(TypeID type, List name, int index) {
+ while (index < name.size()) {
+ GenericName innerName = name.get(index++);
+ ResolvedType members = type.resolveWithoutExpansions();
+ Optional inner = members
+ .findInnerType(innerName.name)
+ .map(t -> DefinitionTypeID.create(t, innerName.arguments));
+ if (!inner.isPresent())
+ return Optional.empty();
+
+ type = inner.get();
+ }
+
+ return Optional.of(type);
+ }
+
public int getNumberOfArguments() {
return arguments.length;
}
-
+
public boolean hasArguments() {
return arguments.length > 0;
}
-
+
public boolean hasNoArguments() {
return arguments.length == 0;
}
-
- public static TypeID getInnerType(GlobalTypeRegistry registry, DefinitionTypeID type, List name, int index) {
- while (index < name.size()) {
- GenericName innerName = name.get(index++);
- type = type.getInnerType(innerName, registry);
- if (type == null)
- return null;
- }
- return type;
- }
-
@Override
public String toString() {
StringBuilder result = new StringBuilder(name);
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/HighLevelDefinition.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/HighLevelDefinition.java
index 360fcd3ba..a693c932c 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/HighLevelDefinition.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/HighLevelDefinition.java
@@ -1,93 +1,72 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
import org.openzen.zencode.shared.CodePosition;
import org.openzen.zencode.shared.Taggable;
import org.openzen.zenscript.codemodel.annotations.DefinitionAnnotation;
-import org.openzen.zenscript.codemodel.definition.AliasDefinition;
-import org.openzen.zenscript.codemodel.definition.DefinitionVisitor;
-import org.openzen.zenscript.codemodel.definition.DefinitionVisitorWithContext;
-import org.openzen.zenscript.codemodel.definition.ExpansionDefinition;
-import org.openzen.zenscript.codemodel.definition.InterfaceDefinition;
-import org.openzen.zenscript.codemodel.definition.MemberCollector;
-import org.openzen.zenscript.codemodel.definition.ZSPackage;
+import org.openzen.zenscript.codemodel.compilation.ResolvingType;
+import org.openzen.zenscript.codemodel.definition.*;
import org.openzen.zenscript.codemodel.generic.TypeParameter;
-import org.openzen.zenscript.codemodel.member.ConstructorMember;
-import org.openzen.zenscript.codemodel.member.DestructorMember;
-import org.openzen.zenscript.codemodel.member.FieldMember;
-import org.openzen.zenscript.codemodel.member.IDefinitionMember;
-import org.openzen.zenscript.codemodel.member.ImplementationMember;
-import org.openzen.zenscript.codemodel.member.InnerDefinitionMember;
-import org.openzen.zenscript.codemodel.scope.TypeScope;
+import org.openzen.zenscript.codemodel.identifiers.ModuleSymbol;
+import org.openzen.zenscript.codemodel.identifiers.TypeSymbol;
+import org.openzen.zenscript.codemodel.identifiers.instances.MethodInstance;
+import org.openzen.zenscript.codemodel.member.*;
+import org.openzen.zenscript.codemodel.type.BasicTypeID;
import org.openzen.zenscript.codemodel.type.DefinitionTypeID;
import org.openzen.zenscript.codemodel.type.TypeID;
+import org.openzen.zenscript.codemodel.type.builtin.BuiltinMethodSymbol;
+import org.openzen.zenscript.codemodel.type.member.*;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
-/**
- *
- * @author Hoofdgebruiker
- */
-public abstract class HighLevelDefinition extends Taggable {
+public abstract class HighLevelDefinition extends Taggable implements TypeSymbol {
public final CodePosition position;
- public final Module module;
+ public final ModuleSymbol module;
public final ZSPackage pkg;
public final String name;
- public final int modifiers;
+ public final Modifiers modifiers;
public final List members = new ArrayList<>();
public TypeParameter[] typeParameters = TypeParameter.NONE;
public DefinitionAnnotation[] annotations = DefinitionAnnotation.NONE;
-
- public HighLevelDefinition outerDefinition;
+
+ public TypeSymbol outerDefinition;
private TypeID superType;
- public HighLevelDefinition(CodePosition position, Module module, ZSPackage pkg, String name, int modifiers, HighLevelDefinition outerDefinition) {
+ public HighLevelDefinition(CodePosition position, ModuleSymbol module, ZSPackage pkg, String name, Modifiers modifiers, TypeSymbol outerDefinition) {
if (module == null)
throw new NullPointerException();
-
+
this.position = position;
this.module = module;
this.pkg = pkg;
this.name = name;
this.modifiers = modifiers;
this.outerDefinition = outerDefinition;
-
+
if (pkg != null)
pkg.register(this);
}
-
+
public String getFullName() {
return pkg.fullName + '.' + name;
}
-
+
public TypeID getSuperType() {
return superType;
}
-
+
public void setSuperType(TypeID superType) {
this.superType = superType;
}
-
- public boolean isSubclassOf(HighLevelDefinition other) {
- if (superType.isDefinition(other))
- return true;
- if (superType == null || !(superType instanceof DefinitionTypeID))
- return false;
-
- DefinitionTypeID superDefinition = (DefinitionTypeID)superType;
- return superDefinition.definition.isSubclassOf(other);
- }
-
+
public int getNumberOfGenericParameters() {
return typeParameters == null ? 0 : typeParameters.length;
}
-
+
+ public void addDefaultMembers() {}
+
public void setOuterDefinition(HighLevelDefinition outerDefinition) {
this.outerDefinition = outerDefinition;
}
@@ -99,97 +78,116 @@ public boolean isExpansion() {
public boolean isInnerDefinition() {
return outerDefinition != null;
}
-
- public boolean isInterface() {
- return this instanceof InterfaceDefinition;
- }
-
- public boolean isAlias() {
- return this instanceof AliasDefinition;
- }
-
+
public void addMember(IDefinitionMember member) {
if (!members.contains(member))
members.add(member);
}
-
+
public void collectMembers(MemberCollector collector) {
for (IDefinitionMember member : members)
collector.member(member);
}
-
+
public void setTypeParameters(TypeParameter[] typeParameters) {
this.typeParameters = typeParameters;
}
-
- public AccessScope getAccessScope() {
- return new AccessScope(module, this);
- }
-
+
public List getFields() {
List fields = new ArrayList<>();
for (IDefinitionMember member : members)
if (member instanceof FieldMember)
- fields.add((FieldMember)member);
-
+ fields.add((FieldMember) member);
+
return fields;
}
-
- public boolean hasEmptyConstructor() {
- for (IDefinitionMember member : members) {
- if (member instanceof ConstructorMember) {
- if (((ConstructorMember) member).header.parameters.length == 0)
- return true;
- }
- }
-
- return false;
+
+ public abstract T accept(DefinitionVisitor visitor);
+
+ public abstract R accept(C context, DefinitionVisitorWithContext visitor);
+
+ /* TypeSymbol implementation */
+
+ @Override
+ public ModuleSymbol getModule() {
+ return module;
+ }
+
+ @Override
+ public String describe() {
+ return name;
+ }
+
+ @Override
+ public boolean isInterface() {
+ return this instanceof InterfaceDefinition;
+ }
+
+ @Override
+ public Modifiers getModifiers() {
+ return modifiers;
}
-
+
+ @Override
public boolean isStatic() {
- return (modifiers & Modifiers.STATIC) > 0;
+ return modifiers.isStatic() || outerDefinition == null;
}
-
- public void normalize(TypeScope scope) {
- List fields = new ArrayList<>();
-
- for (IDefinitionMember member : members) {
- member.normalize(scope);
-
- if (member instanceof FieldMember)
- fields.add((FieldMember)member);
+
+ @Override
+ public boolean isEnum() { return this instanceof EnumDefinition; }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public ResolvingType resolve(TypeID[] typeArguments) {
+ TypeID type = DefinitionTypeID.create(this, typeArguments);
+
+ MemberSet.Builder members = MemberSet.create(type);
+ GenericMapper mapper = GenericMapper.create(typeParameters, typeArguments);
+ for (IDefinitionMember member : this.members) {
+ member.registerTo(type, members, mapper);
}
-
- for (FieldMember field : fields) {
- if (field.autoGetter != null)
- members.add(field.autoGetter);
- if (field.autoSetter != null)
- members.add(field.autoSetter);
+ List interfaces = this.members.stream()
+ .map(IDefinitionMember::asImplementation)
+ .filter(Optional::isPresent)
+ .map(Optional::get)
+ .map(mapper::map)
+ .collect(Collectors.toList());
+
+ members.method(new MethodInstance(BuiltinMethodSymbol.OBJECT_SAME, new FunctionHeader(BasicTypeID.BOOL, type), type));
+ members.method(new MethodInstance(BuiltinMethodSymbol.OBJECT_NOTSAME, new FunctionHeader(BasicTypeID.BOOL, type), type));
+ resolveAdditional(type, members, mapper);
+ ResolvingType resolved = members.build();
+
+ if (superType != null) {
+ TypeID instancedSuperType = mapper.map(superType);
+ resolved = new SubclassResolvingType(resolved, instancedSuperType);
}
+
+ return InterfaceResolvingType.of(resolved, interfaces);
}
-
- public abstract T accept(DefinitionVisitor visitor);
-
- public abstract R accept(C context, DefinitionVisitorWithContext visitor);
-
- public HighLevelDefinition getInnerType(String name) {
- for (IDefinitionMember member : members) {
- if (member instanceof InnerDefinitionMember) {
- InnerDefinitionMember inner = (InnerDefinitionMember)member;
- if (inner.innerDefinition.name.equals(name))
- return inner.innerDefinition;
- }
- }
-
- return null;
+
+ protected void resolveAdditional(TypeID type, MemberSet.Builder members, GenericMapper mapper) {}
+
+ @Override
+ public TypeParameter[] getTypeParameters() {
+ return typeParameters;
+ }
+
+ @Override
+ public Optional getOuter() {
+ return Optional.ofNullable(outerDefinition);
}
- public boolean isOuterOf(HighLevelDefinition definition) {
- if (definition.outerDefinition == this)
- return true;
- if (definition.outerDefinition == null)
- return false;
-
- return isOuterOf(definition.outerDefinition);
+ @Override
+ public Optional getSupertype(TypeID[] typeArguments) {
+ return Optional.ofNullable(superType)
+ .map(t -> {
+ GenericMapper mapper = GenericMapper.create(typeParameters, typeArguments);
+ return mapper.map(t);
+ });
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/LocalVariable.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/LocalVariable.java
new file mode 100644
index 000000000..74ad3b8cf
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/LocalVariable.java
@@ -0,0 +1,15 @@
+package org.openzen.zenscript.codemodel;
+
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+public class LocalVariable {
+ public final String name;
+ public final boolean isFinal;
+ public final TypeID type;
+
+ public LocalVariable(String name, boolean isFinal, TypeID type) {
+ this.name = name;
+ this.isFinal = isFinal;
+ this.type = type;
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/Modifiers.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/Modifiers.java
index 5f47e53c0..53c4c7081 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/Modifiers.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/Modifiers.java
@@ -1,104 +1,261 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-/**
- *
- * @author Hoofdgebruiker
- */
+import java.util.StringJoiner;
+
public class Modifiers {
- private Modifiers() {}
-
- public static final int PUBLIC = 1;
- public static final int INTERNAL = 2;
- public static final int PRIVATE = 4;
- public static final int ABSTRACT = 8;
- public static final int FINAL = 16;
- public static final int CONST = 32;
- public static final int CONST_OPTIONAL = 64;
- public static final int STATIC = 128;
- public static final int PROTECTED = 256;
- public static final int IMPLICIT = 512;
- public static final int VIRTUAL = 1024;
- public static final int EXTERN = 2048;
- public static final int OVERRIDE = 4096;
-
+ public static final int FLAG_PUBLIC = 1;
+ public static final int FLAG_INTERNAL = 2;
+ public static final int FLAG_PRIVATE = 4;
+ public static final int FLAG_ABSTRACT = 8;
+ public static final int FLAG_FINAL = 16;
+ public static final int FLAG_CONST = 32;
+ public static final int FLAG_CONST_OPTIONAL = 64;
+ public static final int FLAG_STATIC = 128;
+ public static final int FLAG_PROTECTED = 256;
+ public static final int FLAG_IMPLICIT = 512;
+ public static final int FLAG_VIRTUAL = 1024;
+ public static final int FLAG_EXTERN = 2048;
+ public static final int FLAG_OVERRIDE = 4096;
+
+ public static final Modifiers NONE = new Modifiers(0);
+ public static final Modifiers PUBLIC = new Modifiers(FLAG_PUBLIC);
+ public static final Modifiers PROTECTED = new Modifiers(FLAG_PROTECTED);
+ public static final Modifiers PUBLIC_STATIC = new Modifiers(FLAG_PUBLIC | FLAG_STATIC);
+ public static final Modifiers PRIVATE = new Modifiers(FLAG_PRIVATE);
+ public static final Modifiers IMPLICIT = new Modifiers(FLAG_IMPLICIT);
+ public static final Modifiers CONST = new Modifiers(FLAG_CONST);
+
+ public final int value;
+
+ public Modifiers(int value) {
+ this.value = value;
+ }
+
+ public Modifiers with(Modifiers other) {
+ return new Modifiers(this.value | other.value);
+ }
+
+ public boolean isPublic() {
+ return (value & FLAG_PUBLIC) > 0;
+ }
+
+ public Modifiers withPublic() {
+ return new Modifiers(value | FLAG_PUBLIC);
+ }
+
public static boolean isPublic(int modifiers) {
- return (modifiers & PUBLIC) > 0;
+ return (modifiers & FLAG_PUBLIC) > 0;
}
-
+
+ public boolean isInternal() {
+ return (value & FLAG_INTERNAL) > 0;
+ }
+
+ public Modifiers withInternal() {
+ return new Modifiers(value | FLAG_INTERNAL);
+ }
+
public static boolean isInternal(int modifiers) {
- return (modifiers & INTERNAL) > 0;
+ return (modifiers & FLAG_INTERNAL) > 0;
}
-
+
+ public boolean isProtected() {
+ return (value & FLAG_PROTECTED) > 0;
+ }
+
+ public Modifiers withProtected() {
+ return new Modifiers(value | FLAG_PROTECTED);
+ }
+
public static boolean isProtected(int modifiers) {
- return (modifiers & PROTECTED) > 0;
+ return (modifiers & FLAG_PROTECTED) > 0;
}
-
+
+ public boolean isPrivate() {
+ return (value & FLAG_PRIVATE) > 0;
+ }
+
+ public Modifiers withPrivate() {
+ return new Modifiers(value | FLAG_PRIVATE);
+ }
+
public static boolean isPrivate(int modifiers) {
- return (modifiers & PRIVATE) > 0;
+ return (modifiers & FLAG_PRIVATE) > 0;
}
-
+
+ public boolean isAbstract() {
+ return (value & FLAG_ABSTRACT) > 0;
+ }
+
+ public Modifiers withAbstract() {
+ return new Modifiers(value | FLAG_ABSTRACT);
+ }
+
+
public static boolean isAbstract(int modifiers) {
- return (modifiers & ABSTRACT) > 0;
+ return (modifiers & FLAG_ABSTRACT) > 0;
}
-
+
+ public boolean isFinal() {
+ return (value & FLAG_FINAL) > 0;
+ }
+
+ public Modifiers withFinal() {
+ return new Modifiers(value | FLAG_FINAL);
+ }
+
public static boolean isFinal(int modifiers) {
- return (modifiers & FINAL) > 0;
+ return (modifiers & FLAG_FINAL) > 0;
}
-
+
+ public boolean isConst() {
+ return (value & FLAG_CONST) > 0;
+ }
+
+ public Modifiers withConst() {
+ return new Modifiers(value | FLAG_CONST);
+ }
+
+ public Modifiers withoutConst() {
+ return new Modifiers(value & ~FLAG_CONST);
+ }
+
public static boolean isConst(int modifiers) {
- return (modifiers & CONST) > 0;
+ return (modifiers & FLAG_CONST) > 0;
}
-
+
+ public boolean isConstOptional() {
+ return (value & FLAG_CONST_OPTIONAL) > 0;
+ }
+
+ public Modifiers withConstOptional() {
+ return new Modifiers(value | FLAG_CONST_OPTIONAL);
+ }
+
public static boolean isConstOptional(int modifiers) {
- return (modifiers & CONST_OPTIONAL) > 0;
+ return (modifiers & FLAG_CONST_OPTIONAL) > 0;
}
-
+
+ public boolean isStatic() {
+ return (value & FLAG_STATIC) > 0;
+ }
+
+ public Modifiers withStatic() {
+ return new Modifiers(value | FLAG_STATIC);
+ }
+
+ public Modifiers withoutStatic() {
+ return new Modifiers(value & ~FLAG_STATIC);
+ }
+
public static boolean isStatic(int modifiers) {
- return (modifiers & STATIC) > 0;
+ return (modifiers & FLAG_STATIC) > 0;
}
-
+
+
+ public boolean isImplicit() {
+ return (value & FLAG_IMPLICIT) > 0;
+ }
+
+ public Modifiers withImplicit() {
+ return new Modifiers(value | FLAG_IMPLICIT);
+ }
+
public static boolean isImplicit(int modifiers) {
- return (modifiers & IMPLICIT) > 0;
+ return (modifiers & FLAG_IMPLICIT) > 0;
}
-
+
+ public boolean isVirtual() {
+ return (value & FLAG_VIRTUAL) > 0;
+ }
+
+ public Modifiers withVirtual() {
+ return new Modifiers(value | FLAG_VIRTUAL);
+ }
+
public static boolean isVirtual(int modifiers) {
- return (modifiers & VIRTUAL) > 0;
+ return (modifiers & FLAG_VIRTUAL) > 0;
}
-
+
+ public boolean isExtern() {
+ return (value & FLAG_EXTERN) > 0;
+ }
+
+ public Modifiers withExtern() {
+ return new Modifiers(value | FLAG_EXTERN);
+ }
+
public static boolean isExtern(int modifiers) {
- return (modifiers & EXTERN) > 0;
+ return (modifiers & FLAG_EXTERN) > 0;
}
-
+
+ public Modifiers withOverride() {
+ return new Modifiers(value | FLAG_OVERRIDE);
+ }
+
+ public boolean isOverride() {
+ return (value & FLAG_OVERRIDE) > 0;
+ }
+
public static boolean isOverride(int modifiers) {
- return (modifiers & OVERRIDE) > 0;
+ return (modifiers & FLAG_OVERRIDE) > 0;
}
+ public boolean hasAccessModifiers() {
+ return (value & (FLAG_PRIVATE | FLAG_PUBLIC | FLAG_PROTECTED | FLAG_INTERNAL)) > 0;
+ }
+
public static boolean hasAccess(int modifiers) {
- return (modifiers & (PRIVATE | PUBLIC | PROTECTED | INTERNAL)) > 0;
- }
-
- public static String describe(int modifiers) {
- StringBuilder builder = new StringBuilder();
- if (isPublic(modifiers)) {
- builder.append("public");
- } else if (isPrivate(modifiers)) {
- builder.append("private");
- } else if (isProtected(modifiers)) {
- builder.append("protected");
- }
- if (isAbstract(modifiers)) {
- builder.append(" abstract");
- } else if (isFinal(modifiers)) {
- builder.append(" final");
- } else if (isStatic(modifiers)) {
- builder.append(" static");
- }
- return builder.toString();
- }
-
+ return (modifiers & (FLAG_PRIVATE | FLAG_PUBLIC | FLAG_PROTECTED | FLAG_INTERNAL)) > 0;
+ }
+
+ @Override
+ public String toString() {
+ return describe(value);
+ }
+
+ public static String describe(int modifiers) {
+ StringJoiner joiner = new StringJoiner(" ");
+ if(isPublic(modifiers)) {
+ joiner.add("public");
+ }
+ if(isInternal(modifiers)) {
+ joiner.add("internal");
+ }
+ if(isProtected(modifiers)) {
+ joiner.add("protected");
+ }
+ if(isPrivate(modifiers)) {
+ joiner.add("private");
+ }
+ if(isAbstract(modifiers)) {
+ joiner.add("abstract");
+ }
+ if(isFinal(modifiers)) {
+ joiner.add("final");
+ }
+ if(isConst(modifiers)) {
+ joiner.add("const");
+ }
+ if(isConstOptional(modifiers)) {
+ joiner.add("constOptional");
+ }
+ if(isStatic(modifiers)) {
+ joiner.add("static");
+ }
+ if(isImplicit(modifiers)) {
+ joiner.add("implicit");
+ }
+ if(isVirtual(modifiers)) {
+ joiner.add("virtual");
+ }
+ if(isExtern(modifiers)) {
+ joiner.add("extern");
+ }
+ if(isOverride(modifiers)) {
+ joiner.add("override");
+ }
+ return joiner.toString();
+ }
+
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/Module.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/Module.java
deleted file mode 100644
index f7de01b34..000000000
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/Module.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.openzen.zenscript.codemodel;
-
-/**
- *
- * @author Hoofdgebruiker
- */
-public class Module {
- public static final Module BUILTIN = new Module("builtin");
-
- public final String name;
-
- public Module(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return name;
- }
-}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ModuleProcessor.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ModuleProcessor.java
index dfca2d290..f7529c934 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ModuleProcessor.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ModuleProcessor.java
@@ -1,16 +1,7 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-/**
- *
- * @author Hoofdgebruiker
- */
public interface ModuleProcessor {
ScriptBlock process(ScriptBlock block);
-
+
void process(HighLevelDefinition definition);
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ModuleSpace.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ModuleSpace.java
index 9ef4f5d25..61067185f 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ModuleSpace.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ModuleSpace.java
@@ -1,80 +1,77 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
import org.openzen.zencode.shared.CodePosition;
import org.openzen.zencode.shared.CompileException;
-import org.openzen.zencode.shared.CompileExceptionCode;
import org.openzen.zenscript.codemodel.annotations.AnnotationDefinition;
import org.openzen.zenscript.codemodel.annotations.NativeAnnotationDefinition;
import org.openzen.zenscript.codemodel.annotations.PreconditionAnnotationDefinition;
-import org.openzen.zenscript.codemodel.definition.ExpansionDefinition;
+import org.openzen.zenscript.codemodel.compilation.CompileErrors;
import org.openzen.zenscript.codemodel.definition.ZSPackage;
-import org.openzen.zenscript.codemodel.type.GlobalTypeRegistry;
-import org.openzen.zenscript.codemodel.type.ISymbol;
+import org.openzen.zenscript.codemodel.globals.IGlobal;
+import org.openzen.zenscript.codemodel.identifiers.ExpansionSymbol;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
-/**
- *
- * @author Hoofdgebruiker
- */
public final class ModuleSpace {
public final ZSPackage rootPackage = new ZSPackage(null, "");
- public final GlobalTypeRegistry registry;
- public final ZSPackage globalsPackage = new ZSPackage(null, "");
- private final List expansions = new ArrayList<>();
- private final Map globals = new HashMap<>();
- private final AnnotationDefinition[] annotations;
+ public final ZSPackage stdlib = new ZSPackage(rootPackage, "stdlib");
+
+ private final List expansions = new ArrayList<>();
+ private final Map globals = new HashMap<>();
+ private final List annotations;
private final Map modules = new HashMap<>();
-
- public ModuleSpace(GlobalTypeRegistry registry, List annotations) {
- this.registry = registry;
-
+
+ public ModuleSpace(List annotations) {
annotations.add(NativeAnnotationDefinition.INSTANCE);
annotations.add(PreconditionAnnotationDefinition.INSTANCE);
- this.annotations = annotations.toArray(new AnnotationDefinition[annotations.size()]);
+ this.annotations = annotations;
}
-
+
public void addModule(String name, SemanticModule dependency) throws CompileException {
modules.put(name, dependency);
rootPackage.add(name, dependency.modulePackage);
dependency.definitions.registerExpansionsTo(expansions);
-
- for (Map.Entry globalEntry : dependency.globals.entrySet()) {
+
+ for (Map.Entry globalEntry : dependency.globals.entrySet()) {
if (globals.containsKey(globalEntry.getKey()))
- throw new CompileException(CodePosition.META, CompileExceptionCode.DUPLICATE_GLOBAL, "Duplicate global: " + globalEntry.getKey());
-
+ throw new CompileException(CodePosition.META, CompileErrors.duplicateGlobal(globalEntry.getKey()));
+
globals.put(globalEntry.getKey(), globalEntry.getValue());
}
}
-
- public void addGlobal(String name, ISymbol global) {
+
+ public void addExpansion(ExpansionSymbol expansion) {
+ expansions.add(expansion);
+ }
+
+ public void addGlobal(String name, IGlobal global) {
globals.put(name, global);
}
-
+
public SemanticModule getModule(String name) {
return modules.get(name);
}
-
+
public ZSPackage collectPackages() {
return rootPackage;
}
-
- public List collectExpansions() {
+
+ public List collectExpansions() {
return expansions;
}
-
- public Map collectGlobals() {
+
+ public Map collectGlobals() {
return globals;
}
-
- public AnnotationDefinition[] getAnnotations() {
+
+ public List getAnnotations() {
return annotations;
}
+
+ public void addAnnotation(AnnotationDefinition definition) {
+ annotations.add(definition);
+ }
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/OperatorType.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/OperatorType.java
index 2cebc73ba..24200b7a2 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/OperatorType.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/OperatorType.java
@@ -2,19 +2,17 @@
/**
* Enum used to indicate operator type.
- *
- * @author Stan Hebben
*/
public enum OperatorType {
- ADD("+", "add"),
- SUB("-", "subtract"),
- MUL("*", "multiply"),
- DIV("/", "divide"),
- MOD("%", "modulo"),
+ ADD("+", "add", true),
+ SUB("-", "subtract", true),
+ MUL("*", "multiply", true),
+ DIV("/", "divide", true),
+ MOD("%", "modulo", true),
CAT("~", "concat"),
- OR("|", "or"),
- AND("&", "and"),
- XOR("^", "xor"),
+ OR("|", "or", true),
+ AND("&", "and", true),
+ XOR("^", "xor", true),
NEG("-", "negate"),
INVERT("~", "invert"),
NOT("!", "not"),
@@ -31,7 +29,7 @@ public enum OperatorType {
SHL("<<", "shl"),
SHR(">>", "shr"),
USHR(">>>", "ushr"),
-
+
ADDASSIGN("+=", "addAssign", ADD),
SUBASSIGN("-=", "subAssign", SUB),
MULASSIGN("*=", "mulAssign", MUL),
@@ -44,30 +42,40 @@ public enum OperatorType {
SHLASSIGN("<<=", "shlAssign", SHL),
SHRASSIGN(">>=", "shrAssign", SHR),
USHRASSIGN(">>>=", "ushrAssign", USHR),
-
+
INCREMENT("++", "increment"),
DECREMENT("--", "decrement"),
-
+
RANGE("..", "rangeTo"),
-
+
CONSTRUCTOR("this", "construct"),
DESTRUCTOR("~this", "destruct"),
CALL("()", "call"),
CAST("as", "cast");
-
+
public final OperatorType assignOperatorFor;
public final String operator;
public final String compiledName;
-
+ public final boolean widening;
+
OperatorType(String operator, String compiledName) {
this.operator = operator;
this.compiledName = compiledName;
assignOperatorFor = null;
+ this.widening = false;
}
-
+
+ OperatorType(String operator, String compiledName, boolean widening) {
+ this.operator = operator;
+ this.compiledName = compiledName;
+ assignOperatorFor = null;
+ this.widening = widening;
+ }
+
OperatorType(String operator, String compiledName, OperatorType assignOperatorFor) {
this.operator = operator;
this.compiledName = compiledName;
this.assignOperatorFor = assignOperatorFor;
+ this.widening = false;
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/PackageDefinitions.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/PackageDefinitions.java
index 8c50c5078..ee3678f5b 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/PackageDefinitions.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/PackageDefinitions.java
@@ -1,48 +1,44 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
+import org.openzen.zenscript.codemodel.definition.ZSPackage;
+import org.openzen.zenscript.codemodel.identifiers.ExpansionSymbol;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.openzen.zenscript.codemodel.definition.ExpansionDefinition;
-import org.openzen.zenscript.codemodel.definition.ZSPackage;
-/**
- *
- * @author Hoofdgebruiker
- */
public class PackageDefinitions {
- private final List definitions = new ArrayList<>();
+ private final List definitions;
private final Map definitionsByName = new HashMap<>();
-
+
+ public PackageDefinitions() {
+ this.definitions = new ArrayList<>();
+ }
+
public List getAll() {
return definitions;
}
-
+
public void add(HighLevelDefinition definition) {
definitions.add(definition);
definitionsByName.put(definition.name, definition);
}
-
+
public HighLevelDefinition getDefinition(String name) {
return definitionsByName.get(name);
}
-
+
public void registerTo(ZSPackage pkg) {
for (HighLevelDefinition definition : definitions) {
pkg.register(definition);
}
}
-
- public void registerExpansionsTo(List expansions) {
+
+ public void registerExpansionsTo(List expansions) {
for (HighLevelDefinition definition : definitions) {
- if (definition instanceof ExpansionDefinition)
- expansions.add((ExpansionDefinition) definition);
+ if (definition instanceof ExpansionSymbol)
+ expansions.add((ExpansionSymbol) definition);
}
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ScriptBlock.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ScriptBlock.java
index 79f606400..028864b79 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ScriptBlock.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/ScriptBlock.java
@@ -1,52 +1,31 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-import java.util.ArrayList;
-import java.util.List;
-import org.openzen.zencode.shared.ConcatMap;
import org.openzen.zencode.shared.SourceFile;
import org.openzen.zencode.shared.Taggable;
import org.openzen.zenscript.codemodel.definition.ZSPackage;
-import org.openzen.zenscript.codemodel.scope.TypeScope;
-import org.openzen.zenscript.codemodel.statement.LoopStatement;
+import org.openzen.zenscript.codemodel.identifiers.ModuleSymbol;
import org.openzen.zenscript.codemodel.statement.Statement;
-/**
- *
- * @author Hoofdgebruiker
- */
+import java.util.List;
+
public class ScriptBlock extends Taggable {
public final SourceFile file;
- public final Module module;
+ public final ModuleSymbol module;
public final ZSPackage pkg;
public final FunctionHeader scriptHeader;
public final List statements;
-
- public ScriptBlock(SourceFile file, Module module, ZSPackage pkg, FunctionHeader scriptHeader, List statements) {
+
+ public ScriptBlock(SourceFile file, ModuleSymbol module, ZSPackage pkg, FunctionHeader scriptHeader, List statements) {
this.file = file;
this.module = module;
this.pkg = pkg;
this.scriptHeader = scriptHeader;
this.statements = statements;
}
-
+
public ScriptBlock withStatements(List newStatements) {
ScriptBlock result = new ScriptBlock(file, module, pkg, scriptHeader, newStatements);
result.addAllTagsFrom(this);
return result;
}
-
- public ScriptBlock normalize(TypeScope scope) {
- List normalized = new ArrayList<>();
- for (Statement statement : statements) {
- normalized.add(statement.normalize(scope, ConcatMap.empty(LoopStatement.class, LoopStatement.class)));
- }
- ScriptBlock result = new ScriptBlock(file, module, pkg, scriptHeader, normalized);
- result.addAllTagsFrom(this);
- return result;
- }
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/SemanticModule.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/SemanticModule.java
index 0fc28940e..025fc0e9e 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/SemanticModule.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/SemanticModule.java
@@ -1,102 +1,85 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.openzen.zencode.shared.logging.*;
+import org.openzen.zencode.shared.logging.IZSLogger;
import org.openzen.zenscript.codemodel.annotations.AnnotationDefinition;
import org.openzen.zenscript.codemodel.annotations.AnnotationProcessor;
+import org.openzen.zenscript.codemodel.compilation.CompileContext;
import org.openzen.zenscript.codemodel.context.ModuleContext;
-import org.openzen.zenscript.codemodel.context.ModuleTypeResolutionContext;
import org.openzen.zenscript.codemodel.definition.ExpansionDefinition;
import org.openzen.zenscript.codemodel.definition.ZSPackage;
-import org.openzen.zenscript.codemodel.scope.FileScope;
-import org.openzen.zenscript.codemodel.type.GlobalTypeRegistry;
-import org.openzen.zenscript.codemodel.type.ISymbol;
-
-/**
- *
- * @author Hoofdgebruiker
- */
+import org.openzen.zenscript.codemodel.globals.IGlobal;
+import org.openzen.zenscript.codemodel.identifiers.ExpansionSymbol;
+import org.openzen.zenscript.codemodel.identifiers.ModuleSymbol;
+
+import java.util.*;
+import java.util.stream.Stream;
+
public class SemanticModule {
+
public static final SemanticModule[] NONE = new SemanticModule[0];
-
+
public final String name;
public final SemanticModule[] dependencies;
public final FunctionParameter[] parameters;
-
+
public final State state;
- public final Module module;
+ public final ModuleSymbol module;
public final ZSPackage rootPackage;
public final ZSPackage modulePackage;
public final PackageDefinitions definitions;
public final List scripts;
- public final Map globals = new HashMap<>();
-
- public final GlobalTypeRegistry registry;
- public final List expansions;
+ public final Map globals = new HashMap<>();
+ public final List expansions;
public final AnnotationDefinition[] annotations;
public final IZSLogger logger;
-
+
public SemanticModule(
- Module module,
- SemanticModule[] dependencies,
- FunctionParameter[] parameters,
- State state,
- ZSPackage rootPackage,
- ZSPackage modulePackage,
- PackageDefinitions definitions,
- List scripts,
- GlobalTypeRegistry registry,
- List expansions,
- AnnotationDefinition[] annotations,
- IZSLogger logger)
- {
+ ModuleSymbol module,
+ SemanticModule[] dependencies,
+ FunctionParameter[] parameters,
+ State state,
+ ZSPackage rootPackage,
+ ZSPackage modulePackage,
+ PackageDefinitions definitions,
+ List scripts,
+ List expansions,
+ AnnotationDefinition[] annotations,
+ IZSLogger logger) {
this.name = module.name;
this.module = module;
this.dependencies = dependencies;
this.parameters = parameters;
-
+
this.state = state;
this.rootPackage = rootPackage;
this.modulePackage = modulePackage;
this.definitions = definitions;
this.scripts = scripts;
-
- this.registry = registry;
+
this.expansions = expansions;
this.annotations = annotations;
- this.logger = logger;
- }
-
+ this.logger = logger;
+ }
+
public boolean isValid() {
return state != State.INVALID;
}
-
+
public SemanticModule normalize() {
if (state != State.ASSEMBLED)
throw new IllegalStateException("Module is invalid");
-
- ModuleTypeResolutionContext context = new ModuleTypeResolutionContext(registry, annotations, rootPackage, null, globals);
- AnnotationProcessor annotationProcessor = new AnnotationProcessor(context, expansions);
+
+ AnnotationProcessor annotationProcessor = new AnnotationProcessor(Collections.unmodifiableList(expansions));
List processedScripts = new ArrayList<>();
- FileScope fileScope = new FileScope(context, expansions, globals, member -> {});
-
+
for (ScriptBlock block : scripts)
- processedScripts.add(annotationProcessor.process(block).normalize(fileScope));
-
- for (HighLevelDefinition definition : definitions.getAll()) {
- annotationProcessor.process(definition);
- definition.normalize(fileScope);
- }
-
+ processedScripts.add(annotationProcessor.process(block));
+
+ Stream.concat(
+ definitions.getAll().stream(),
+ expansions.stream().filter(e -> e instanceof ExpansionDefinition).map(e -> (ExpansionDefinition) e)
+ ).forEach(annotationProcessor::process);
+
return new SemanticModule(
module,
dependencies,
@@ -106,16 +89,19 @@ public SemanticModule normalize() {
modulePackage,
definitions,
processedScripts,
- registry,
expansions,
annotations,
- logger);
+ logger);
}
-
+
public ModuleContext getContext() {
- return new ModuleContext(registry, module, expansions, rootPackage);
+ return new ModuleContext(module, expansions, rootPackage);
}
-
+
+ public CompileContext createCompileContext() {
+ return new CompileContext(rootPackage, modulePackage, Collections.unmodifiableList(expansions), globals, Arrays.asList(annotations));
+ }
+
public enum State {
INVALID,
ASSEMBLED,
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/VariableDefinition.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/VariableDefinition.java
new file mode 100644
index 000000000..65b735fc2
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/VariableDefinition.java
@@ -0,0 +1,24 @@
+package org.openzen.zenscript.codemodel;
+
+import org.openzen.zenscript.codemodel.ssa.SSAVariable;
+import org.openzen.zenscript.codemodel.statement.VariableID;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+public class VariableDefinition {
+ public final VariableID id;
+ public final String name;
+ public final TypeID type;
+ public final boolean isFinal;
+ public final SSAVariable variable;
+
+ public VariableDefinition(VariableID id, String name, TypeID type, boolean isFinal, SSAVariable variable) {
+ if (type == null)
+ throw new IllegalArgumentException("Variable type must be known");
+
+ this.id = id;
+ this.name = name;
+ this.type = type;
+ this.isFinal = isFinal;
+ this.variable = variable;
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/WhitespaceInfo.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/WhitespaceInfo.java
index 960146678..c4a05f4b5 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/WhitespaceInfo.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/WhitespaceInfo.java
@@ -1,50 +1,41 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-import java.util.ArrayList;
-import java.util.List;
import org.openzen.zencode.shared.Tag;
import stdlib.Strings;
-/**
- *
- * @author Hoofdgebruiker
- */
+import java.util.ArrayList;
+import java.util.List;
+
public class WhitespaceInfo implements Tag {
+ public boolean emptyLine;
+ public String[] commentsBefore;
+ public String commentsAfter;
+ public WhitespaceInfo(boolean emptyLine, String[] commentsBefore, String commentsAfter) {
+ this.emptyLine = emptyLine;
+ this.commentsBefore = commentsBefore;
+ this.commentsAfter = commentsAfter;
+ }
+
public static WhitespaceInfo from(String whitespaceBefore, String lineAfter, boolean skipLineBefore) {
int numNewLines = 0;
for (char c : whitespaceBefore.toCharArray())
if (c == '\n')
numNewLines++;
-
+
String[] split = Strings.split(whitespaceBefore, '\n');
List commentsBefore = new ArrayList<>();
for (String splitLine : split) {
String trimmed = splitLine.trim();
if (trimmed.isEmpty())
continue;
-
+
commentsBefore.add(trimmed);
}
-
+
boolean emptyLine = !skipLineBefore && numNewLines - commentsBefore.size() > 0;
return new WhitespaceInfo(
emptyLine,
commentsBefore.toArray(new String[commentsBefore.size()]),
lineAfter.trim());
}
-
- public boolean emptyLine;
- public String[] commentsBefore;
- public String commentsAfter;
-
- public WhitespaceInfo(boolean emptyLine, String[] commentsBefore, String commentsAfter) {
- this.emptyLine = emptyLine;
- this.commentsBefore = commentsBefore;
- this.commentsAfter = commentsAfter;
- }
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/WhitespacePostComment.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/WhitespacePostComment.java
index 22c59714f..b84829b42 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/WhitespacePostComment.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/WhitespacePostComment.java
@@ -1,39 +1,31 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel;
-import java.util.ArrayList;
-import java.util.List;
import org.openzen.zencode.shared.Tag;
import stdlib.Strings;
-/**
- *
- * @author Hoofdgebruiker
- */
+import java.util.ArrayList;
+import java.util.List;
+
public class WhitespacePostComment implements Tag {
+ public final String[] comments;
+
+ public WhitespacePostComment(String[] comments) {
+ this.comments = comments;
+ }
+
public static WhitespacePostComment fromWhitespace(String whitespace) {
List comments = new ArrayList<>();
for (String line : Strings.split(whitespace, '\n')) {
line = line.trim();
if (line.isEmpty())
continue;
-
+
comments.add(line);
}
-
+
if (comments.isEmpty())
return null;
-
+
return new WhitespacePostComment(comments.toArray(new String[comments.size()]));
}
-
- public final String[] comments;
-
- public WhitespacePostComment(String[] comments) {
- this.comments = comments;
- }
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/AnnotationDefinition.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/AnnotationDefinition.java
index efef06329..ebb4b915c 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/AnnotationDefinition.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/AnnotationDefinition.java
@@ -1,55 +1,45 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
-import java.util.List;
import org.openzen.zencode.shared.CodePosition;
import org.openzen.zenscript.codemodel.FunctionHeader;
import org.openzen.zenscript.codemodel.FunctionParameter;
import org.openzen.zenscript.codemodel.HighLevelDefinition;
-import org.openzen.zenscript.codemodel.context.StatementContext;
-import org.openzen.zenscript.codemodel.context.TypeContext;
+import org.openzen.zenscript.codemodel.compilation.*;
import org.openzen.zenscript.codemodel.expression.CallArguments;
import org.openzen.zenscript.codemodel.member.IDefinitionMember;
-import org.openzen.zenscript.codemodel.scope.BaseScope;
-import org.openzen.zenscript.codemodel.scope.ExpressionScope;
-import org.openzen.zenscript.codemodel.scope.StatementScope;
import org.openzen.zenscript.codemodel.serialization.CodeSerializationInput;
+import org.openzen.zenscript.codemodel.serialization.StatementSerializationContext;
+import org.openzen.zenscript.codemodel.serialization.TypeSerializationContext;
import org.openzen.zenscript.codemodel.statement.Statement;
-/**
- *
- * @author Hoofdgebruiker
- */
+import java.util.List;
+
public interface AnnotationDefinition {
String getAnnotationName();
-
- List getInitializers(BaseScope scope);
-
- ExpressionScope getScopeForMember(IDefinitionMember member, BaseScope scope);
-
- ExpressionScope getScopeForType(HighLevelDefinition definition, BaseScope scope);
-
- ExpressionScope getScopeForStatement(Statement statement, StatementScope scope);
-
- ExpressionScope getScopeForParameter(FunctionHeader header, FunctionParameter parameter, BaseScope scope);
-
+
+ List getInitializers(TypeBuilder types);
+
+ ExpressionCompiler getScopeForMember(IDefinitionMember member, MemberCompiler compiler);
+
+ ExpressionCompiler getScopeForType(HighLevelDefinition definition, DefinitionCompiler compiler);
+
+ ExpressionCompiler getScopeForStatement(Statement statement, StatementCompiler compiler);
+
+ ExpressionCompiler getScopeForParameter(FunctionHeader header, FunctionParameter parameter, ExpressionCompiler compiler);
+
MemberAnnotation createForMember(CodePosition position, CallArguments arguments);
-
+
DefinitionAnnotation createForDefinition(CodePosition position, CallArguments arguments);
-
+
StatementAnnotation createForStatement(CodePosition position, CallArguments arguments);
-
+
ParameterAnnotation createForParameter(CodePosition position, CallArguments arguments);
-
- MemberAnnotation deserializeForMember(CodeSerializationInput input, TypeContext context, IDefinitionMember member);
-
- DefinitionAnnotation deserializeForDefinition(CodeSerializationInput input, TypeContext context);
-
- StatementAnnotation deserializeForStatement(CodeSerializationInput input, StatementContext context);
-
- ParameterAnnotation deserializeForParameter(CodeSerializationInput input, TypeContext context);
+
+ MemberAnnotation deserializeForMember(CodeSerializationInput input, TypeSerializationContext context, IDefinitionMember member);
+
+ DefinitionAnnotation deserializeForDefinition(CodeSerializationInput input, TypeSerializationContext context);
+
+ StatementAnnotation deserializeForStatement(CodeSerializationInput input, StatementSerializationContext context);
+
+ ParameterAnnotation deserializeForParameter(CodeSerializationInput input, TypeSerializationContext context);
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/AnnotationInitializer.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/AnnotationInitializer.java
new file mode 100644
index 000000000..64f5e29e0
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/AnnotationInitializer.java
@@ -0,0 +1,32 @@
+package org.openzen.zenscript.codemodel.annotations;
+
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.GenericMapper;
+import org.openzen.zenscript.codemodel.compilation.AnyMethod;
+import org.openzen.zenscript.codemodel.identifiers.instances.MethodInstance;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.Optional;
+
+public class AnnotationInitializer implements AnyMethod {
+ private final FunctionHeader header;
+
+ public AnnotationInitializer(FunctionHeader header) {
+ this.header = header;
+ }
+
+ @Override
+ public FunctionHeader getHeader() {
+ return header;
+ }
+
+ @Override
+ public Optional asMethod() {
+ return Optional.empty();
+ }
+
+ @Override
+ public AnyMethod withGenericArguments(GenericMapper mapper) {
+ return new AnnotationInitializer(header.withGenericArguments(mapper));
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/AnnotationProcessor.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/AnnotationProcessor.java
index 0418d85e5..8afcf1d33 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/AnnotationProcessor.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/AnnotationProcessor.java
@@ -1,117 +1,64 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import org.openzen.zenscript.codemodel.FunctionHeader;
import org.openzen.zenscript.codemodel.HighLevelDefinition;
import org.openzen.zenscript.codemodel.ModuleProcessor;
import org.openzen.zenscript.codemodel.ScriptBlock;
-import org.openzen.zenscript.codemodel.context.TypeResolutionContext;
import org.openzen.zenscript.codemodel.definition.ExpansionDefinition;
-import org.openzen.zenscript.codemodel.member.CallerMember;
-import org.openzen.zenscript.codemodel.member.CasterMember;
-import org.openzen.zenscript.codemodel.member.ConstMember;
-import org.openzen.zenscript.codemodel.member.ConstructorMember;
-import org.openzen.zenscript.codemodel.member.IteratorMember;
-import org.openzen.zenscript.codemodel.member.DestructorMember;
-import org.openzen.zenscript.codemodel.member.FieldMember;
-import org.openzen.zenscript.codemodel.member.FunctionalMember;
-import org.openzen.zenscript.codemodel.member.GetterMember;
-import org.openzen.zenscript.codemodel.member.IDefinitionMember;
-import org.openzen.zenscript.codemodel.member.ImplementationMember;
-import org.openzen.zenscript.codemodel.member.InnerDefinitionMember;
-import org.openzen.zenscript.codemodel.member.MemberVisitor;
-import org.openzen.zenscript.codemodel.member.MethodMember;
-import org.openzen.zenscript.codemodel.member.OperatorMember;
-import org.openzen.zenscript.codemodel.member.SetterMember;
-import org.openzen.zenscript.codemodel.member.StaticInitializerMember;
-import org.openzen.zenscript.codemodel.member.ref.DefinitionMemberRef;
-import org.openzen.zenscript.codemodel.member.ref.GetterMemberRef;
-import org.openzen.zenscript.codemodel.member.ref.SetterMemberRef;
-import org.openzen.zenscript.codemodel.scope.DefinitionScope;
-import org.openzen.zenscript.codemodel.scope.FileScope;
-import org.openzen.zenscript.codemodel.scope.FunctionScope;
-import org.openzen.zenscript.codemodel.scope.GlobalScriptScope;
-import org.openzen.zenscript.codemodel.scope.StatementScope;
+import org.openzen.zenscript.codemodel.identifiers.ExpansionSymbol;
+import org.openzen.zenscript.codemodel.identifiers.instances.MethodInstance;
+import org.openzen.zenscript.codemodel.member.*;
import org.openzen.zenscript.codemodel.statement.Statement;
-import org.openzen.zenscript.codemodel.type.BasicTypeID;
-/**
- *
- * @author Hoofdgebruiker
- */
+import java.util.ArrayList;
+import java.util.List;
+
public class AnnotationProcessor implements ModuleProcessor {
- private final TypeResolutionContext context;
- private final List expansions;
-
- public AnnotationProcessor(TypeResolutionContext context, List expansions) {
- this.context = context;
+ private final List expansions;
+
+ public AnnotationProcessor(List expansions) {
this.expansions = expansions;
}
-
+
@Override
public ScriptBlock process(ScriptBlock block) {
- FileScope fileScope = new FileScope(context, expansions, new HashMap<>(), member -> {});
- StatementScope scope = new GlobalScriptScope(fileScope, block.scriptHeader);
List transformed = new ArrayList<>();
boolean unchanged = true;
for (Statement statement : block.statements) {
- Statement newStatement = process(statement, scope);
+ Statement newStatement = process(statement);
transformed.add(newStatement);
unchanged &= statement == newStatement;
}
return unchanged ? block : block.withStatements(transformed);
}
-
+
@Override
public void process(HighLevelDefinition definition) {
- FileScope fileScope = new FileScope(context, expansions, new HashMap<>(), member -> {});
- DefinitionScope scope = new DefinitionScope(fileScope, definition);
for (DefinitionAnnotation annotation : definition.annotations) {
- annotation.apply(definition, scope);
+ annotation.apply(definition);
}
-
- MemberAnnotationVisitor visitor = new MemberAnnotationVisitor(scope);
+
+ MemberAnnotationVisitor visitor = new MemberAnnotationVisitor();
for (IDefinitionMember member : definition.members) {
member.accept(visitor);
}
}
-
- private Statement process(Statement statement, StatementScope scope) {
+
+ private Statement process(Statement statement) {
return statement.transform(s -> {
for (StatementAnnotation annotation : s.annotations) {
- s = annotation.apply(s, scope);
+ s = annotation.apply(s);
}
return s;
});
}
-
+
private class MemberAnnotationVisitor implements MemberVisitor {
- private final DefinitionScope scope;
-
- public MemberAnnotationVisitor(DefinitionScope scope) {
- this.scope = scope;
- }
-
- @Override
- public Void visitConst(ConstMember member) {
- for (MemberAnnotation annotation : member.annotations)
- annotation.apply(member, scope);
-
- return null;
- }
@Override
public Void visitField(FieldMember member) {
for (MemberAnnotation annotation : member.annotations)
- annotation.apply(member, scope);
-
+ annotation.apply(member);
+
return null;
}
@@ -120,11 +67,6 @@ public Void visitConstructor(ConstructorMember member) {
return functional(member);
}
- @Override
- public Void visitDestructor(DestructorMember member) {
- return functional(member);
- }
-
@Override
public Void visitMethod(MethodMember member) {
return functional(member);
@@ -155,13 +97,11 @@ public Void visitCustomIterator(IteratorMember member) {
return functional(member);
}
- @Override
- public Void visitCaller(CallerMember member) {
- return functional(member);
- }
-
@Override
public Void visitImplementation(ImplementationMember implementation) {
+ for (MemberAnnotation annotation : implementation.annotations)
+ annotation.apply(implementation);
+
for (IDefinitionMember member : implementation.members) {
member.accept(this);
}
@@ -176,88 +116,72 @@ public Void visitInnerDefinition(InnerDefinitionMember member) {
@Override
public Void visitStaticInitializer(StaticInitializerMember member) {
- StatementScope scope = new FunctionScope(member.position, this.scope, new FunctionHeader(BasicTypeID.VOID));
if (member.body == null) {
throw new IllegalStateException("No body in static initializer @ " + member.position);
} else {
- member.body = process(member.body, scope);
+ member.body = process(member.body);
}
return null;
}
-
+
private Void functional(FunctionalMember member) {
for (MemberAnnotation annotation : member.annotations)
- annotation.apply(member, scope);
-
- if (member.getOverrides() != null) {
- functional(member, member.getOverrides());
- }
-
+ annotation.apply(member);
+
+ member.getOverrides().ifPresent(overrides -> functional(member, overrides));
+
if (member.body == null)
return null;
-
- StatementScope scope = new FunctionScope(member.position, this.scope, member.header);
- member.body = process(member.body, scope);
+
+ member.body = process(member.body);
return null;
}
-
+
private Void getter(GetterMember member) {
for (MemberAnnotation annotation : member.annotations)
- annotation.apply(member, scope);
-
- if (member.getOverrides() != null) {
- getter(member, member.getOverrides());
- }
-
+ annotation.apply(member);
+
+ member.getOverrides().ifPresent(overrides -> getter(member, overrides));
+
if (member.body == null)
return null;
-
- StatementScope scope = new FunctionScope(member.position, this.scope, new FunctionHeader(member.getType()));
- member.body = process(member.body, scope);
+
+ member.body = process(member.body);
return null;
}
-
+
private Void setter(SetterMember member) {
for (MemberAnnotation annotation : member.annotations)
- annotation.apply(member, scope);
-
- if (member.getOverrides() != null) {
- setter(member, member.getOverrides());
- }
-
+ annotation.apply(member);
+
+ member.getOverrides().ifPresent(overrides -> setter(member, overrides));
+
if (member.body == null)
return null;
-
- StatementScope scope = new FunctionScope(member.position, this.scope, new FunctionHeader(BasicTypeID.VOID, member.parameter));
- member.body = process(member.body, scope);
+
+ member.body = process(member.body);
return null;
}
-
- private void functional(FunctionalMember member, DefinitionMemberRef overrides) {
- for (MemberAnnotation annotation : overrides.getAnnotations())
- annotation.applyOnOverridingMethod(member, scope);
-
- if (overrides.getOverrides() != null) {
- functional(member, overrides.getOverrides());
- }
+
+ private void functional(FunctionalMember member, MethodInstance overrides) {
+ for (MemberAnnotation annotation : overrides.method.getAnnotations())
+ annotation.applyOnOverridingMethod(member);
+
+ overrides.method.getOverrides().ifPresent(overrides2 -> functional(member, overrides2));
}
-
- private void getter(GetterMember member, GetterMemberRef overrides) {
- for (MemberAnnotation annotation : overrides.getAnnotations())
- annotation.applyOnOverridingGetter(member, scope);
-
- if (overrides.getOverrides() != null) {
- getter(member, overrides.getOverrides());
- }
+
+ private void getter(GetterMember member, MethodInstance overrides) {
+ for (MemberAnnotation annotation : overrides.method.getAnnotations())
+ annotation.applyOnOverridingGetter(member);
+
+ overrides.method.getOverrides().ifPresent(overrides2 -> getter(member, overrides2));
}
-
- private void setter(SetterMember member, SetterMemberRef overrides) {
- for (MemberAnnotation annotation : overrides.getAnnotations())
- annotation.applyOnOverridingSetter(member, scope);
-
- if (overrides.getOverrides() != null) {
- setter(member, overrides.getOverrides());
- }
+
+ private void setter(SetterMember member, MethodInstance overrides) {
+ for (MemberAnnotation annotation : overrides.method.getAnnotations())
+ annotation.applyOnOverridingSetter(member);
+
+ overrides.method.getOverrides().ifPresent(overrides2 -> setter(member, overrides2));
}
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/DefinitionAnnotation.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/DefinitionAnnotation.java
index f9cab1643..0c9f50b0a 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/DefinitionAnnotation.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/DefinitionAnnotation.java
@@ -1,27 +1,17 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
import org.openzen.zenscript.codemodel.HighLevelDefinition;
-import org.openzen.zenscript.codemodel.context.TypeContext;
-import org.openzen.zenscript.codemodel.scope.BaseScope;
import org.openzen.zenscript.codemodel.serialization.CodeSerializationOutput;
+import org.openzen.zenscript.codemodel.serialization.TypeSerializationContext;
-/**
- *
- * @author Hoofdgebruiker
- */
public interface DefinitionAnnotation {
DefinitionAnnotation[] NONE = new DefinitionAnnotation[0];
-
+
AnnotationDefinition getDefinition();
-
- void apply(HighLevelDefinition definition, BaseScope scope);
-
- void applyOnSubtype(HighLevelDefinition definition, BaseScope scope);
-
- void serialize(CodeSerializationOutput output, HighLevelDefinition definition, TypeContext context);
+
+ void apply(HighLevelDefinition definition);
+
+ void applyOnSubtype(HighLevelDefinition definition);
+
+ void serialize(CodeSerializationOutput output, HighLevelDefinition definition, TypeSerializationContext context);
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidAnnotationDefinition.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidAnnotationDefinition.java
index 52230e0d4..d82f72846 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidAnnotationDefinition.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidAnnotationDefinition.java
@@ -1,34 +1,25 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
-import java.util.Collections;
-import java.util.List;
import org.openzen.zencode.shared.CodePosition;
import org.openzen.zenscript.codemodel.FunctionHeader;
import org.openzen.zenscript.codemodel.FunctionParameter;
import org.openzen.zenscript.codemodel.HighLevelDefinition;
-import org.openzen.zenscript.codemodel.context.StatementContext;
-import org.openzen.zenscript.codemodel.context.TypeContext;
+import org.openzen.zenscript.codemodel.compilation.*;
import org.openzen.zenscript.codemodel.expression.CallArguments;
import org.openzen.zenscript.codemodel.member.IDefinitionMember;
-import org.openzen.zenscript.codemodel.scope.BaseScope;
-import org.openzen.zenscript.codemodel.scope.ExpressionScope;
-import org.openzen.zenscript.codemodel.scope.StatementScope;
import org.openzen.zenscript.codemodel.serialization.CodeSerializationInput;
+import org.openzen.zenscript.codemodel.serialization.StatementSerializationContext;
+import org.openzen.zenscript.codemodel.serialization.TypeSerializationContext;
import org.openzen.zenscript.codemodel.statement.Statement;
-/**
- *
- * @author Hoofdgebruiker
- */
+import java.util.Collections;
+import java.util.List;
+
public class InvalidAnnotationDefinition implements AnnotationDefinition {
public static final InvalidAnnotationDefinition INSTANCE = new InvalidAnnotationDefinition();
-
- private InvalidAnnotationDefinition() {}
+
+ private InvalidAnnotationDefinition() {
+ }
@Override
public String getAnnotationName() {
@@ -36,27 +27,27 @@ public String getAnnotationName() {
}
@Override
- public List getInitializers(BaseScope scope) {
+ public List getInitializers(TypeBuilder types) {
return Collections.emptyList();
}
@Override
- public ExpressionScope getScopeForMember(IDefinitionMember member, BaseScope scope) {
+ public ExpressionCompiler getScopeForMember(IDefinitionMember member, MemberCompiler compiler) {
throw new UnsupportedOperationException("Not a valid annotation");
}
@Override
- public ExpressionScope getScopeForType(HighLevelDefinition definition, BaseScope scope) {
+ public ExpressionCompiler getScopeForType(HighLevelDefinition definition, DefinitionCompiler compiler) {
throw new UnsupportedOperationException("Not a valid annotation");
}
@Override
- public ExpressionScope getScopeForStatement(Statement statement, StatementScope scope) {
+ public ExpressionCompiler getScopeForStatement(Statement statement, StatementCompiler compiler) {
throw new UnsupportedOperationException("Not a valid annotation");
}
@Override
- public ExpressionScope getScopeForParameter(FunctionHeader header, FunctionParameter parameter, BaseScope scope) {
+ public ExpressionCompiler getScopeForParameter(FunctionHeader header, FunctionParameter parameter, ExpressionCompiler compiler) {
throw new UnsupportedOperationException("Not a valid annotation");
}
@@ -81,22 +72,22 @@ public ParameterAnnotation createForParameter(CodePosition position, CallArgumen
}
@Override
- public MemberAnnotation deserializeForMember(CodeSerializationInput input, TypeContext context, IDefinitionMember member) {
+ public MemberAnnotation deserializeForMember(CodeSerializationInput input, TypeSerializationContext context, IDefinitionMember member) {
throw new UnsupportedOperationException("Not a valid annotation");
}
@Override
- public DefinitionAnnotation deserializeForDefinition(CodeSerializationInput input, TypeContext context) {
+ public DefinitionAnnotation deserializeForDefinition(CodeSerializationInput input, TypeSerializationContext context) {
throw new UnsupportedOperationException("Not a valid annotation");
}
@Override
- public StatementAnnotation deserializeForStatement(CodeSerializationInput input, StatementContext context) {
+ public StatementAnnotation deserializeForStatement(CodeSerializationInput input, StatementSerializationContext context) {
throw new UnsupportedOperationException("Not a valid annotation");
}
@Override
- public ParameterAnnotation deserializeForParameter(CodeSerializationInput input, TypeContext context) {
+ public ParameterAnnotation deserializeForParameter(CodeSerializationInput input, TypeSerializationContext context) {
throw new UnsupportedOperationException("Not a valid annotation");
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidDefinitionAnnotation.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidDefinitionAnnotation.java
index 182649df6..db3207b43 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidDefinitionAnnotation.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidDefinitionAnnotation.java
@@ -1,37 +1,24 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zencode.shared.CompileError;
import org.openzen.zencode.shared.CompileException;
-import org.openzen.zencode.shared.CompileExceptionCode;
import org.openzen.zenscript.codemodel.HighLevelDefinition;
-import org.openzen.zenscript.codemodel.context.TypeContext;
-import org.openzen.zenscript.codemodel.scope.BaseScope;
import org.openzen.zenscript.codemodel.serialization.CodeSerializationOutput;
+import org.openzen.zenscript.codemodel.serialization.TypeSerializationContext;
-/**
- *
- * @author Hoofdgebruiker
- */
public class InvalidDefinitionAnnotation implements DefinitionAnnotation {
public final CodePosition position;
- public final CompileExceptionCode code;
- public final String message;
-
- public InvalidDefinitionAnnotation(CodePosition position, CompileExceptionCode code, String message) {
+ public final CompileError error;
+
+ public InvalidDefinitionAnnotation(CodePosition position, CompileError error) {
this.position = position;
- this.code = code;
- this.message = message;
+ this.error = error;
}
-
+
public InvalidDefinitionAnnotation(CompileException ex) {
this.position = ex.position;
- this.code = ex.code;
- this.message = ex.getMessage();
+ this.error = ex.error;
}
@Override
@@ -40,17 +27,17 @@ public AnnotationDefinition getDefinition() {
}
@Override
- public void apply(HighLevelDefinition definition, BaseScope scope) {
-
+ public void apply(HighLevelDefinition definition) {
+
}
@Override
- public void applyOnSubtype(HighLevelDefinition definition, BaseScope scope) {
-
+ public void applyOnSubtype(HighLevelDefinition definition) {
+
}
@Override
- public void serialize(CodeSerializationOutput output, HighLevelDefinition definition, TypeContext context) {
+ public void serialize(CodeSerializationOutput output, HighLevelDefinition definition, TypeSerializationContext context) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidMemberAnnotation.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidMemberAnnotation.java
index 27d4538cf..8cb2e6c78 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidMemberAnnotation.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidMemberAnnotation.java
@@ -1,35 +1,27 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zencode.shared.CompileError;
import org.openzen.zencode.shared.CompileException;
-import org.openzen.zencode.shared.CompileExceptionCode;
-import org.openzen.zenscript.codemodel.HighLevelDefinition;
-import org.openzen.zenscript.codemodel.context.TypeContext;
import org.openzen.zenscript.codemodel.member.FunctionalMember;
import org.openzen.zenscript.codemodel.member.GetterMember;
import org.openzen.zenscript.codemodel.member.IDefinitionMember;
import org.openzen.zenscript.codemodel.member.SetterMember;
-import org.openzen.zenscript.codemodel.scope.BaseScope;
import org.openzen.zenscript.codemodel.serialization.CodeSerializationOutput;
+import org.openzen.zenscript.codemodel.serialization.TypeSerializationContext;
-/**
- *
- * @author Hoofdgebruiker
- */
public class InvalidMemberAnnotation implements MemberAnnotation {
public final CodePosition position;
- public final CompileExceptionCode code;
- public final String message;
-
+ public final CompileError error;
+
+ public InvalidMemberAnnotation(CodePosition position, CompileError error) {
+ this.position = position;
+ this.error = error;
+ }
+
public InvalidMemberAnnotation(CompileException ex) {
this.position = ex.position;
- this.code = ex.code;
- this.message = ex.getMessage();
+ this.error = ex.error;
}
@Override
@@ -38,29 +30,29 @@ public AnnotationDefinition getDefinition() {
}
@Override
- public void apply(IDefinitionMember member, BaseScope scope) {
-
+ public void apply(IDefinitionMember member) {
+
}
@Override
- public void applyOnOverridingMethod(FunctionalMember member, BaseScope scope) {
-
+ public void applyOnOverridingMethod(FunctionalMember member) {
+
}
@Override
- public void applyOnOverridingGetter(GetterMember member, BaseScope scope) {
-
+ public void applyOnOverridingGetter(GetterMember member) {
+
}
@Override
- public void applyOnOverridingSetter(SetterMember member, BaseScope scope) {
-
+ public void applyOnOverridingSetter(SetterMember member) {
+
}
@Override
- public void serialize(CodeSerializationOutput output, IDefinitionMember member, TypeContext context) {
+ public void serialize(CodeSerializationOutput output, IDefinitionMember member, TypeSerializationContext context) {
output.serialize(position);
- output.writeUInt(code.ordinal());
- output.writeString(message);
+ output.writeUInt(error.code.ordinal());
+ output.writeString(error.description);
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidParameterAnnotation.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidParameterAnnotation.java
index 9557335cd..dd907092e 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidParameterAnnotation.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidParameterAnnotation.java
@@ -1,33 +1,15 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
import org.openzen.zencode.shared.CodePosition;
-import org.openzen.zencode.shared.CompileException;
-import org.openzen.zencode.shared.CompileExceptionCode;
+import org.openzen.zencode.shared.CompileError;
-/**
- *
- * @author Hoofdgebruiker
- */
public class InvalidParameterAnnotation implements ParameterAnnotation {
public final CodePosition position;
- public final CompileExceptionCode code;
- public final String message;
-
- public InvalidParameterAnnotation(CodePosition position, CompileExceptionCode code, String message) {
+ public final CompileError error;
+
+ public InvalidParameterAnnotation(CodePosition position, CompileError error) {
this.position = position;
- this.code = code;
- this.message = message;
- }
-
- public InvalidParameterAnnotation(CompileException ex) {
- this.position = ex.position;
- this.code = ex.code;
- this.message = ex.getMessage();
+ this.error = error;
}
@Override
@@ -37,6 +19,6 @@ public AnnotationDefinition getDefinition() {
@Override
public void apply() {
-
+
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidStatementAnnotation.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidStatementAnnotation.java
index 6c5ef622a..10227c7aa 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidStatementAnnotation.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/InvalidStatementAnnotation.java
@@ -1,35 +1,16 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
import org.openzen.zencode.shared.CodePosition;
-import org.openzen.zencode.shared.CompileException;
-import org.openzen.zencode.shared.CompileExceptionCode;
-import org.openzen.zenscript.codemodel.scope.StatementScope;
+import org.openzen.zencode.shared.CompileError;
import org.openzen.zenscript.codemodel.statement.Statement;
-/**
- *
- * @author Hoofdgebruiker
- */
public class InvalidStatementAnnotation implements StatementAnnotation {
public final CodePosition position;
- public final CompileExceptionCode code;
- public final String message;
-
- public InvalidStatementAnnotation(CodePosition position, CompileExceptionCode code, String message) {
+ public final CompileError error;
+
+ public InvalidStatementAnnotation(CodePosition position, CompileError error) {
this.position = position;
- this.code = code;
- this.message = message;
- }
-
- public InvalidStatementAnnotation(CompileException ex) {
- this.position = ex.position;
- this.code = ex.code;
- this.message = ex.getMessage();
+ this.error = error;
}
@Override
@@ -38,7 +19,7 @@ public AnnotationDefinition getDefinition() {
}
@Override
- public Statement apply(Statement statement, StatementScope scope) {
+ public Statement apply(Statement statement) {
return statement;
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/MemberAnnotation.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/MemberAnnotation.java
index 45346b3f2..9a6e3bea9 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/MemberAnnotation.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/MemberAnnotation.java
@@ -1,34 +1,24 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
-import org.openzen.zenscript.codemodel.context.TypeContext;
import org.openzen.zenscript.codemodel.member.FunctionalMember;
import org.openzen.zenscript.codemodel.member.GetterMember;
import org.openzen.zenscript.codemodel.member.IDefinitionMember;
import org.openzen.zenscript.codemodel.member.SetterMember;
-import org.openzen.zenscript.codemodel.scope.BaseScope;
import org.openzen.zenscript.codemodel.serialization.CodeSerializationOutput;
+import org.openzen.zenscript.codemodel.serialization.TypeSerializationContext;
-/**
- *
- * @author Hoofdgebruiker
- */
public interface MemberAnnotation {
MemberAnnotation[] NONE = new MemberAnnotation[0];
-
+
AnnotationDefinition getDefinition();
-
- void apply(IDefinitionMember member, BaseScope scope);
-
- void applyOnOverridingMethod(FunctionalMember member, BaseScope scope);
-
- void applyOnOverridingGetter(GetterMember member, BaseScope scope);
-
- void applyOnOverridingSetter(SetterMember member, BaseScope scope);
-
- void serialize(CodeSerializationOutput output, IDefinitionMember member, TypeContext context);
+
+ void apply(IDefinitionMember member);
+
+ void applyOnOverridingMethod(FunctionalMember member);
+
+ void applyOnOverridingGetter(GetterMember member);
+
+ void applyOnOverridingSetter(SetterMember member);
+
+ void serialize(CodeSerializationOutput output, IDefinitionMember member, TypeSerializationContext context);
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeAnnotationDefinition.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeAnnotationDefinition.java
index 70ef27d09..5fe4038f2 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeAnnotationDefinition.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeAnnotationDefinition.java
@@ -1,40 +1,33 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zencode.shared.CompileException;
import org.openzen.zenscript.codemodel.FunctionHeader;
import org.openzen.zenscript.codemodel.FunctionParameter;
import org.openzen.zenscript.codemodel.HighLevelDefinition;
-import org.openzen.zenscript.codemodel.context.StatementContext;
-import org.openzen.zenscript.codemodel.context.TypeContext;
+import org.openzen.zenscript.codemodel.compilation.*;
+import org.openzen.zenscript.codemodel.constant.CompileTimeConstant;
import org.openzen.zenscript.codemodel.expression.CallArguments;
import org.openzen.zenscript.codemodel.expression.Expression;
import org.openzen.zenscript.codemodel.member.IDefinitionMember;
-import org.openzen.zenscript.codemodel.scope.BaseScope;
-import org.openzen.zenscript.codemodel.scope.ExpressionScope;
-import org.openzen.zenscript.codemodel.scope.StatementScope;
import org.openzen.zenscript.codemodel.serialization.CodeSerializationInput;
+import org.openzen.zenscript.codemodel.serialization.StatementSerializationContext;
+import org.openzen.zenscript.codemodel.serialization.TypeSerializationContext;
import org.openzen.zenscript.codemodel.statement.Statement;
import org.openzen.zenscript.codemodel.type.BasicTypeID;
import java.util.Collections;
import java.util.List;
+import java.util.Optional;
-/**
- *
- * @author Hoofdgebruiker
- */
public class NativeAnnotationDefinition implements AnnotationDefinition {
public static final NativeAnnotationDefinition INSTANCE = new NativeAnnotationDefinition();
-
- private final List INITIALIZERS = Collections.singletonList(
- new FunctionHeader(BasicTypeID.VOID, BasicTypeID.STRING));
-
- private NativeAnnotationDefinition() {}
+
+ private final List INITIALIZERS = Collections.singletonList(
+ new AnnotationInitializer(new FunctionHeader(BasicTypeID.VOID, BasicTypeID.STRING)));
+
+ private NativeAnnotationDefinition() {
+ }
@Override
public String getAnnotationName() {
@@ -42,42 +35,50 @@ public String getAnnotationName() {
}
@Override
- public List getInitializers(BaseScope scope) {
+ public List getInitializers(TypeBuilder types) {
return INITIALIZERS;
}
@Override
- public ExpressionScope getScopeForMember(IDefinitionMember member, BaseScope scope) {
- return new ExpressionScope(scope);
+ public ExpressionCompiler getScopeForMember(IDefinitionMember member, MemberCompiler compiler) {
+ return compiler.forFieldInitializers();
}
@Override
- public ExpressionScope getScopeForType(HighLevelDefinition definition, BaseScope scope) {
- return new ExpressionScope(scope);
+ public ExpressionCompiler getScopeForType(HighLevelDefinition definition, DefinitionCompiler compiler) {
+ return compiler.types().getDefaultValueCompiler();
}
@Override
- public ExpressionScope getScopeForStatement(Statement statement, StatementScope scope) {
- return new ExpressionScope(scope);
+ public ExpressionCompiler getScopeForStatement(Statement statement, StatementCompiler compiler) {
+ return compiler.types().getDefaultValueCompiler();
}
@Override
- public ExpressionScope getScopeForParameter(FunctionHeader header, FunctionParameter parameter, BaseScope scope) {
- return new ExpressionScope(scope);
+ public ExpressionCompiler getScopeForParameter(FunctionHeader header, FunctionParameter parameter, ExpressionCompiler compiler) {
+ return compiler;
}
@Override
public MemberAnnotation createForMember(CodePosition position, CallArguments arguments) {
Expression value = arguments.arguments[0];
- String constant = value.evaluateStringConstant();
- return new NativeMemberAnnotation(constant);
+ Optional constant = value.evaluate().flatMap(CompileTimeConstant::asString).map(c -> c.value);
+ if (constant.isPresent()) {
+ return new NativeMemberAnnotation(constant.get());
+ } else {
+ return new InvalidMemberAnnotation(new CompileException(position, CompileErrors.notAStringConstant()));
+ }
}
@Override
public DefinitionAnnotation createForDefinition(CodePosition position, CallArguments arguments) {
Expression value = arguments.arguments[0];
- String constant = value.evaluateStringConstant();
- return new NativeDefinitionAnnotation(constant);
+ Optional constant = value.evaluate().flatMap(CompileTimeConstant::asString).map(c -> c.value);
+ if (constant.isPresent()) {
+ return new NativeDefinitionAnnotation(constant.get());
+ } else {
+ return new InvalidDefinitionAnnotation(new CompileException(position, CompileErrors.notAStringConstant()));
+ }
}
@Override
@@ -91,24 +92,24 @@ public ParameterAnnotation createForParameter(CodePosition position, CallArgumen
}
@Override
- public MemberAnnotation deserializeForMember(CodeSerializationInput input, TypeContext context, IDefinitionMember member) {
+ public MemberAnnotation deserializeForMember(CodeSerializationInput input, TypeSerializationContext context, IDefinitionMember member) {
String name = input.readString();
return new NativeMemberAnnotation(name);
}
@Override
- public DefinitionAnnotation deserializeForDefinition(CodeSerializationInput input, TypeContext context) {
+ public DefinitionAnnotation deserializeForDefinition(CodeSerializationInput input, TypeSerializationContext context) {
String name = input.readString();
return new NativeDefinitionAnnotation(name);
}
@Override
- public StatementAnnotation deserializeForStatement(CodeSerializationInput input, StatementContext context) {
+ public StatementAnnotation deserializeForStatement(CodeSerializationInput input, StatementSerializationContext context) {
throw new UnsupportedOperationException("Not supported");
}
@Override
- public ParameterAnnotation deserializeForParameter(CodeSerializationInput input, TypeContext context) {
+ public ParameterAnnotation deserializeForParameter(CodeSerializationInput input, TypeSerializationContext context) {
throw new UnsupportedOperationException("Not supported");
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeDefinitionAnnotation.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeDefinitionAnnotation.java
index de65e7de1..dd09980e9 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeDefinitionAnnotation.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeDefinitionAnnotation.java
@@ -1,22 +1,12 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
import org.openzen.zenscript.codemodel.HighLevelDefinition;
-import org.openzen.zenscript.codemodel.context.TypeContext;
-import org.openzen.zenscript.codemodel.scope.BaseScope;
import org.openzen.zenscript.codemodel.serialization.CodeSerializationOutput;
+import org.openzen.zenscript.codemodel.serialization.TypeSerializationContext;
-/**
- *
- * @author Hoofdgebruiker
- */
public class NativeDefinitionAnnotation implements DefinitionAnnotation {
private final String identifier;
-
+
public NativeDefinitionAnnotation(String identifier) {
this.identifier = identifier;
}
@@ -25,19 +15,19 @@ public NativeDefinitionAnnotation(String identifier) {
public AnnotationDefinition getDefinition() {
return NativeAnnotationDefinition.INSTANCE;
}
-
+
@Override
- public void apply(HighLevelDefinition definition, BaseScope scope) {
+ public void apply(HighLevelDefinition definition) {
definition.setTag(NativeTag.class, new NativeTag(identifier));
}
@Override
- public void applyOnSubtype(HighLevelDefinition definition, BaseScope scope) {
+ public void applyOnSubtype(HighLevelDefinition definition) {
// this annotation is not inherited
}
@Override
- public void serialize(CodeSerializationOutput output, HighLevelDefinition definition, TypeContext context) {
+ public void serialize(CodeSerializationOutput output, HighLevelDefinition definition, TypeSerializationContext context) {
output.writeString(identifier);
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeMemberAnnotation.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeMemberAnnotation.java
index c49ac3f15..1796be334 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeMemberAnnotation.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeMemberAnnotation.java
@@ -1,25 +1,15 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
-import org.openzen.zenscript.codemodel.context.TypeContext;
import org.openzen.zenscript.codemodel.member.FunctionalMember;
import org.openzen.zenscript.codemodel.member.GetterMember;
import org.openzen.zenscript.codemodel.member.IDefinitionMember;
import org.openzen.zenscript.codemodel.member.SetterMember;
-import org.openzen.zenscript.codemodel.scope.BaseScope;
import org.openzen.zenscript.codemodel.serialization.CodeSerializationOutput;
+import org.openzen.zenscript.codemodel.serialization.TypeSerializationContext;
-/**
- *
- * @author Hoofdgebruiker
- */
public class NativeMemberAnnotation implements MemberAnnotation {
private final String identifier;
-
+
public NativeMemberAnnotation(String identifier) {
this.identifier = identifier;
}
@@ -28,29 +18,29 @@ public NativeMemberAnnotation(String identifier) {
public AnnotationDefinition getDefinition() {
return NativeAnnotationDefinition.INSTANCE;
}
-
+
@Override
- public void apply(IDefinitionMember member, BaseScope scope) {
+ public void apply(IDefinitionMember member) {
member.setTag(NativeTag.class, new NativeTag(identifier));
}
@Override
- public void applyOnOverridingMethod(FunctionalMember member, BaseScope scope) {
+ public void applyOnOverridingMethod(FunctionalMember member) {
// not inherited
}
@Override
- public void applyOnOverridingGetter(GetterMember member, BaseScope scope) {
+ public void applyOnOverridingGetter(GetterMember member) {
// not inherited
}
@Override
- public void applyOnOverridingSetter(SetterMember member, BaseScope scope) {
+ public void applyOnOverridingSetter(SetterMember member) {
// not inherited
}
@Override
- public void serialize(CodeSerializationOutput output, IDefinitionMember member, TypeContext context) {
+ public void serialize(CodeSerializationOutput output, IDefinitionMember member, TypeSerializationContext context) {
output.writeString(identifier);
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeTag.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeTag.java
index b3ab693f7..89843cad7 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeTag.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/NativeTag.java
@@ -1,19 +1,10 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
import org.openzen.zencode.shared.Tag;
-/**
- *
- * @author Hoofdgebruiker
- */
public class NativeTag implements Tag {
public final String value;
-
+
public NativeTag(String value) {
this.value = value;
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/ParameterAnnotation.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/ParameterAnnotation.java
index 2e7ab248b..1a055444c 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/ParameterAnnotation.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/ParameterAnnotation.java
@@ -1,18 +1,9 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
-/**
- *
- * @author Hoofdgebruiker
- */
public interface ParameterAnnotation {
ParameterAnnotation[] NONE = new ParameterAnnotation[0];
-
+
AnnotationDefinition getDefinition();
-
+
void apply();
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/PreconditionAnnotationDefinition.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/PreconditionAnnotationDefinition.java
index f90871340..4ffad5e6e 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/PreconditionAnnotationDefinition.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/PreconditionAnnotationDefinition.java
@@ -1,45 +1,37 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
import org.openzen.zencode.shared.CodePosition;
import org.openzen.zenscript.codemodel.FunctionHeader;
import org.openzen.zenscript.codemodel.FunctionParameter;
+import org.openzen.zenscript.codemodel.GenericName;
import org.openzen.zenscript.codemodel.HighLevelDefinition;
-import org.openzen.zenscript.codemodel.context.StatementContext;
-import org.openzen.zenscript.codemodel.context.TypeContext;
+import org.openzen.zenscript.codemodel.compilation.*;
+import org.openzen.zenscript.codemodel.constant.CompileTimeConstant;
import org.openzen.zenscript.codemodel.definition.FunctionDefinition;
import org.openzen.zenscript.codemodel.expression.CallArguments;
import org.openzen.zenscript.codemodel.expression.Expression;
import org.openzen.zenscript.codemodel.member.FunctionalMember;
import org.openzen.zenscript.codemodel.member.IDefinitionMember;
-import org.openzen.zenscript.codemodel.scope.BaseScope;
-import org.openzen.zenscript.codemodel.scope.ExpressionScope;
-import org.openzen.zenscript.codemodel.scope.FunctionScope;
-import org.openzen.zenscript.codemodel.scope.StatementScope;
import org.openzen.zenscript.codemodel.serialization.CodeSerializationInput;
+import org.openzen.zenscript.codemodel.serialization.StatementSerializationContext;
+import org.openzen.zenscript.codemodel.serialization.TypeSerializationContext;
import org.openzen.zenscript.codemodel.statement.Statement;
import org.openzen.zenscript.codemodel.type.BasicTypeID;
-import org.openzen.zenscript.codemodel.GenericName;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
-/**
- *
- * @author Hoofdgebruiker
- */
public class PreconditionAnnotationDefinition implements AnnotationDefinition {
public static final PreconditionAnnotationDefinition INSTANCE = new PreconditionAnnotationDefinition();
-
+
private final List enforcementLevelName = Arrays.asList(
new GenericName("stdlib"),
new GenericName("EnforcementLevel"));
-
- private PreconditionAnnotationDefinition() {}
+
+ private PreconditionAnnotationDefinition() {
+ }
@Override
public String getAnnotationName() {
@@ -47,47 +39,52 @@ public String getAnnotationName() {
}
@Override
- public List getInitializers(BaseScope scope) {
- return Collections.singletonList(new FunctionHeader(
+ public List getInitializers(TypeBuilder types) {
+ TypeID enforcementLevel = types.resolve(CodePosition.BUILTIN, enforcementLevelName)
+ .orElseThrow(() -> new RuntimeException("Could not find stdlib.EnforcementLevel"));
+
+ return Collections.singletonList(new AnnotationInitializer(new FunctionHeader(
BasicTypeID.VOID,
- scope.getType(CodePosition.BUILTIN, enforcementLevelName),
+ enforcementLevel,
BasicTypeID.BOOL,
- BasicTypeID.STRING));
+ BasicTypeID.STRING)));
}
@Override
- public ExpressionScope getScopeForMember(IDefinitionMember member, BaseScope scope) {
+ public ExpressionCompiler getScopeForMember(IDefinitionMember member, MemberCompiler compiler) {
if (member instanceof FunctionalMember) {
- FunctionHeader header = ((FunctionalMember)member).header;
- return new ExpressionScope(new FunctionScope(((FunctionalMember) member).position, scope, header));
+ FunctionHeader header = ((FunctionalMember) member).header;
+ return compiler.forMethod(header).expressions();
} else {
throw new UnsupportedOperationException("Can only assign preconditions to methods");
}
}
@Override
- public ExpressionScope getScopeForType(HighLevelDefinition definition, BaseScope scope) {
+ public ExpressionCompiler getScopeForType(HighLevelDefinition definition, DefinitionCompiler compiler) {
if (definition instanceof FunctionDefinition) {
- FunctionHeader header = ((FunctionDefinition)definition).header;
- return new ExpressionScope(new FunctionScope(((FunctionDefinition) definition).position, scope, header));
+ FunctionHeader header = ((FunctionDefinition) definition).header;
+ return compiler.forMembers(definition).forMethod(header).expressions();
} else {
throw new UnsupportedOperationException("Can only assign preconditions to functions");
}
}
@Override
- public ExpressionScope getScopeForStatement(Statement statement, StatementScope scope) {
+ public ExpressionCompiler getScopeForStatement(Statement statement, StatementCompiler compiler) {
throw new UnsupportedOperationException("Not supported");
}
@Override
- public ExpressionScope getScopeForParameter(FunctionHeader header, FunctionParameter parameter, BaseScope scope) {
+ public ExpressionCompiler getScopeForParameter(FunctionHeader header, FunctionParameter parameter, ExpressionCompiler compiler) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public MemberAnnotation createForMember(CodePosition position, CallArguments arguments) {
- String enforcement = arguments.arguments[0].evaluateEnumConstant().name;
+ String enforcement = arguments.arguments[0].evaluate().flatMap(CompileTimeConstant::asEnumValue)
+ .map(c -> c.member.name)
+ .orElse("INVALID");
Expression condition = arguments.arguments[1];
Expression message = arguments.arguments[2];
return new PreconditionForMethod(position, enforcement, condition, message);
@@ -97,7 +94,6 @@ public MemberAnnotation createForMember(CodePosition position, CallArguments arg
public DefinitionAnnotation createForDefinition(CodePosition position, CallArguments arguments) {
throw new UnsupportedOperationException("Not supported");
}
-
@Override
public StatementAnnotation createForStatement(CodePosition position, CallArguments arguments) {
throw new UnsupportedOperationException("Not supported");
@@ -109,27 +105,28 @@ public ParameterAnnotation createForParameter(CodePosition position, CallArgumen
}
@Override
- public MemberAnnotation deserializeForMember(CodeSerializationInput input, TypeContext context, IDefinitionMember member) {
- CodePosition position = input.deserializePosition();
+ public MemberAnnotation deserializeForMember(CodeSerializationInput input, TypeSerializationContext context, IDefinitionMember member) {
+/* CodePosition position = input.deserializePosition();
String enforcement = input.readString();
StatementContext statementContext = new StatementContext(position, context, member.getHeader());
Expression condition = input.deserializeExpression(statementContext);
Expression message = input.deserializeExpression(statementContext);
- return new PreconditionForMethod(position, enforcement, condition, message);
+ return new PreconditionForMethod(position, enforcement, condition, message);*/
+ throw new UnsupportedOperationException("Not yet supported");
}
@Override
- public DefinitionAnnotation deserializeForDefinition(CodeSerializationInput input, TypeContext context) {
+ public DefinitionAnnotation deserializeForDefinition(CodeSerializationInput input, TypeSerializationContext context) {
throw new UnsupportedOperationException("Not supported");
}
@Override
- public StatementAnnotation deserializeForStatement(CodeSerializationInput input, StatementContext context) {
+ public StatementAnnotation deserializeForStatement(CodeSerializationInput input, StatementSerializationContext context) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
- public ParameterAnnotation deserializeForParameter(CodeSerializationInput input, TypeContext context) {
+ public ParameterAnnotation deserializeForParameter(CodeSerializationInput input, TypeSerializationContext context) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/PreconditionForMethod.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/PreconditionForMethod.java
index 6906f34a6..27e63196f 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/PreconditionForMethod.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/PreconditionForMethod.java
@@ -1,44 +1,36 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
import org.openzen.zencode.shared.CodePosition;
-import org.openzen.zencode.shared.CompileException;
-import org.openzen.zenscript.codemodel.OperatorType;
-import org.openzen.zenscript.codemodel.context.StatementContext;
-import org.openzen.zenscript.codemodel.context.TypeContext;
import org.openzen.zenscript.codemodel.expression.CallArguments;
+import org.openzen.zenscript.codemodel.expression.CallExpression;
import org.openzen.zenscript.codemodel.expression.Expression;
import org.openzen.zenscript.codemodel.expression.PanicExpression;
+import org.openzen.zenscript.codemodel.identifiers.instances.MethodInstance;
import org.openzen.zenscript.codemodel.member.FunctionalMember;
import org.openzen.zenscript.codemodel.member.GetterMember;
import org.openzen.zenscript.codemodel.member.IDefinitionMember;
import org.openzen.zenscript.codemodel.member.SetterMember;
-import org.openzen.zenscript.codemodel.scope.BaseScope;
import org.openzen.zenscript.codemodel.serialization.CodeSerializationOutput;
+import org.openzen.zenscript.codemodel.serialization.StatementSerializationContext;
+import org.openzen.zenscript.codemodel.serialization.TypeSerializationContext;
+import org.openzen.zenscript.codemodel.ssa.CodeBlock;
import org.openzen.zenscript.codemodel.statement.BlockStatement;
import org.openzen.zenscript.codemodel.statement.ExpressionStatement;
import org.openzen.zenscript.codemodel.statement.IfStatement;
import org.openzen.zenscript.codemodel.statement.Statement;
import org.openzen.zenscript.codemodel.type.BasicTypeID;
-import org.openzen.zenscript.codemodel.type.member.TypeMembers;
+import org.openzen.zenscript.codemodel.type.builtin.BuiltinMethodSymbol;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
-/**
- *
- * @author Hoofdgebruiker
- */
public class PreconditionForMethod implements MemberAnnotation {
private final CodePosition position;
private final String enforcement;
private final Expression condition;
private final Expression message;
-
+
public PreconditionForMethod(
CodePosition position,
String enforcement,
@@ -49,69 +41,66 @@ public PreconditionForMethod(
this.condition = condition;
this.message = message;
}
-
+
@Override
public AnnotationDefinition getDefinition() {
return PreconditionAnnotationDefinition.INSTANCE;
}
@Override
- public void apply(IDefinitionMember member, BaseScope scope) {
+ public void apply(IDefinitionMember member) {
if (member instanceof GetterMember) {
- applyOnOverridingGetter((GetterMember)member, scope);
+ applyOnOverridingGetter((GetterMember) member);
} else if (member instanceof SetterMember) {
- applyOnOverridingSetter((SetterMember)member, scope);
+ applyOnOverridingSetter((SetterMember) member);
} else if (member instanceof FunctionalMember) {
- applyOnOverridingMethod((FunctionalMember)member, scope);
+ applyOnOverridingMethod((FunctionalMember) member);
}
}
@Override
- public void applyOnOverridingMethod(FunctionalMember member, BaseScope scope) {
- member.body = applyOnOverride(member.body, scope);
+ public void applyOnOverridingMethod(FunctionalMember member) {
+ member.body = applyOnOverride(member.body);
}
@Override
- public void applyOnOverridingGetter(GetterMember member, BaseScope scope) {
- member.body = applyOnOverride(member.body, scope);
+ public void applyOnOverridingGetter(GetterMember member) {
+ member.body = applyOnOverride(member.body);
}
@Override
- public void applyOnOverridingSetter(SetterMember member, BaseScope scope) {
- member.body = applyOnOverride(member.body, scope);
+ public void applyOnOverridingSetter(SetterMember member) {
+ member.body = applyOnOverride(member.body);
}
-
- private Statement applyOnOverride(Statement body, BaseScope scope) {
+
+ private Statement applyOnOverride(Statement body) {
if (body == null)
return body;
-
- try {
- TypeMembers members = scope.getTypeMembers(condition.type);
- Expression inverseCondition = members.getGroup(OperatorType.NOT)
- .call(position, scope, condition, CallArguments.EMPTY, false);
- Statement throwStatement = new ExpressionStatement(position, new PanicExpression(position, BasicTypeID.VOID, message));
- List statements = new ArrayList<>();
- statements.add(new IfStatement(position, inverseCondition, throwStatement, null));
+ CodeBlock block = new CodeBlock();
+ Expression inverseCondition = new CallExpression(
+ position,
+ condition,
+ new MethodInstance(BuiltinMethodSymbol.BOOL_NOT),
+ CallArguments.EMPTY);
- if (body instanceof BlockStatement) {
- statements.addAll(Arrays.asList(((BlockStatement)body).statements));
- } else {
- statements.add(body);
- }
- return new BlockStatement(position, statements.toArray(new Statement[statements.size()]));
- } catch (CompileException ex) {
- // TODO
- ex.printStackTrace();
- return body;
+ Statement throwStatement = new ExpressionStatement(position, new PanicExpression(position, BasicTypeID.VOID, message));
+ List statements = new ArrayList<>();
+ statements.add(new IfStatement(position, inverseCondition, throwStatement, null));
+
+ if (body instanceof BlockStatement) {
+ statements.addAll(Arrays.asList(((BlockStatement) body).statements));
+ } else {
+ statements.add(body);
}
+ return new BlockStatement(position, statements.toArray(new Statement[0]));
}
@Override
- public void serialize(CodeSerializationOutput output, IDefinitionMember member, TypeContext context) {
+ public void serialize(CodeSerializationOutput output, IDefinitionMember member, TypeSerializationContext context) {
output.serialize(position);
output.writeString(enforcement);
- StatementContext statementContext = new StatementContext(position, context, member.getHeader());
+ StatementSerializationContext statementContext = context.forMethod(member.getHeader());
output.serialize(statementContext, condition);
output.serialize(statementContext, message);
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/StatementAnnotation.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/StatementAnnotation.java
index 8137bb67c..1f2aa31a8 100644
--- a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/StatementAnnotation.java
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/annotations/StatementAnnotation.java
@@ -1,21 +1,11 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
package org.openzen.zenscript.codemodel.annotations;
-import org.openzen.zenscript.codemodel.scope.StatementScope;
import org.openzen.zenscript.codemodel.statement.Statement;
-/**
- *
- * @author Hoofdgebruiker
- */
public interface StatementAnnotation {
StatementAnnotation[] NONE = new StatementAnnotation[0];
-
+
AnnotationDefinition getDefinition();
-
- Statement apply(Statement statement, StatementScope scope);
+
+ Statement apply(Statement statement);
}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/AnyMethod.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/AnyMethod.java
new file mode 100644
index 000000000..81d815987
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/AnyMethod.java
@@ -0,0 +1,21 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.GenericMapper;
+import org.openzen.zenscript.codemodel.identifiers.MethodSymbol;
+import org.openzen.zenscript.codemodel.identifiers.instances.MethodInstance;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.Optional;
+
+public interface AnyMethod {
+ FunctionHeader getHeader();
+
+ Optional asMethod();
+
+ AnyMethod withGenericArguments(GenericMapper mapper);
+
+ default boolean hasWideningConversions() {
+ return false;
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CastedEval.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CastedEval.java
new file mode 100644
index 000000000..61356b4bf
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CastedEval.java
@@ -0,0 +1,112 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zencode.shared.CompileError;
+import org.openzen.zenscript.codemodel.expression.*;
+import org.openzen.zenscript.codemodel.type.BasicTypeID;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.Optional;
+
+public class CastedEval {
+ public static CastedEval implicit(ExpressionCompiler compiler, CodePosition position, TypeID type) {
+ return new CastedEval(compiler, position, type, false, false);
+ }
+
+ public static CastedEval implicit(ExpressionCompiler compiler, CodePosition position, TypeID type, TypeID original) {
+ return new CastedEval(compiler, position, type, original, false, false);
+ }
+
+ private final ExpressionCompiler compiler;
+ private final CodePosition position;
+ public final TypeID type;
+ public final TypeID original; // used for lambdas
+ private final boolean explicit;
+ private final boolean optional;
+
+ public CastedEval(ExpressionCompiler compiler, CodePosition position, TypeID type, boolean explicit, boolean optional) {
+ this.compiler = compiler;
+ this.position = position;
+ this.type = type;
+ this.original = type;
+ this.explicit = explicit;
+ this.optional = optional;
+ }
+
+ public CastedEval(ExpressionCompiler compiler, CodePosition position, TypeID type, TypeID original, boolean explicit, boolean optional) {
+ this.compiler = compiler;
+ this.position = position;
+ this.type = type;
+ this.original = original;
+ this.explicit = explicit;
+ this.optional = optional;
+ }
+
+ public CastedExpression of(Expression value) {
+ if (value.type.equals(type) || type == BasicTypeID.UNDETERMINED)
+ return new CastedExpression(CastedExpression.Level.EXACT, value);
+ if (value.type.isInvalid())
+ return CastedExpression.invalidType(value);
+
+ ResolvedType resolvedTargetType = compiler.resolve(type);
+
+ Optional implicitConstructor = resolvedTargetType.findImplicitConstructor();
+ if (implicitConstructor.isPresent()) {
+ CastedExpression fromImplicitConstructor = implicitConstructor.get().casted(compiler, position, this, null, value.wrap(compiler));
+ if (!fromImplicitConstructor.isFailed())
+ return fromImplicitConstructor;
+ }
+
+ ResolvedType resolvedValueType = compiler.resolve(value.type);
+
+ Optional implicitCast = resolvedValueType.tryCastImplicit(type, compiler, position, value, optional);
+ if (implicitCast.isPresent())
+ return CastedExpression.implicit(implicitCast.get());
+
+ Optional castedImplicitlyTo = value.type.castImplicitTo(position, value, type);
+ if (castedImplicitlyTo.isPresent())
+ return CastedExpression.implicit(castedImplicitlyTo.get());
+
+ Optional castedImplicitlyFrom = type.castImplicitFrom(position, value);
+ if (castedImplicitlyFrom.isPresent())
+ return CastedExpression.implicit(castedImplicitlyFrom.get());
+
+ if (value.type == BasicTypeID.NULL && type.isOptional())
+ return CastedExpression.exact(new NullExpression(position, type));
+
+ // TODO: optional cast (implicit value casting map)
+ if (type.isOptional() && !value.type.isOptional()) {
+ CastedEval cast = new CastedEval(compiler, position, type.withoutOptional(), explicit, optional);
+ CastedExpression result = cast.of(value);
+ if (!result.isFailed())
+ return new CastedExpression(result.level, new WrapOptionalExpression(position, result.value, type));
+ } else if (value.type.isOptional() && !type.isOptional()) {
+ CastedExpression result = of(new CheckNullExpression(position, value));
+ if (!result.isFailed())
+ return result;
+ }
+
+ if (this.type.extendsOrImplements(value.type, compiler.getAvailableExpansions()))
+ return CastedExpression.implicit(new SupertypeCastExpression(position, value, type));
+
+ if (explicit) {
+ Optional casted = compiler.resolve(value.type).tryCastExplicit(type, compiler, position, value, optional);
+ if (casted.isPresent())
+ return new CastedExpression(CastedExpression.Level.EXPLICIT, casted.get());
+ }
+
+ return CastedExpression.invalid(position, CompileErrors.cannotCast(value.type, type, explicit));
+ }
+
+ public CastedExpression of(CastedExpression.Level level, Expression value) {
+ if (level == CastedExpression.Level.EXPLICIT && !explicit)
+ return CastedExpression.invalid(position, CompileErrors.cannotCast(value.type, type, explicit));
+
+ CastedExpression casted = of(value);
+ return new CastedExpression(level.max(casted.level), casted.value);
+ }
+
+ public CastedExpression invalid(CompileError error) {
+ return CastedExpression.invalid(position, error);
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CastedExpression.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CastedExpression.java
new file mode 100644
index 000000000..e20c235fe
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CastedExpression.java
@@ -0,0 +1,75 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zencode.shared.CompileError;
+import org.openzen.zenscript.codemodel.expression.Expression;
+import org.openzen.zenscript.codemodel.expression.InvalidExpression;
+import org.openzen.zenscript.codemodel.type.BasicTypeID;
+
+public class CastedExpression {
+ public enum Level {
+ EXACT,
+ WIDENING,
+ IMPLICIT,
+ EXPLICIT,
+ INVALID;
+
+ public Level min(Level other) {
+ return ordinal() < other.ordinal() ? this : other;
+ }
+
+ public Level max(Level other) {
+ return ordinal() < other.ordinal() ? other : this;
+ }
+ }
+
+ public static CastedExpression exact(Expression value) {
+ return new CastedExpression(Level.EXACT, value);
+ }
+
+ public static CastedExpression implicit(Expression value) {
+ return new CastedExpression(Level.IMPLICIT, value);
+ }
+
+ public static CastedExpression explicit(Expression value) {
+ return new CastedExpression(Level.EXPLICIT, value);
+ }
+
+ public static CastedExpression invalid(CodePosition position, CompileError error) {
+ return new CastedExpression(position, error);
+ }
+
+ public static CastedExpression invalid(Expression expression, CompileError error) {
+ return new CastedExpression(Level.INVALID, expression, error);
+ }
+
+ public static CastedExpression invalidType(Expression expression) {
+ return new CastedExpression(Level.INVALID, expression, expression.type.asInvalid().error);
+ }
+
+ public final Level level;
+ public final Expression value;
+ public final CompileError error;
+
+ public CastedExpression(Level level, Expression value) {
+ this.level = level;
+ this.value = value;
+ this.error = level == Level.INVALID ? value.asInvalid().map(i -> i.error).orElse(null) : null;
+ }
+
+ public CastedExpression(CodePosition position, CompileError error) {
+ this.level = Level.INVALID;
+ this.value = new InvalidExpression(position, BasicTypeID.INVALID, error);
+ this.error = error;
+ }
+
+ private CastedExpression(Level level, Expression value, CompileError error) {
+ this.level = level;
+ this.value = value;
+ this.error = error;
+ }
+
+ public boolean isFailed() {
+ return level == Level.INVALID;
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableExpression.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableExpression.java
new file mode 100644
index 000000000..9c5d85dc2
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableExpression.java
@@ -0,0 +1,55 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zenscript.codemodel.expression.switchvalue.ErrorSwitchValue;
+import org.openzen.zenscript.codemodel.expression.switchvalue.SwitchValue;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+
+public interface CompilableExpression {
+ CodePosition getPosition();
+
+ /**
+ * Compiles the given parsed expression to a high-level expression or
+ * partial expression.
+ *
+ * @param compiler expression compiler
+ * @return
+ */
+ CompilingExpression compile(ExpressionCompiler compiler);
+
+ /**
+ * Compiles the given parsed expression to a map key value.
+ *
+ * @param compiler expression compiler
+ * @return
+ */
+ default CompilingExpression compileKey(ExpressionCompiler compiler) {
+ return compile(compiler);
+ }
+
+ default CompilingSwitchValue compileSwitchValue(ExpressionCompiler compiler) {
+ return type -> new ErrorSwitchValue(getPosition(), CompileErrors.invalidSwitchCaseExpression());
+ }
+
+ /**
+ * Converts this expression to a lambda expression header, if possible.
+ *
+ * @return
+ */
+ default Optional asLambdaHeader() {
+ return Optional.empty();
+ }
+
+ /**
+ * Converts this expression to a lambda header parameter, if possible.
+ *
+ * @return
+ */
+ default Optional asLambdaHeaderParameter() {
+ return Optional.empty();
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableLambdaHeader.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableLambdaHeader.java
new file mode 100644
index 000000000..766e50102
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableLambdaHeader.java
@@ -0,0 +1,42 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.FunctionParameter;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.Arrays;
+import java.util.Optional;
+
+public class CompilableLambdaHeader {
+ private final TypeID returnType;
+ private final Parameter[] parameters;
+
+ public CompilableLambdaHeader(TypeID returnType, Parameter... parameters) {
+ this.returnType = returnType;
+ this.parameters = parameters;
+ }
+
+ public FunctionHeader compile(TypeBuilder types) {
+ return new FunctionHeader(
+ returnType,
+ Arrays.stream(parameters).map(p -> new FunctionParameter(p.type, p.name)).toArray(FunctionParameter[]::new));
+ }
+
+ public static class Parameter {
+ private final String name;
+ private final TypeID type;
+
+ public Parameter(String name, TypeID type) {
+ this.name = name;
+ this.type = type;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Optional getType() {
+ return Optional.ofNullable(type);
+ }
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableMember.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableMember.java
new file mode 100644
index 000000000..ca14f1daa
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableMember.java
@@ -0,0 +1,12 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.HighLevelDefinition;
+import org.openzen.zenscript.codemodel.member.ImplementationMember;
+
+public interface CompilableMember {
+ CompilingMember compile(
+ HighLevelDefinition definition,
+ ImplementationMember implementation,
+ MemberCompiler compiler
+ );
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableType.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableType.java
new file mode 100644
index 000000000..697baf45d
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilableType.java
@@ -0,0 +1,16 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.HighLevelDefinition;
+import org.openzen.zenscript.codemodel.context.CompilingPackage;
+
+import java.util.List;
+
+public interface CompilableType {
+ void registerCompiling(
+ List definitions,
+ List expansions,
+ DefinitionCompiler compiler
+ );
+
+ CompilingDefinition compileAsDefinition(DefinitionCompiler compiler, HighLevelDefinition outer);
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilationHelper.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilationHelper.java
new file mode 100644
index 000000000..f800828b7
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilationHelper.java
@@ -0,0 +1,63 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zenscript.codemodel.CompareType;
+import org.openzen.zenscript.codemodel.OperatorType;
+import org.openzen.zenscript.codemodel.expression.CallArguments;
+import org.openzen.zenscript.codemodel.expression.CallExpression;
+import org.openzen.zenscript.codemodel.expression.Expression;
+import org.openzen.zenscript.codemodel.identifiers.instances.MethodInstance;
+import org.openzen.zenscript.codemodel.type.BasicTypeID;
+import org.openzen.zenscript.codemodel.type.TypeID;
+import org.openzen.zenscript.codemodel.type.builtin.BuiltinMethodSymbol;
+
+import java.util.Optional;
+
+public class CompilationHelper {
+ private final ExpressionCompiler compiler;
+ private final CodePosition position;
+
+ public CompilationHelper(ExpressionCompiler compiler, CodePosition position) {
+ this.compiler = compiler;
+ this.position = position;
+ }
+
+ public Expression compare(Expression left, CompilingExpression right, CompareType type) {
+ ResolvedType resolved = compiler.resolve(left.type);
+
+ if (type == CompareType.EQ) {
+ Optional equals = resolved.findOperator(OperatorType.EQUALS);
+ if (equals.isPresent()) {
+ return equals.get().call(compiler, position, left, TypeID.NONE, right);
+ }
+ } else if (type == CompareType.NE) {
+ Optional notEquals = resolved.findOperator(OperatorType.NOTEQUALS);
+ if (notEquals.isPresent()) {
+ return notEquals.get().call(compiler, position, left, TypeID.NONE, right);
+ } else {
+ Optional equals = resolved.findOperator(OperatorType.EQUALS);
+ if (equals.isPresent()) {
+ Expression value = equals.get().call(compiler, position, left, TypeID.NONE, right);
+ return new CallExpression(position, value, new MethodInstance(BuiltinMethodSymbol.BOOL_NOT), CallArguments.EMPTY);
+ }
+ }
+ }
+ CastedExpression result = resolved.comparators()
+ .stream()
+ .map(comparator -> comparator.compare(compiler, position, left, right, type))
+ .reduce((a, b) -> {
+ if (a.isFailed()) return b;
+ if (b.isFailed()) return a;
+
+ if (a.level.compareTo(b.level) == 0) {
+ return new CastedExpression(a.level, compiler.at(position).invalid(CompileErrors.ambiguousComparison(a.value.type, b.value.type)));
+ } else if (a.level.compareTo(b.level) > 0) {
+ return a;
+ } else {
+ return b;
+ }
+ })
+ .orElseGet(() -> CastedExpression.invalid(position, CompileErrors.noOperatorInType(left.type, OperatorType.COMPARE)));
+ return result.value;
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompileContext.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompileContext.java
new file mode 100644
index 000000000..4e7a43e8c
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompileContext.java
@@ -0,0 +1,139 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.GenericName;
+import org.openzen.zenscript.codemodel.annotations.AnnotationDefinition;
+import org.openzen.zenscript.codemodel.compilation.impl.AbstractTypeBuilder;
+import org.openzen.zenscript.codemodel.compilation.impl.compiler.ExpressionCompilerImpl;
+import org.openzen.zenscript.codemodel.compilation.impl.compiler.LocalSymbols;
+import org.openzen.zenscript.codemodel.definition.ExpansionDefinition;
+import org.openzen.zenscript.codemodel.definition.ZSPackage;
+import org.openzen.zenscript.codemodel.identifiers.ExpansionSymbol;
+import org.openzen.zenscript.codemodel.identifiers.TypeSymbol;
+import org.openzen.zenscript.codemodel.type.DefinitionTypeID;
+import org.openzen.zenscript.codemodel.globals.IGlobal;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.*;
+
+public class CompileContext extends AbstractTypeBuilder implements TypeResolver {
+ private final ZSPackage rootPackage;
+ private final ZSPackage modulePackage;
+ private final List expansions;
+ private final Map globals;
+ private final Map compiling = new HashMap<>();
+ private final Map annotations = new HashMap<>();
+
+ public CompileContext(
+ ZSPackage rootPackage,
+ ZSPackage modulePackage,
+ List expansions,
+ Map globals,
+ List annotations
+ ) {
+ this.rootPackage = rootPackage;
+ this.modulePackage = modulePackage;
+ this.expansions = expansions;
+ this.globals = globals;
+
+ for (AnnotationDefinition annotation : annotations) {
+ this.annotations.put(annotation.getAnnotationName(), annotation);
+ }
+ }
+
+ /**
+ * Creates an expression compiler without further context.
+ *
+ * @return expression compiler
+ */
+ public ExpressionCompiler createStaticCompiler() {
+ return new ExpressionCompilerImpl(this,null, this, null, LocalSymbols.empty(), null);
+ }
+
+ /**
+ * Creates an expression compiler for the given context.
+ *
+ * @param localType local type (can be null)
+ * @param thrownType local thrown type (can be null)
+ * @param locals locals
+ * @param header local function header (can be null)
+ * @return expression compiler suited for the local context
+ */
+ public ExpressionCompiler createExpressionCompiler(LocalType localType, TypeID thrownType, LocalSymbols locals, FunctionHeader header) {
+ return new ExpressionCompilerImpl(this, localType, this, thrownType, locals, header);
+ }
+
+ public void addCompiling(CompilingDefinition definition) {
+ compiling.put(definition.getName(), definition);
+ }
+
+ public void addExpansion(ExpansionDefinition expansion) {
+ expansions.add(expansion);
+ }
+
+ @Override
+ public List getAvailableExpansions() {
+ return expansions;
+ }
+
+ public Optional findGlobal(String name) {
+ return Optional.ofNullable(globals.get(name));
+ }
+
+ @Override
+ public ResolvedType resolve(TypeID type) {
+ return type.resolve().withExpansions(expansions);
+ }
+
+ @Override
+ public Optional resolve(CodePosition position, List name) {
+ if (compiling.containsKey(name.get(0).name)) {
+ CompilingDefinition definition = compiling.get(name.get(0).name);
+ for (int i = 1; i < name.size(); i++) {
+ Optional inner = definition.getInner(name.get(i).name);
+ if (inner.isPresent()) {
+ definition = inner.get();
+ } else {
+ return Optional.empty();
+ }
+ }
+ return Optional.of(DefinitionTypeID.create(definition.getDefinition(), name.get(name.size() - 1).arguments));
+ } else if (rootPackage.contains(name.get(0).name)) {
+ return rootPackage.getType(name);
+ }
+
+ return Optional.ofNullable(globals.get(name.get(0).name))
+ .flatMap(t -> t.getType(position, this, name.get(0).arguments))
+ .flatMap(t -> {
+ for (int i = 1; i < name.size(); i++) {
+ Optional inner = t.resolveWithoutExpansions().findInnerType(name.get(i).name);
+ if (inner.isPresent()) {
+ t = DefinitionTypeID.create(inner.get(), name.get(i).arguments);
+ } else {
+ return Optional.empty();
+ }
+ }
+ return Optional.of(t);
+ });
+ }
+
+ @Override
+ public Optional getRootPackage(String name) {
+ return rootPackage.getOptional(name);
+ }
+
+ @Override
+ public Optional resolveAnnotation(List name) {
+ if (name.size() > 1) {
+ return Optional.empty();
+ } else {
+ return Optional.ofNullable(annotations.get(name.get(0).name));
+ }
+ }
+
+ @Override
+ public ExpressionCompiler getDefaultValueCompiler() {
+ return createStaticCompiler();
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompileErrors.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompileErrors.java
new file mode 100644
index 000000000..3a0b3e537
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompileErrors.java
@@ -0,0 +1,614 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CompileError;
+import org.openzen.zencode.shared.CompileExceptionCode;
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.OperatorType;
+import org.openzen.zenscript.codemodel.identifiers.MethodID;
+import org.openzen.zenscript.codemodel.identifiers.MethodSymbol;
+import org.openzen.zenscript.codemodel.identifiers.instances.MethodInstance;
+import org.openzen.zenscript.codemodel.member.IDefinitionMember;
+import org.openzen.zenscript.codemodel.type.BasicTypeID;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class CompileErrors {
+ private CompileErrors() {}
+
+ public static CompileError noIntersectionBetweenTypes(TypeID a, TypeID b) {
+ return new CompileError(CompileExceptionCode.TYPE_CANNOT_UNITE, "Cannot find intersection between " + a + " and " + b);
+ }
+
+ public static CompileError ambiguousType(List candidates) {
+ String possibleTypes = candidates.stream().map(Object::toString).collect(Collectors.joining(", "));
+ return new CompileError(CompileExceptionCode.INFERENCE_AMBIGUOUS, "Type inference ambiguity, possible types: " + possibleTypes);
+ }
+
+ public static CompileError cannotCompare(TypeID a, TypeID b) {
+ return new CompileError(CompileExceptionCode.CANNOT_COMPARE, "Cannot compare " + a + " and " + b);
+ }
+
+ public static CompileError ambiguousComparison(TypeID a, TypeID b) {
+ return new CompileError(CompileExceptionCode.AMBIGUOUS_COMPARISON, "Ambiguous comparison, not sure to compare as " + a + " or " + b);
+ }
+
+ public static CompileError noMemberInType(TypeID type, String name) {
+ return new CompileError(CompileExceptionCode.NO_SUCH_MEMBER, "No member " + name + " in type " + type);
+ }
+
+ public static CompileError noGetterInType(TypeID type, String name) {
+ return new CompileError(CompileExceptionCode.NO_SUCH_MEMBER, "No getter " + name + " in type " + type);
+ }
+
+ public static CompileError noSetterInType(TypeID type, String name) {
+ return new CompileError(CompileExceptionCode.NO_SUCH_MEMBER, "No setter " + name + " in type " + type);
+ }
+
+ public static CompileError noFieldInType(TypeID type, String name) {
+ return new CompileError(CompileExceptionCode.NO_SUCH_MEMBER, "No field " + name + " in type " + type);
+ }
+
+ public static CompileError noOperatorInType(TypeID type, OperatorType operator) {
+ return new CompileError(CompileExceptionCode.NO_SUCH_MEMBER, "No operator " + operator + " in type " + type);
+ }
+
+ public static CompileError noThisInScope() {
+ return new CompileError(CompileExceptionCode.USING_THIS_OUTSIDE_TYPE, "Not in an instance method; cannot use this");
+ }
+
+ public static CompileError localTypeNoSuper() {
+ return new CompileError(CompileExceptionCode.SUPER_CALL_NO_SUPERCLASS, "Local class has no supertype");
+ }
+
+ public static CompileError invalidSwitchCaseExpression() {
+ return new CompileError(CompileExceptionCode.INVALID_SWITCH_CASE, "Invalid expression for switch case");
+ }
+
+ public static CompileError cannotUseTypeAsValue() {
+ return new CompileError(CompileExceptionCode.TYPE_NOT_VALUE, "Type cannot be used as value");
+ }
+
+ public static CompileError cannotUsePackageAsValue() {
+ return new CompileError(CompileExceptionCode.PACKAGE_NOT_VALUE, "Package cannot be used as value");
+ }
+
+ public static CompileError associativeKeyCannotHaveTypeParameters() {
+ return new CompileError(CompileExceptionCode.INVALID_ASSOC_KEY,
+ "Associative array key cannot have type parameters");
+ }
+
+ public static CompileError noMatchValuesForInference() {
+ return new CompileError(CompileExceptionCode.CANNOT_INFER_RETURN_TYPE, "Cannot infer value from an empty match expression");
+ }
+
+ public static CompileError tryConvertWithoutResult() {
+ return new CompileError(CompileExceptionCode.TRY_CONVERT_WITHOUT_RESULT, "try? expression requires result return type");
+ }
+
+ public static CompileError tryConvertRequiresThrow() {
+ return new CompileError(CompileExceptionCode.TRY_CONVERT_WITHOUT_THROW, "try? expression is only valid on an expression which throws");
+ }
+
+ public static CompileError noDollarHere() {
+ return new CompileError(CompileExceptionCode.NO_DOLLAR_HERE, "No dollar expression available in this context");
+ }
+
+ public static CompileError stringInsteadOfChar() {
+ return new CompileError(CompileExceptionCode.INVALID_SWITCH_CASE, "char value expected but string given");
+ }
+
+ public static CompileError stringForNonStringSwitchValue(TypeID type) {
+ return new CompileError(CompileExceptionCode.INVALID_SWITCH_CASE, "canot use string as " + type + " switch value");
+ }
+
+ public static CompileError typeArgumentsNotAllowedHere() {
+ return new CompileError(CompileExceptionCode.TYPE_ARGUMENTS_NOT_ALLOWED, "Type arguments not allowed here");
+ }
+
+ public static CompileError invalidLValue() {
+ return new CompileError(CompileExceptionCode.CANNOT_ASSIGN, "Invalid lvalue");
+ }
+
+ public static CompileError invalidArrayType(TypeID type) {
+ return new CompileError(CompileExceptionCode.INVALID_ARRAY_TYPE, "Cannot compile an array as " + type);
+ }
+
+ public static CompileError noSuchVariable(ExpressionCompiler compiler, String name) {
+ StringBuilder builder = new StringBuilder("No such symbol: " + name);
+ List possibleImports = compiler.findCandidateImports(name);
+ if (!possibleImports.isEmpty()){
+ builder.append("\nPossible imports:");
+ possibleImports.forEach(n -> builder.append("\n").append(n));
+ }
+
+ return new CompileError(CompileExceptionCode.UNDEFINED_VARIABLE, builder.toString());
+ }
+
+ public static CompileError tryRethrowRequiresResult() {
+ return new CompileError(CompileExceptionCode.TRY_RETHROW_NO_THROW, "Cannot rethrow: no throws or try/catch and no result return type");
+ }
+
+ public static CompileError cannotThrowHere() {
+ return new CompileError(CompileExceptionCode.CANNOT_THROW_HERE, "Cannot throw here");
+ }
+
+ public static CompileError cannotInferEmptyArray() {
+ return new CompileError(CompileExceptionCode.UNTYPED_EMPTY_ARRAY, "Cannot infer type of empty array");
+ }
+
+ public static CompileError invalidNumberOfArguments(int actual, int expected) {
+ return new CompileError(CompileExceptionCode.INVALID_ARGUMENTS, "Invalid number of arguments, " + expected + " expected but " + actual + " given");
+ }
+
+ public static CompileError cannotInfer() {
+ return new CompileError(CompileExceptionCode.CANNOT_INFER_RETURN_TYPE, "Could not infer return type");
+ }
+
+ public static CompileError cannotCall() {
+ return new CompileError(CompileExceptionCode.CANNOT_CALL, "Not a callable expression");
+ }
+
+ public static CompileError invalidFloatSuffix(String suffix) {
+ return new CompileError(CompileExceptionCode.INVALID_SUFFIX, "Invalid number literal suffix: " + suffix);
+ }
+
+ public static CompileError cannotCompileFloatLiteralAs(TypeID type) {
+ return new CompileError(CompileExceptionCode.INVALID_CAST, "Cannot compile float literal as " + type);
+ }
+
+ public static CompileError cannotCompileFloatLiteralAs(TypeID type, String suffix) {
+ return new CompileError(CompileExceptionCode.INVALID_CAST, "Cannot compile float literal as " + type + " using suffix " + suffix);
+ }
+
+ public static CompileError cannotCast(TypeID fromType, TypeID toType, boolean explicit) {
+ if (explicit) {
+ return new CompileError(CompileExceptionCode.INVALID_CAST, "Cannot cast " + fromType + " to " + toType + ", even explicitly");
+ } else {
+ return new CompileError(CompileExceptionCode.INVALID_CAST, "Cannot implicitly cast " + fromType + " to " + toType);
+ }
+ }
+
+ public static CompileError bracketMultipleExpressions() {
+ return new CompileError(CompileExceptionCode.BRACKET_MULTIPLE_EXPRESSIONS, "Bracket expression may have only one expression");
+ }
+
+ public static CompileError invalidIntSuffix(String suffix) {
+ return new CompileError(CompileExceptionCode.INVALID_SUFFIX, "Invalid integer literal suffix: " + suffix);
+ }
+
+ public static CompileError cannotInferNull() {
+ return new CompileError(CompileExceptionCode.CANNOT_INFER_RETURN_TYPE, "Cannot infer the type of null");
+ }
+
+ public static CompileError invalidRangeType(TypeID type) {
+ return new CompileError(CompileExceptionCode.INVALID_TYPE, "Cannot construct range from type " + type);
+ }
+
+ public static CompileError invalidCharLiteral() {
+ return new CompileError(CompileExceptionCode.INVALID_CHAR_LITERAL, "char value expected but string given");
+ }
+
+ public static CompileError superNotExpression() {
+ return new CompileError(CompileExceptionCode.NOT_AN_EXPRESSION, "super is not a valid expression");
+ }
+
+ public static CompileError noContextMemberInType(TypeID type, String name) {
+ return new CompileError(CompileExceptionCode.NO_SUCH_MEMBER, "No enum or variant member named " + name + " in type " + type);
+ }
+
+ public static CompileError genericMapConstructedEmpty() {
+ return new CompileError(CompileExceptionCode.GENERIC_MAP_CONSTRUCTED_EMPTY, "Generic map construction must be empty");
+ }
+
+ public static CompileError invalidMapType(TypeID type) {
+ return new CompileError(CompileExceptionCode.INVALID_TYPE, "Cannot construct type " + type + " from map");
+ }
+
+ public static CompileError invalidMapKey() {
+ return new CompileError(CompileExceptionCode.INVALID_ASSOC_KEY, "Invalid map key");
+ }
+
+ public static CompileError missingParameter(String name) {
+ return new CompileError(CompileExceptionCode.MISSING_PARAMETER, "Parameter " + name + " missing in method invocation");
+ }
+
+ public static CompileError unknownParameter(String name) {
+ return new CompileError(CompileExceptionCode.NO_SUCH_PARAMETER, "No parameter with the name " + name + " exists");
+ }
+
+ public static CompileError cannotInferEmptyMap() {
+ return new CompileError(CompileExceptionCode.UNTYPED_EMPTY_MAP, "Cannot infer type of empty map");
+ }
+
+ public static CompileError invalidPostfix() {
+ return new CompileError(CompileExceptionCode.INVALID_POSTFIX, "Invalid postfix expression");
+ }
+
+ public static CompileError breakWithoutLoop(String name) {
+ return new CompileError(CompileExceptionCode.BREAK_OUTSIDE_LOOP, name == null ? "Not in a loop" : "No such loop: " + name);
+ }
+
+ public static CompileError continueOutsideLoop(String name) {
+ return new CompileError(CompileExceptionCode.CONTINUE_OUTSIDE_LOOP, name == null ? "Not in a loop" : "No such loop: " + name);
+ }
+
+ public static CompileError noSuchIterator(TypeID listType, int variables) {
+ return new CompileError(CompileExceptionCode.NO_SUCH_ITERATOR, listType + " doesn't have an iterator with " + variables + " variables");
+ }
+
+ public static CompileError returnOutsideFunction() {
+ return new CompileError(CompileExceptionCode.RETURN_OUTSIDE_FUNCTION, "Cannot return a value outside a function");
+ }
+
+ public static CompileError varWithoutTypeOrInitializer() {
+ return new CompileError(CompileExceptionCode.VAR_WITHOUT_TYPE_OR_INITIALIZER, "Local variables must have either a type or an initializer");
+ }
+
+ public static CompileError rangeTypeFromToDifferent() {
+ return new CompileError(CompileExceptionCode.NO_SUCH_TYPE, "from and to in a range must be the same type");
+ }
+
+ public static CompileError invalidTypeArguments() {
+ return new CompileError(CompileExceptionCode.INVALID_TYPE_ARGUMENTS, "Invalid number of type arguments");
+ }
+
+ public static CompileError invalidType() {
+ return new CompileError(CompileExceptionCode.INVALID_TYPE, "Invalid type");
+ }
+
+ public static CompileError noInnerType(TypeID type, String name) {
+ return new CompileError(CompileExceptionCode.NO_SUCH_TYPE, "No such inner type in " + type + ": " + name);
+ }
+
+ public static CompileError notAStringConstant() {
+ return new CompileError(CompileExceptionCode.NOT_A_CONSTANT, "Not a string constant");
+ }
+
+ public static CompileError ambiguousCall(List candidates) {
+ StringBuilder message = new StringBuilder("Ambiguous call; multiple headers match:");
+ for (FunctionHeader header : candidates) {
+ message.append("\n").append(header.toString());
+ }
+ return new CompileError(CompileExceptionCode.CALL_AMBIGUOUS, message.toString());
+ }
+
+ public static CompileError noMethodMatched(List candidates, List argumentTypes) {
+ FunctionHeader expectedHeader = new FunctionHeader(BasicTypeID.UNDETERMINED, argumentTypes.toArray(TypeID.NONE));
+
+ StringBuilder message = new StringBuilder("Method invocation invalid, none of these overloads match:");
+ for (FunctionHeader header : candidates) {
+ message.append("\n - ").append(header.toString());
+ }
+ message.append("\nTarget overload should be compatible with header ").append(expectedHeader);
+ // TODO("Reimplement this once we are in a better place for it")
+ // for (FunctionHeader candidate : candidateFunctions)
+ // explanation.append(candidate.explainWhyIncompatible(scope, arguments)).append("\n");
+ return new CompileError(CompileExceptionCode.CALL_NO_VALID_METHOD, message.toString());
+ }
+
+ public static CompileError annotationNotFound(String type) {
+ return new CompileError(CompileExceptionCode.UNKNOWN_ANNOTATION, "Unknown annotation type: " + type);
+ }
+
+ public static CompileError duplicateGlobal(String name) {
+ return new CompileError(CompileExceptionCode.DUPLICATE_GLOBAL, "Duplicate global: " + name);
+ }
+
+ public static CompileError variantValueWithoutArguments() {
+ return new CompileError(CompileExceptionCode.VARIANT_OPTION_NOT_AN_EXPRESSION, "Variant options need parameters");
+ }
+
+ public static CompileError noSuchModule(String name) {
+ return new CompileError(CompileExceptionCode.NO_SUCH_MODULE, "Module not found: " + name);
+ }
+
+ public static CompileError overrideWithoutBase() {
+ return new CompileError(CompileExceptionCode.OVERRIDE_WITHOUT_BASE, "Override specified without base type");
+ }
+
+ public static CompileError overriddenMethodNotFound(MethodID method, FunctionHeader header) {
+ return new CompileError(CompileExceptionCode.OVERRIDDEN_METHOD_NOT_FOUND, "Could not find the base method for " + method + header);
+ }
+
+ public static CompileError fieldWithoutType() {
+ return new CompileError(CompileExceptionCode.PRECOMPILE_FAILED, "Could not infer type since no initializer is given");
+ }
+
+ public static CompileError ambiguousExpansionCall(List methods) {
+ return new CompileError(CompileExceptionCode.AMBIGUOUS_EXPANSION_CALL, "Ambigious expansion call (" + methods.size() + " candidates)");
+ }
+
+ public static CompileError deserializationError(String message) {
+ return new CompileError(CompileExceptionCode.DESERIALIZATION_ERROR, message);
+ }
+
+ public static CompileError notAnExpression(String message) {
+ return new CompileError(CompileExceptionCode.NOT_AN_EXPRESSION, message);
+ }
+
+ public static CompileError duplicateFieldName(String name) {
+ return new CompileError(CompileExceptionCode.DUPLICATE_FIELD_NAME, "Duplicate field name: " + name);
+ }
+
+ public static CompileError constValueInvalidType(String name, TypeID expected, TypeID actual) {
+ return new CompileError(CompileExceptionCode.CONST_INVALID_INITIALIZER, "Invalid initializer for const " + name + ": " + expected + " expected but " + actual + " given");
+ }
+
+ public static CompileError duplicateConstructor(FunctionHeader existing) {
+ return new CompileError(CompileExceptionCode.DUPLICATE_CONSTRUCTOR, "Duplicate constructor, conflicts with this" + existing);
+ }
+
+ public static CompileError constructorWithoutBody() {
+ return new CompileError(CompileExceptionCode.METHOD_BODY_REQUIRED, "Constructors must have a method body");
+ }
+
+ public static CompileError constructorNotForwarded() {
+ return new CompileError(CompileExceptionCode.CONSTRUCTOR_FORWARD_MISSING, "Constructor not forwarded to base type");
+ }
+
+ public static CompileError duplicateEnumValue(String name) {
+ return new CompileError(CompileExceptionCode.DUPLICATE_ENUM_VALUE, "Duplicate enum value: " + name);
+ }
+
+ public static CompileError duplicateDestructor() {
+ return new CompileError(CompileExceptionCode.DUPLICATE_DESTRUCTOR, "Type already has a destructor");
+ }
+
+ public static CompileError destructorCannotThrow() {
+ return new CompileError(CompileExceptionCode.DESTRUCTOR_CANNOT_THROW, "Destructor cannot throw exceptions");
+ }
+
+ public static CompileError cannotNestImplementations() {
+ return new CompileError(CompileExceptionCode.CANNOT_NEST_IMPLEMENTATIONS, "Implementations cannot be nested");
+ }
+
+ public static CompileError duplicateImplementation(TypeID type) {
+ return new CompileError(CompileExceptionCode.DUPLICATE_IMPLEMENTATION, "Type is already implemented: " + type);
+ }
+
+ public static CompileError invalidImplementedType(TypeID type) {
+ return new CompileError(CompileExceptionCode.INVALID_IMPLEMENTED_TYPE, "Cannot implement " + type + " since it is not an interface");
+ }
+
+ public static CompileError duplicateMember(String name) {
+ return new CompileError(CompileExceptionCode.DUPLICATE_MEMBER, "Duplicate member: " + name);
+ }
+
+ public static CompileError staticInitializerCannotThrow() {
+ return new CompileError(CompileExceptionCode.CANNOT_THROW_HERE, "Static initializer cannot throw exceptions");
+ }
+
+ public static CompileError cannotThrowWithoutThrows() {
+ return new CompileError(CompileExceptionCode.CANNOT_THROW_HERE, "Method is throwing but doesn't declare thrown type in method header");
+ }
+
+ public static CompileError invalidThrownType(TypeID expected, TypeID actual) {
+ return new CompileError(CompileExceptionCode.INVALID_THROWN_TYPE, "Thrown type is wrong: " + expected + " expected but " + actual + " thrown");
+ }
+
+ public static CompileError invalidOperand(String message) {
+ return new CompileError(CompileExceptionCode.INVALID_OPERAND_TYPE, message);
+ }
+
+ public static CompileError notInstanceCallableMethod(MethodID id) {
+ return new CompileError(CompileExceptionCode.CANNOT_CALL, "Cannot call this method on a value: " + id + "(" + id.getKind() + ")");
+ }
+
+ public static CompileError notStaticCallableMethod(MethodID id) {
+ return new CompileError(CompileExceptionCode.CANNOT_CALL, "Cannot call this method statically: " + id + "(" + id.getKind() + ")");
+ }
+
+ public static CompileError notSuperCallableMethod(MethodID id) {
+ return new CompileError(CompileExceptionCode.CANNOT_CALL, "Cannot call this method on super: " + id + "(" + id.getKind() + ")");
+ }
+
+ public static CompileError constructorForwardOutsideConstructor() {
+ return new CompileError(CompileExceptionCode.CONSTRUCTOR_FORWARD_OUTSIDE_CONSTRUCTOR, "Can only forward constructors inside constructors");
+ }
+
+ public static CompileError constructorForwardMustBeFirstStatement() {
+ return new CompileError(CompileExceptionCode.CONSTRUCTOR_FORWARD_NOT_FIRST_STATEMENT, "Constructor forward must be first statement in the constructor");
+ }
+
+ public static CompileError enumConstantNotYetInitialized(String name) {
+ return new CompileError(CompileExceptionCode.ENUM_CONSTANT_NOT_YET_INITIALIZED, "Using an enum constant that is not yet initialized: " + name);
+ }
+
+ public static CompileError fieldNotYetInitialized(String name) {
+ return new CompileError(CompileExceptionCode.FIELD_NOT_YET_INITIALIZED, "Field " + name + " is not yet initialized");
+ }
+
+ public static CompileError localVariableNotYetInitialized(String name) {
+ return new CompileError(CompileExceptionCode.LOCAL_VARIABLE_NOT_YET_INITIALIZED, "Local variable not yet initialized: " + name);
+ }
+
+ public static CompileError localVariableTypeUnknown(String name) {
+ return new CompileError(CompileExceptionCode.LOCAL_VARIABLE_TYPE_UNKNOWN, "Could not determine type of local variable " + name);
+ }
+
+ public static CompileError invalidMatchingVariantField(int index) {
+ return new CompileError(CompileExceptionCode.INVALID_MATCHING_VARIANT_FIELD, "Invalid matching field field (" + index + ")");
+ }
+
+ public static CompileError duplicateDefaultMatchCase() {
+ return new CompileError(CompileExceptionCode.DUPLICATE_DEFAULT_MATCH_CASE, "Duplicate default in match");
+ }
+
+ public static CompileError duplicateMatchCase(String name) {
+ return new CompileError(CompileExceptionCode.DUPLICATE_MATCH_CASE, "Duplicate case in match: " + name);
+ }
+
+ public static CompileError invalidVariantMatchCase() {
+ return new CompileError(CompileExceptionCode.INVALID_MATCH_CASE, "Invalid match case: must be a variant option or default");
+ }
+
+ public static CompileError invalidEnumMatchCase() {
+ return new CompileError(CompileExceptionCode.INVALID_MATCH_CASE, "Invalid match case: must be a enum constant or default");
+ }
+
+ public static CompileError incompleteMatch(List missingOptions) {
+ return new CompileError(
+ CompileExceptionCode.INCOMPLETE_MATCH,
+ "Incomplete match: missing cases " + String.join(", ", missingOptions));
+ }
+
+ public static CompileError incompleteMatchBecauseDefaultRequired() {
+ return new CompileError(CompileExceptionCode.INCOMPLETE_MATCH, "Incomplete match: must have a default option");
+ }
+
+ public static CompileError panicArgumentMustBeString() {
+ return new CompileError(CompileExceptionCode.PANIC_ARGUMENT_NO_STRING, "Panic argument must be a string");
+ }
+
+ public static CompileError cannotSetFinalField(String name) {
+ return new CompileError(CompileExceptionCode.CANNOT_SET_FINAL_FIELD, "Cannot update field " + name + " since it is final");
+ }
+
+ public static CompileError typeMismatch(TypeID expected, TypeID actual) {
+ return new CompileError(CompileExceptionCode.TYPE_MISMATCH, "Provided a " + actual + " where a " + expected + " was expected");
+ }
+
+ public static CompileError cannotSetFinalVariable(String name) {
+ return new CompileError(CompileExceptionCode.CANNOT_SET_FINAL_VARIABLE, "Cannot update " + name + " since it is a final variable");
+ }
+
+ public static CompileError invalidCallArgument(String message) {
+ return new CompileError(CompileExceptionCode.INVALID_CALL_ARGUMENT, message);
+ }
+
+ public static CompileError noAccess(String message) {
+ return new CompileError(CompileExceptionCode.NO_ACCESS, message);
+ }
+
+ public static CompileError memberMustBeStatic() {
+ return new CompileError(CompileExceptionCode.MEMBER_NOT_STATIC, "Static member expected");
+ }
+
+ public static CompileError memberMustNotBeStatic() {
+ return new CompileError(CompileExceptionCode.MEMBER_IS_STATIC, "Non-static member expected");
+ }
+
+ public static CompileError returnValueInVoidFunction() {
+ return new CompileError(CompileExceptionCode.RETURN_VALUE_VOID, "Return type is void; cannot return a value");
+ }
+
+ public static CompileError missingReturn() {
+ return new CompileError(CompileExceptionCode.MISSING_RETURN, "Missing return");
+ }
+
+ public static CompileError notAllBranchesReturn() {
+ return new CompileError(CompileExceptionCode.MISSING_RETURN, "Not all branches return a value");
+ }
+
+ public static CompileError missingHeaderReturnType(){
+ return new CompileError(CompileExceptionCode.MISSING_RETURN_TYPE_IN_HEADER, "Missing return type in function header");
+ }
+
+ public static CompileError missingReturnValue() {
+ return new CompileError(CompileExceptionCode.MISSING_RETURN_VALUE, "Missing return value");
+ }
+
+ public static CompileError tryCatchResourceWithoutInitializer() {
+ return new CompileError(CompileExceptionCode.TRY_CATCH_RESOURCE_REQUIRES_INITIALIZER, "try with resource requires initializer");
+ }
+
+ public static CompileError invalidSuperclass(TypeID type) {
+ return new CompileError(CompileExceptionCode.INVALID_SUPERCLASS, type + " is not a valid superclass");
+ }
+
+ public static CompileError superclassNotVirtual(TypeID type) {
+ return new CompileError(CompileExceptionCode.INVALID_SUPERCLASS, "Cannot use " + type + " as superclass since it is not virtual");
+ }
+
+ public static CompileError typeNotDetermined(String display) {
+ return new CompileError(CompileExceptionCode.TYPE_NOT_INFERRED, display + " could not be inferred");
+ }
+
+ public static CompileError invalidArrayDimension(int dimension) {
+ return new CompileError(CompileExceptionCode.INVALID_TYPE, "Invalid array dimension: " + dimension);
+ }
+
+ public static CompileError invalidOverride(String message) {
+ return new CompileError(CompileExceptionCode.INVALID_OVERRIDE, message);
+ }
+
+ public static CompileError invalidIdentifier(String identifier) {
+ return new CompileError(CompileExceptionCode.INVALID_IDENTIFIER, "Invalid identifier: " + identifier);
+ }
+
+ public static CompileError duplicateParameterName(String name) {
+ return new CompileError(CompileExceptionCode.DUPLICATE_PARAMETER_NAME, "Duplicate parameter name: " + name);
+ }
+
+ public static CompileError variadicParameterMustBeLast() {
+ return new CompileError(CompileExceptionCode.VARIADIC_PARAMETER_MUST_BE_LAST, "variadic parameter must be the last parameter");
+ }
+
+ public static CompileError variadicParameterMustBeArray() {
+ return new CompileError(CompileExceptionCode.VARIADIC_PARAMETER_MUST_BE_ARRAY, "variadic parameter must be an array");
+ }
+
+ public static CompileError invalidModifier(String message) {
+ return new CompileError(CompileExceptionCode.INVALID_MODIFIER, message);
+ }
+
+ public static CompileError invalidNumberOfTypeArguments(int expectedTypeArguments, int actualTypeArguments) {
+ return new CompileError(CompileExceptionCode.TYPE_ARGUMENTS_INVALID_NUMBER, "Invalid number of type arguments: "
+ + actualTypeArguments
+ + " arguments given but "
+ + expectedTypeArguments
+ + " expected");
+ }
+
+ public static CompileError parseError(String message) {
+ return new CompileError(CompileExceptionCode.PARSE_ERROR, message);
+ }
+
+ public static CompileError invalidModificationTarget() {
+ return new CompileError(CompileExceptionCode.INVALID_MODIFICATION_TARGET, "Invalid target for increment or decrement operators");
+ }
+
+ public static CompileError invalidPropertyGetter(TypeID type, String name) {
+ return new CompileError(CompileExceptionCode.INVALID_PROPERTY_GETTER, "Invalid getter for property " + name + " in type " + type);
+ }
+
+ public static CompileError invalidPropertySetter(TypeID type, String name) {
+ return new CompileError(CompileExceptionCode.INVALID_PROPERTY_SETTER, "Invalid setter for property " + name + " in type " + type);
+ }
+
+ public static CompileError invalidPropertyPair(TypeID type, String name) {
+ return new CompileError(CompileExceptionCode.INVALID_PROPERTY_PAIR, "Setter and getter of property " + name + " in type " + type + " have different types");
+ }
+
+ public static CompileError invalidLambdaHeader(FunctionHeader header) {
+ return new CompileError(CompileExceptionCode.LAMBDA_HEADER_INVALID, "Invalid lambda header " + header);
+ }
+
+ public static CompileError unreachableStatement() {
+ return new CompileError(CompileExceptionCode.UNREACHABLE_STATEMENT, "Unreachable statement");
+ }
+
+ public static CompileError definitionNotAllowedHere(String text) {
+ return new CompileError(CompileExceptionCode.DEFINITION_NOT_ALLOWED_HERE, text);
+ }
+
+ public static CompileError incompleteImplementation(List unimplementedMembers) {
+
+ String text;
+ if(unimplementedMembers.size() == 1) {
+ text = unimplementedMembers.get(0).toString() + " is not implemented";
+ } else {
+ text = unimplementedMembers.stream()
+ .map(MethodSymbol::toString)
+ .collect(Collectors.joining("\n - ", "Implementation incomplete: " + unimplementedMembers.size() + " members not yet implemented:\n", ""));
+ }
+
+ return new CompileError(CompileExceptionCode.INCOMPLETE_IMPLEMENTATION, text);
+ }
+
+ public static CompileError noMemberInPackage(String fullName, String name) {
+ return new CompileError(CompileExceptionCode.NO_SUCH_MEMBER, "No member " + name + " in package " + fullName);
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingCallable.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingCallable.java
new file mode 100644
index 000000000..bde93b86e
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingCallable.java
@@ -0,0 +1,10 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zenscript.codemodel.expression.Expression;
+
+public interface CompilingCallable {
+ Expression call(CodePosition position, CompilingExpression[] arguments);
+
+ CastedExpression casted(CodePosition position, CastedEval cast, CompilingExpression[] arguments);
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingDefinition.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingDefinition.java
new file mode 100644
index 000000000..c75c38299
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingDefinition.java
@@ -0,0 +1,33 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CompileException;
+import org.openzen.zenscript.codemodel.HighLevelDefinition;
+import org.openzen.zenscript.codemodel.context.CompilingPackage;
+import org.openzen.zenscript.codemodel.identifiers.TypeSymbol;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+public interface CompilingDefinition {
+ CompilingPackage getPackage();
+
+ String getName();
+
+ HighLevelDefinition getDefinition();
+
+ boolean isInner();
+
+ void linkTypes();
+
+ Set getDependencies();
+
+ // prepareMembers will register all definition members to their
+ // respective definitions, such as fields, constructors, methods...
+ // It doesn't yet compile the method contents.
+ void prepareMembers(List errors);
+
+ void compileMembers(List errors);
+
+ Optional getInner(String name);
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingExpansion.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingExpansion.java
new file mode 100644
index 000000000..716cecd26
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingExpansion.java
@@ -0,0 +1,19 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CompileException;
+import org.openzen.zenscript.codemodel.definition.ExpansionDefinition;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.List;
+
+public interface CompilingExpansion {
+ ExpansionDefinition getCompiling();
+
+ void linkTypes();
+
+ TypeID getTarget();
+
+ void prepareMembers(List errors);
+
+ void compileMembers(List errors);
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingExpression.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingExpression.java
new file mode 100644
index 000000000..7039b69bc
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingExpression.java
@@ -0,0 +1,95 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zenscript.codemodel.GenericName;
+import org.openzen.zenscript.codemodel.expression.Expression;
+import org.openzen.zenscript.codemodel.expression.ModificationExpression;
+import org.openzen.zenscript.codemodel.expression.modifiable.ModifiableExpression;
+import org.openzen.zenscript.codemodel.ssa.CodeBlockStatement;
+import org.openzen.zenscript.codemodel.ssa.SSAVariableCollector;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.Optional;
+
+public interface CompilingExpression {
+ CompilingExpression[] NONE = new CompilingExpression[0];
+
+ /**
+ * Compiles this expression. The return type is inferred from the expression.
+ *
+ * @return compiled expression
+ */
+ Expression eval();
+
+ /**
+ * Casts this expression to the given type, if possible.
+ *
+ * @param cast operation
+ * @return expression to be compiled
+ */
+ CastedExpression cast(CastedEval cast);
+
+ /**
+ * Checks if this expression can be compiled to be of the given type. Either because it's the correct kind
+ * of constant or because there was an implicit constructor.
+ *
+ * @param type type to check for
+ * @return
+ */
+ boolean canConstructAs(TypeID type);
+
+ /**
+ * Attempts to make this expression callable.
+ *
+ * @return callable
+ */
+ Optional call();
+
+ default Optional asModifiable() {
+ return Optional.empty();
+ }
+
+ /**
+ * Finds a member from this expression.
+ * Returns an invalid expression if none could be found.
+ *
+ * @param position current position
+ * @param name member name
+ * @return member
+ */
+ CompilingExpression getMember(CodePosition position, GenericName name);
+
+ /**
+ * Compiles this expression as an lvalue with an assignment.
+ *
+ * @param value assigned value
+ * @return compiled expression
+ */
+ CompilingExpression assign(CompilingExpression value);
+
+ /**
+ * Compiles this expression to the given type. Attempts an implicit cast.
+ *
+ * @param type target type
+ * @return compiled expression
+ */
+ Expression as(TypeID type);
+
+ /**
+ * Collects all usages and assignments of variables for SSA analysis.
+ *
+ * @param collector variable collector
+ */
+ void collect(SSAVariableCollector collector);
+
+ void linkVariables(CodeBlockStatement.VariableLinker linker);
+
+ /**
+ * Compiles this expression as an identifier. (implemented on string literals and identifiers)
+ *
+ * @return this expression, as identifier
+ */
+ default Optional asStringKey() {
+ return Optional.empty();
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingMember.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingMember.java
new file mode 100644
index 000000000..08c827fa0
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingMember.java
@@ -0,0 +1,40 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CompileException;
+import org.openzen.zenscript.codemodel.identifiers.TypeSymbol;
+import org.openzen.zenscript.codemodel.member.IDefinitionMember;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+public interface CompilingMember {
+ void linkTypes();
+
+ /**
+ * Retrieves the compiled definition member. Only available after invocation of linkTypes.
+ *
+ * @return compiled member
+ */
+ IDefinitionMember getCompiled();
+
+ void prepare(List errors);
+
+ void compile(List errors);
+
+ /**
+ * Finds all dependencies that affect compilation order. Circular dependencies are not allowed!
+ *
+ * Used by interface implementations.
+ */
+ default void listCompilationOrderDependencies(Set result) {}
+
+ /**
+ * If this member is an inner definition, returns the compiling definition; otherwise, returns empty.
+ *
+ * @return inner definition of this member, if any
+ */
+ default Optional asInner() {
+ return Optional.empty();
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingSwitchValue.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingSwitchValue.java
new file mode 100644
index 000000000..5cda96482
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingSwitchValue.java
@@ -0,0 +1,15 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.expression.switchvalue.SwitchValue;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.Collections;
+import java.util.List;
+
+public interface CompilingSwitchValue {
+ SwitchValue as(TypeID type);
+
+ default List getBindings() {
+ return Collections.emptyList();
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingVariable.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingVariable.java
new file mode 100644
index 000000000..c71cc4ed6
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/CompilingVariable.java
@@ -0,0 +1,40 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.VariableDefinition;
+import org.openzen.zenscript.codemodel.compilation.expression.SSACompilingVariable;
+import org.openzen.zenscript.codemodel.statement.VariableID;
+import org.openzen.zenscript.codemodel.type.BasicTypeID;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+public class CompilingVariable {
+ public final VariableID id;
+ public final String name;
+ public final TypeID definedType; // may be null if the type is not yet known
+ public TypeID inferredType;
+ public final boolean isFinal;
+ public SSACompilingVariable ssaCompilingVariable;
+
+ public CompilingVariable(VariableID id, String name, TypeID type, boolean isFinal) {
+ this.id = id;
+ this.name = name;
+ this.definedType = type;
+ this.isFinal = isFinal;
+ }
+
+ public VariableDefinition eval() {
+ TypeID type = getActualType();
+ if (type == null)
+ throw new IllegalStateException("Variable type must be known");
+
+ return new VariableDefinition(id, name, type, isFinal, ssaCompilingVariable.as(type));
+ }
+
+ public VariableDefinition asType(TypeID type) {
+ TypeID actualType = getActualType();
+ return new VariableDefinition(id, name, actualType, isFinal, ssaCompilingVariable.as(actualType));
+ }
+
+ public TypeID getActualType() {
+ return definedType == null ? inferredType : definedType;
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/DefinitionCompiler.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/DefinitionCompiler.java
new file mode 100644
index 000000000..4ae641e99
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/DefinitionCompiler.java
@@ -0,0 +1,18 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.context.CompilingPackage;
+import org.openzen.zenscript.codemodel.identifiers.TypeSymbol;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+public interface DefinitionCompiler extends TypeResolver {
+ CompilingPackage getPackage();
+
+ TypeBuilder types();
+
+ MemberCompiler forMembers(TypeSymbol compiled);
+
+ MemberCompiler forExpansionMembers(TypeID extended, TypeSymbol expansion);
+
+ StatementCompiler forScripts(FunctionHeader scriptHeader);
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ExpressionBuilder.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ExpressionBuilder.java
new file mode 100644
index 000000000..bdbe8660c
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ExpressionBuilder.java
@@ -0,0 +1,105 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CompileError;
+import org.openzen.zenscript.codemodel.CompareType;
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.FunctionParameter;
+import org.openzen.zenscript.codemodel.VariableDefinition;
+import org.openzen.zenscript.codemodel.expression.*;
+import org.openzen.zenscript.codemodel.expression.modifiable.ModifiableExpression;
+import org.openzen.zenscript.codemodel.identifiers.instances.FieldInstance;
+import org.openzen.zenscript.codemodel.identifiers.instances.MethodInstance;
+import org.openzen.zenscript.codemodel.member.ref.ImplementationMemberInstance;
+import org.openzen.zenscript.codemodel.statement.Statement;
+import org.openzen.zenscript.codemodel.type.ArrayTypeID;
+import org.openzen.zenscript.codemodel.type.AssocTypeID;
+import org.openzen.zenscript.codemodel.type.GenericMapTypeID;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.List;
+
+public interface ExpressionBuilder {
+ Expression andAnd(Expression left, Expression right);
+
+ Expression callStatic(MethodInstance method, CallArguments arguments);
+
+ Expression callVirtual(MethodInstance method, Expression target, CallArguments arguments);
+
+ Expression callSuper(MethodInstance method, Expression target, CallArguments arguments);
+
+ Expression coalesce(Expression left, Expression right);
+
+ Expression compare(Expression left, CompilingExpression right, CompareType type);
+
+ Expression constant(boolean value);
+
+ Expression constant(String value);
+
+ Expression constant(float value);
+
+ Expression constant(double value);
+
+ Expression constant(int value);
+
+ Expression constantNull(TypeID type);
+
+ Expression constructorSuper(TypeID type, MethodInstance constructor, CallArguments arguments);
+
+ Expression constructorThis(TypeID type, MethodInstance constructor, CallArguments arguments);
+
+ Expression getThis(TypeID thisType);
+
+ Expression getInstanceField(Expression target, FieldInstance field);
+
+ Expression getFunctionParameter(FunctionParameter parameter);
+
+ Expression getLocalVariable(VariableDefinition variable);
+
+ Expression getStaticField(FieldInstance field);
+
+ Expression interfaceCast(ImplementationMemberInstance implementation, Expression value);
+
+ Expression invalid(CompileError error);
+
+ Expression invalid(CompileError error, TypeID type);
+
+ Expression is(Expression value, TypeID type);
+
+ Expression lambda(LambdaClosure closure, FunctionHeader header, Statement body);
+
+ Expression lambda(LambdaClosure closure, FunctionHeader header, FunctionHeader original, Statement body);
+
+ Expression newArray(ArrayTypeID type, Expression[] values);
+
+ Expression newAssoc(AssocTypeID type, List keys, List values);
+
+ Expression newGenericMap(GenericMapTypeID type);
+
+ Expression newRange(Expression from, Expression to);
+
+ Expression match(Expression value, TypeID resultingType, MatchExpression.Case[] cases);
+
+ Expression modification(ModifiableExpression target, MethodInstance operator, ModificationExpression.Modification modification);
+
+ Expression orOr(Expression left, Expression right);
+
+ Expression panic(TypeID type, Expression value);
+
+ Expression setFunctionParameter(FunctionParameter parameter, Expression value);
+
+ Expression setInstanceField(Expression target, FieldInstance field, Expression value);
+
+ Expression setLocalVariable(VariableDefinition variable, Expression value);
+
+ Expression setStaticField(FieldInstance field, Expression value);
+
+ Expression ternary(Expression condition, Expression ifThen, Expression ifElse);
+
+ Expression throw_(TypeID type, Expression value);
+
+ Expression tryConvert(Expression value, TypeID resultingType);
+
+ Expression tryRethrowAsException(Expression value, TypeID resultingType);
+
+ Expression tryRethrowAsResult(Expression value, TypeID resultingType);
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ExpressionCompiler.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ExpressionCompiler.java
new file mode 100644
index 000000000..b1d7398d3
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ExpressionCompiler.java
@@ -0,0 +1,47 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zencode.shared.CompileError;
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.GenericName;
+import org.openzen.zenscript.codemodel.compilation.impl.capture.LocalExpression;
+import org.openzen.zenscript.codemodel.expression.LambdaClosure;
+import org.openzen.zenscript.codemodel.identifiers.ExpansionSymbol;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.List;
+import java.util.Optional;
+
+public interface ExpressionCompiler extends TypeResolver {
+ ExpressionBuilder at(CodePosition position);
+
+ CompilingExpression invalid(CodePosition position, CompileError error);
+
+ Optional getThisType();
+
+ Optional getThis(CodePosition position);
+
+ Optional getLocalType();
+
+ Optional getThrowableType();
+
+ TypeBuilder types();
+
+ Optional resolve(CodePosition position, GenericName name);
+
+ Optional dollar();
+
+ List findCandidateImports(String name);
+
+ Optional union(TypeID left, TypeID right);
+
+ ExpressionCompiler withLocalVariables(List variables);
+
+ ExpressionCompiler withDollarTarget(CompilingExpression target);
+
+ ExpressionCompiler withDollar(CompilingExpression value);
+
+ StatementCompiler forLambda(LambdaClosure closure, FunctionHeader header);
+
+ List getAvailableExpansions();
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/InstanceCallable.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/InstanceCallable.java
new file mode 100644
index 000000000..5d2bac1a6
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/InstanceCallable.java
@@ -0,0 +1,119 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.compilation.impl.BoundInstanceCallable;
+import org.openzen.zenscript.codemodel.expression.CallArguments;
+import org.openzen.zenscript.codemodel.expression.Expression;
+import org.openzen.zenscript.codemodel.expression.ModificationExpression;
+import org.openzen.zenscript.codemodel.expression.modifiable.ModifiableExpression;
+import org.openzen.zenscript.codemodel.identifiers.instances.MethodInstance;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public final class InstanceCallable {
+ public final List overloads;
+
+ public InstanceCallable(List overloads) {
+ this.overloads = overloads;
+ }
+
+ public InstanceCallable(InstanceCallableMethod method) {
+ this.overloads = Collections.singletonList(method);
+ }
+
+ public InstanceCallable union(InstanceCallable other) {
+ List concatenated = Stream.concat(overloads.stream(), other.overloads.stream()).collect(Collectors.toList());
+ return new InstanceCallable(concatenated);
+ }
+
+ /**
+ * Merges the given callable into this one; skipping any overloads that are already present.
+ *
+ * @param other
+ * @return
+ */
+ public InstanceCallable merge(InstanceCallable other) {
+ List overloads = new ArrayList<>(this.overloads);
+ outer: for (InstanceCallableMethod overload : other.overloads) {
+ for (InstanceCallableMethod existing : this.overloads) {
+ if (overload.getHeader().isEquivalentTo(existing.getHeader()))
+ continue outer;
+ }
+
+ overloads.add(overload);
+ }
+ return new InstanceCallable(overloads);
+ }
+
+ public Expression call(ExpressionCompiler compiler, CodePosition position, Expression instance, TypeID[] typeArguments, CompilingExpression... arguments) {
+ MatchedCallArguments matched = MatchedCallArguments.match(compiler, position, overloads, null, typeArguments, arguments);
+ Expression finalInstance = applyWideningIfNecessary(compiler, position, instance, matched);
+ return matched.eval(compiler.at(position), (buildr, method, args) -> method.call(buildr, finalInstance, args));
+ }
+
+ public CastedExpression cast(ExpressionCompiler compiler, CodePosition position, CastedEval cast, Expression instance, TypeID[] typeArguments, CompilingExpression... arguments) {
+ MatchedCallArguments matched = MatchedCallArguments.match(compiler, position, overloads, cast.type, typeArguments, arguments);
+ Expression finalInstance = applyWideningIfNecessary(compiler, position, instance, matched);
+ return matched.cast(compiler.at(position), cast, (buildr, method, args) -> method.call(buildr, finalInstance, args));
+ }
+
+ private static Expression applyWideningIfNecessary(ExpressionCompiler compiler, CodePosition position, Expression instance, MatchedCallArguments matched) {
+ if (matched.requiresWidenedInstance(instance.type)) {
+ Expression originalInstance = instance;
+ instance = compiler.resolve(instance.type).findCaster(matched.getWidenedInstanceType())
+ .map(caster -> caster.call(compiler.at(position), originalInstance, CallArguments.EMPTY))
+ .orElseThrow(() -> new IllegalStateException("No widening conversion found for " + originalInstance.type + " to " + matched.getWidenedInstanceType()));
+ }
+ return instance;
+ }
+
+ public Expression callModification(ExpressionBuilder builder, ModifiableExpression instance, ModificationExpression.Modification modification) {
+ if (overloads.size() != 1) {
+ return builder.invalid(CompileErrors.invalidPostfix());
+ } else {
+ return overloads.get(0).callModification(builder, instance, modification);
+ }
+ }
+
+ public CompilingCallable bind(ExpressionCompiler compiler, Expression instance, TypeID[] typeArguments) {
+ return new BoundInstanceCallable(compiler, this, instance, typeArguments);
+ }
+
+ /**
+ * Finds the method that is being overridden. If this callable cannot be overridden (eg. it's not a method) or
+ * doesn't match the given header, returns empty.
+ *
+ * The provided header may or may not have types defined on its parameters.
+ *
+ * @param header header as defined in the overriding method
+ * @return
+ */
+ public Optional findOverriddenMethod(TypeResolver resolver, FunctionHeader header) {
+ for (InstanceCallableMethod overload : overloads) {
+ if (!header.canOverride(resolver, overload.getHeader()))
+ continue;
+
+ Optional method = overload.asMethod();
+ if (!method.isPresent())
+ continue;
+
+ return method;
+ }
+
+ return Optional.empty();
+ }
+
+ public Optional asSingleMethod() {
+ if (overloads.size() != 1)
+ return Optional.empty();
+
+ return overloads.get(0).asMethod();
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/InstanceCallableMethod.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/InstanceCallableMethod.java
new file mode 100644
index 000000000..153b6b30c
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/InstanceCallableMethod.java
@@ -0,0 +1,17 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.Modifiers;
+import org.openzen.zenscript.codemodel.expression.CallArguments;
+import org.openzen.zenscript.codemodel.expression.Expression;
+import org.openzen.zenscript.codemodel.expression.ModificationExpression;
+import org.openzen.zenscript.codemodel.expression.modifiable.ModifiableExpression;
+
+public interface InstanceCallableMethod extends AnyMethod {
+ Modifiers getModifiers();
+
+ Expression call(ExpressionBuilder builder, Expression instance, CallArguments arguments);
+
+ default Expression callModification(ExpressionBuilder builder, ModifiableExpression instance, ModificationExpression.Modification modification) {
+ return builder.invalid(CompileErrors.invalidPostfix());
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/LocalType.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/LocalType.java
new file mode 100644
index 000000000..b64531e53
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/LocalType.java
@@ -0,0 +1,15 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.Optional;
+
+public interface LocalType {
+ TypeID getThisType();
+
+ Optional getSuperType();
+
+ StaticCallable thisCall();
+
+ Optional superCall();
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/MatchedCallArguments.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/MatchedCallArguments.java
new file mode 100644
index 000000000..d8116641b
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/MatchedCallArguments.java
@@ -0,0 +1,377 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zencode.shared.CompileError;
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.GenericMapper;
+import org.openzen.zenscript.codemodel.compilation.expression.WrappedCompilingExpression;
+import org.openzen.zenscript.codemodel.expression.ArrayExpression;
+import org.openzen.zenscript.codemodel.expression.CallArguments;
+import org.openzen.zenscript.codemodel.expression.Expression;
+import org.openzen.zenscript.codemodel.generic.TypeParameter;
+import org.openzen.zenscript.codemodel.identifiers.ExpansionSymbol;
+import org.openzen.zenscript.codemodel.identifiers.instances.MethodInstance;
+import org.openzen.zenscript.codemodel.type.BasicTypeID;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+public class MatchedCallArguments {
+
+ private static final CastedExpression.Level[] candidateLevelsInOrderOfPriority = {CastedExpression.Level.EXACT, CastedExpression.Level.WIDENING, CastedExpression.Level.IMPLICIT};
+
+ public static MatchedCallArguments match(
+ ExpressionCompiler compiler,
+ CodePosition position,
+ List overloads,
+ TypeID asType,
+ TypeID[] typeArguments,
+ CompilingExpression... arguments
+ ) {
+ final Map>> methodsGroupedByMatchLevel = overloads.stream()
+ .map(method -> match(compiler, position, method, asType, typeArguments, arguments))
+ .collect(Collectors.groupingBy(matched -> matched.arguments.level, Collectors.toList()));
+
+ for (final CastedExpression.Level level : candidateLevelsInOrderOfPriority) {
+ final List> matchingMethods = methodsGroupedByMatchLevel.getOrDefault(level, Collections.emptyList());
+
+ switch (matchingMethods.size()) {
+ case 0:
+ continue;
+ case 1:
+ return matchingMethods.get(0);
+ default:
+ return ambiguousCall(methodsGroupedByMatchLevel);
+ }
+ }
+
+ return methodsGroupedByMatchLevel.getOrDefault(CastedExpression.Level.INVALID, Collections.emptyList()).stream()
+ .findFirst()
+ .orElseGet(() -> {
+ List headers = overloads.stream().map(AnyMethod::getHeader).collect(Collectors.toList());
+ List types = Arrays.stream(arguments).map(CompilingExpression::eval).map(it -> it.type).collect(Collectors.toList());
+ return new MatchedCallArguments<>(CompileErrors.noMethodMatched(headers, types));
+ });
+ }
+
+ private static MatchedCallArguments ambiguousCall(Map>> methodsGroupedByMatchLevel) {
+ List candidates = Arrays.stream(candidateLevelsInOrderOfPriority)
+ .flatMap(level -> methodsGroupedByMatchLevel.getOrDefault(level, Collections.emptyList()).stream())
+ .map(pair -> pair.method.getHeader())
+ .collect(Collectors.toList());
+
+ return new MatchedCallArguments<>(CompileErrors.ambiguousCall(candidates));
+ }
+
+ private final T method;
+ private final CallArguments arguments;
+ private final CompileError error;
+
+ private MatchedCallArguments(T method, CallArguments arguments) {
+ this.method = method;
+ this.arguments = arguments;
+ this.error = null;
+ }
+
+ private MatchedCallArguments(CompileError error) {
+ this.method = null;
+ this.arguments = null;
+ this.error = error;
+ }
+
+ private MatchedCallArguments(CompileError error, CallArguments arguments) {
+ this.method = null;
+ this.arguments = arguments;
+ this.error = error;
+ }
+
+ public boolean requiresWidenedInstance(TypeID instanceType) {
+ return method != null && method.hasWideningConversions() && method.asMethod().map(method -> !method.getTarget().equals(instanceType)).orElse(false);
+ }
+
+ public TypeID getWidenedInstanceType() {
+ return method.asMethod().map(MethodInstance::getTarget).orElse(null);
+ }
+
+ public Expression eval(ExpressionBuilder builder, CallEvaluator evaluator) {
+ if (this.error != null) {
+ return builder.invalid(error);
+ } else {
+ return evaluator.eval(builder, method, arguments);
+ }
+ }
+
+ public CastedExpression cast(ExpressionBuilder builder, CastedEval eval, CallEvaluator evaluator) {
+ if (this.error != null) {
+ return CastedExpression.invalid(builder.invalid(error), error);
+ } else {
+ return eval.of(evaluator.eval(builder, method, arguments));
+ }
+ }
+
+ public Optional getArguments() {
+ return Optional.ofNullable(arguments);
+ }
+
+ public Optional getError() {
+ return Optional.ofNullable(error);
+ }
+
+ @FunctionalInterface
+ public interface CallEvaluator {
+ Expression eval(ExpressionBuilder builder, T method, CallArguments arguments);
+ }
+
+ private static MatchedCallArguments match(
+ ExpressionCompiler compiler,
+ CodePosition position,
+ T method,
+ TypeID result,
+ TypeID[] typeArguments,
+ CompilingExpression... arguments
+ ) {
+ TypeID[] expansionTypeArguments = method.asMethod().map(MethodInstance::getExpansionTypeArguments).orElse(TypeID.NONE);
+
+ if (!method.getHeader().accepts(arguments.length)) {
+ return new MatchedCallArguments<>(method, new CallArguments(
+ CastedExpression.Level.INVALID,
+ expansionTypeArguments,
+ typeArguments,
+ Expression.NONE));
+ }
+
+ // Type inference
+ Optional inferred = inferTypeArguments(expansionTypeArguments, method, result, typeArguments, compiler.getAvailableExpansions(), arguments);
+ if (!inferred.isPresent()) {
+ return new MatchedCallArguments<>(
+ method,
+ new CallArguments(CastedExpression.Level.INVALID, TypeID.NONE, typeArguments, Expression.NONE));
+ }
+
+ typeArguments = inferred.get();
+
+ GenericMapper mapper = GenericMapper.create(method.getHeader().typeParameters, typeArguments);
+ @SuppressWarnings("unchecked")
+ T instancedMethod = (T) method.withGenericArguments(mapper);
+
+ Optional> matchedVarArg = matchVarArg(expansionTypeArguments, compiler, position, method, instancedMethod, typeArguments, arguments);
+
+ MatchedCallArguments matchedWidening;
+ {
+ MatchedCallArguments matchedNormal = matchNormal(expansionTypeArguments, compiler, position, method, instancedMethod, typeArguments, arguments);
+ matchedWidening = applyWidening(matchedNormal, expansionTypeArguments, compiler, position, method, instancedMethod, typeArguments);
+ }
+
+ if (!matchedVarArg.isPresent()) {
+ return matchedWidening;
+ } else {
+ return Stream.of(matchedWidening, matchedVarArg.get()).min(Comparator.comparing(match -> match.arguments.level)).orElseThrow(() -> new IllegalStateException("Should never happen"));
+ }
+ }
+
+ private static MatchedCallArguments applyWidening(
+ MatchedCallArguments matchedNormal,
+ TypeID[] expansionTypeArguments,
+ ExpressionCompiler compiler,
+ CodePosition position,
+ T method,
+ T instancedMethod,
+ TypeID[] typeArguments
+ ) {
+ FunctionHeader header = instancedMethod.getHeader();
+
+ if (matchedNormal.arguments.level != CastedExpression.Level.EXACT || !method.hasWideningConversions()) {
+ return matchedNormal;
+ }
+
+ FunctionHeader originalHeader = method.asMethod().map(instance -> instance.method.getHeader()).orElse(header);
+
+ Expression[] expressions = IntStream.range(0, matchedNormal.arguments.arguments.length)
+ .mapToObj(i -> {
+ final Expression value = matchedNormal.arguments.arguments[i];
+
+ final TypeID originalParameterType = originalHeader.getParameterType(false, i);
+ if (value.type.equals(originalParameterType)) {
+ return value;
+ }
+
+ return compiler.resolve(value.type).findCaster(originalHeader.parameters[i].type)
+ .map(caster -> caster.call(compiler.at(position), value, CallArguments.EMPTY))
+ .orElse(value);
+ }).toArray(Expression[]::new);
+
+ if (Stream.of(expressions).anyMatch(e -> e.type.isInvalid())) {
+ return new MatchedCallArguments<>(
+ method,
+ new CallArguments(CastedExpression.Level.INVALID, expansionTypeArguments, typeArguments, expressions)
+ );
+ }
+
+ return new MatchedCallArguments<>(
+ method,
+ new CallArguments(CastedExpression.Level.WIDENING, expansionTypeArguments, typeArguments, expressions)
+ );
+ }
+
+ private static MatchedCallArguments matchNormal(
+ TypeID[] expansionTypeArguments,
+ ExpressionCompiler compiler,
+ CodePosition position,
+ T method,
+ T instancedMethod,
+ TypeID[] typeArguments,
+ CompilingExpression[] arguments
+ ) {
+ FunctionHeader header = instancedMethod.getHeader();
+
+ // skip vararg calls here (handled in matchVarArg)
+ if (arguments.length > header.parameters.length) {
+ return new MatchedCallArguments<>(
+ method,
+ new CallArguments(CastedExpression.Level.INVALID, expansionTypeArguments, typeArguments, Expression.NONE));
+ }
+
+ CastedExpression[] providedArguments = IntStream.range(0, header.parameters.length)
+ .mapToObj(i -> {
+ CompilingExpression argument;
+ if (i < arguments.length) {
+ // parameter provided
+ argument = arguments[i];
+ } else if (header.getParameter(false, i).defaultValue != null) {
+ // default value
+ argument = new WrappedCompilingExpression(compiler, header.getParameter(false, i).defaultValue);
+ } else {
+ // invalid
+ return CastedExpression.invalid(position, CompileErrors.missingParameter(header.getParameter(false, i).name));
+ }
+ TypeID originalType = method.getHeader().getParameterType(false, i);
+ return argument.cast(CastedEval.implicit(compiler, position, header.getParameterType(false, i), originalType));
+ })
+ .toArray(CastedExpression[]::new);
+
+ CastedExpression.Level level = Stream.of(providedArguments)
+ .map(e -> e.level)
+ .max(Comparator.naturalOrder())
+ .orElse(CastedExpression.Level.EXACT);
+
+ if (level == CastedExpression.Level.INVALID) {
+ CastedExpression firstInvalid = Stream.of(providedArguments)
+ .filter(e -> e.level == CastedExpression.Level.INVALID)
+ .findFirst()
+ .orElseThrow(() -> new IllegalStateException("Should never happen"));
+
+ return new MatchedCallArguments<>(firstInvalid.error,
+ new CallArguments(CastedExpression.Level.INVALID, expansionTypeArguments, typeArguments, Expression.NONE));
+ }
+
+ return new MatchedCallArguments<>(
+ instancedMethod,
+ new CallArguments(level, expansionTypeArguments, typeArguments, Stream.of(providedArguments).map(casted -> casted.value).toArray(Expression[]::new))
+ );
+ }
+
+ private static Optional> matchVarArg(
+ TypeID[] expansionTypeArguments,
+ ExpressionCompiler compiler,
+ CodePosition position,
+ T method,
+ T instancedMethod,
+ TypeID[] typeArguments,
+ CompilingExpression[] arguments
+ ) {
+ FunctionHeader header = instancedMethod.getHeader();
+
+ // We only check vararg calls
+ // - more arguments than parameters provided
+ // - 0 vararg parameters provided (and variadic argument is NOT optional)
+ if (!header.isVariadic()
+ || (arguments.length < header.parameters.length - 1 && header.getVariadicParameter().map(p -> p.defaultValue).isPresent())
+ ) {
+ return Optional.empty();
+ }
+
+ CastedExpression[] castedExpressions = IntStream.range(0, arguments.length)
+ .mapToObj(i -> arguments[i].cast(CastedEval.implicit(
+ compiler,
+ position,
+ header.getParameterType(true, i),
+ method.getHeader().getParameterType(true, i)
+ )))
+ .toArray(CastedExpression[]::new);
+
+ Expression[] expressions = new Expression[header.parameters.length];
+ Expression[] varargExpressions = new Expression[arguments.length - (header.parameters.length - 1)];
+ IntStream.range(0, header.parameters.length - 1).forEach(i -> expressions[i] = castedExpressions[i].value);
+ IntStream.range(header.parameters.length - 1, arguments.length).forEach(i -> varargExpressions[i - (header.parameters.length - 1)] = castedExpressions[i].value);
+
+ CodePosition arrayPosition = Stream.of(varargExpressions).map(e -> e.position).reduce(CodePosition::merge).orElse(position);
+ expressions[header.parameters.length - 1] = new ArrayExpression(arrayPosition, varargExpressions, header.getVariadicParameterType().orElseThrow(IllegalStateException::new));
+
+ CastedExpression.Level level = Stream.of(castedExpressions)
+ .map(e -> e.level)
+ .max(Comparator.naturalOrder())
+ .orElse(CastedExpression.Level.EXACT);
+
+ return Optional.of(new MatchedCallArguments<>(
+ instancedMethod,
+ new CallArguments(level, expansionTypeArguments, typeArguments, expressions)
+ ));
+ }
+
+
+ private static Optional inferTypeArguments(
+ TypeID[] expansionTypeArguments,
+ T method,
+ TypeID result,
+ TypeID[] typeArguments,
+ List expansions,
+ CompilingExpression... arguments
+ ) {
+ int providedTypeArguments = typeArguments == null ? 0 : typeArguments.length;
+
+ if (providedTypeArguments == method.getHeader().typeParameters.length) {
+ return Optional.of(typeArguments != null ? typeArguments : TypeID.NONE);
+ }
+
+ if(providedTypeArguments != 0 && providedTypeArguments != method.getHeader().typeParameters.length) {
+ return Optional.empty();
+ }
+
+ // attempt to infer type arguments from the return type
+ final Map typeArgumentMap = new HashMap<>();
+ if (result != null) {
+ typeArgumentMap.putAll(method.getHeader().getReturnType().inferTypeParameters(result, expansions));
+ }
+
+ // create a mapping with everything found so far
+ // NOTE - this means that inference is sensitive to order of parameters
+ GenericMapper mapper = new GenericMapper(typeArgumentMap, expansionTypeArguments);
+
+ // now try to infer type arguments from the arguments
+ for (int i = 0; i < arguments.length; i++) {
+ CompilingExpression argument = arguments[i];
+ Expression evaluated = argument.eval();
+ if (evaluated.type != BasicTypeID.UNDETERMINED) {
+ TypeID parameterType = mapper.map(method.getHeader().parameters[i].type);
+ Map mapping = parameterType.inferTypeParameters(evaluated.type, expansions);
+ if (mapping != null)
+ typeArgumentMap.putAll(mapping);
+ }
+ }
+
+ TypeID[] typeArguments2 = Arrays.stream(method.getHeader().typeParameters)
+ .map(typeArgumentMap::get)
+ .toArray(TypeID[]::new);
+
+ boolean allTypesResolved = Arrays.stream(typeArguments2).noneMatch(Objects::isNull);
+ if (allTypesResolved) {
+ return Optional.of(typeArguments2);
+ }
+
+ // TODO: improve type inference
+ return Optional.empty();
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/MemberCompiler.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/MemberCompiler.java
new file mode 100644
index 000000000..ec0a4d7fb
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/MemberCompiler.java
@@ -0,0 +1,15 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.FunctionHeader;
+
+public interface MemberCompiler extends TypeResolver {
+ LocalType getThisType();
+
+ TypeBuilder types();
+
+ ExpressionCompiler forFieldInitializers();
+
+ StatementCompiler forMethod(FunctionHeader header);
+
+ DefinitionCompiler forInner();
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/MemoizedCompilingExpression.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/MemoizedCompilingExpression.java
new file mode 100644
index 000000000..f84026d63
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/MemoizedCompilingExpression.java
@@ -0,0 +1,39 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zenscript.codemodel.compilation.expression.AbstractCompilingExpression;
+import org.openzen.zenscript.codemodel.expression.Expression;
+import org.openzen.zenscript.codemodel.expression.MemoizedExpression;
+import org.openzen.zenscript.codemodel.ssa.CodeBlockStatement;
+import org.openzen.zenscript.codemodel.ssa.SSAVariableCollector;
+
+public class MemoizedCompilingExpression extends AbstractCompilingExpression {
+ private final CompilingExpression expression;
+ private MemoizedExpression result;
+
+ public MemoizedCompilingExpression(ExpressionCompiler compiler, CodePosition position, CompilingExpression expression) {
+ super(compiler, position);
+
+ this.expression = expression;
+ }
+
+ @Override
+ public Expression eval() {
+ if (result == null) {
+ result = new MemoizedExpression(expression.eval());
+ } else {
+ result.markAccessedMoreThanOnce();
+ }
+ return result;
+ }
+
+ @Override
+ public void collect(SSAVariableCollector collector) {
+ expression.collect(collector);
+ }
+
+ @Override
+ public void linkVariables(CodeBlockStatement.VariableLinker linker) {
+ expression.linkVariables(linker);
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ResolvedType.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ResolvedType.java
new file mode 100644
index 000000000..1de912a8a
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ResolvedType.java
@@ -0,0 +1,127 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zenscript.codemodel.CompareType;
+import org.openzen.zenscript.codemodel.OperatorType;
+import org.openzen.zenscript.codemodel.expression.CallArguments;
+import org.openzen.zenscript.codemodel.expression.Expression;
+import org.openzen.zenscript.codemodel.expression.switchvalue.SwitchValue;
+import org.openzen.zenscript.codemodel.identifiers.MethodSymbol;
+import org.openzen.zenscript.codemodel.identifiers.TypeSymbol;
+import org.openzen.zenscript.codemodel.identifiers.instances.IteratorInstance;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+
+public interface ResolvedType {
+ TypeID getType();
+
+ StaticCallable getConstructor();
+
+ Optional findImplicitConstructor();
+
+ Optional findSuffixConstructor(String suffix);
+
+ Optional findCaster(TypeID toType);
+
+ default Optional tryCastExplicit(TypeID target, ExpressionCompiler compiler, CodePosition position, Expression value, boolean optional) {
+ return findCaster(target)
+ .filter(caster -> !caster.getModifiers().isImplicit())
+ // TODO: remember the type arguments in the caster method instead, so we don't need to infer it again
+ .flatMap(caster -> MatchedCallArguments.match(compiler, position, Collections.singletonList(caster), target, TypeID.NONE)
+ .getArguments()
+ .map(arg -> caster.call(compiler.at(position), value, arg))
+ );
+ }
+
+ default Optional tryCastImplicit(TypeID target, ExpressionCompiler compiler, CodePosition position, Expression value, boolean optional) {
+ return findCaster(target)
+ .filter(caster -> caster.getModifiers().isImplicit())
+ // TODO: remember the type arguments in the caster method instead, so we don't need to infer it again
+ .flatMap(caster -> MatchedCallArguments.match(compiler, position, Collections.singletonList(caster), target, TypeID.NONE)
+ .getArguments()
+ .map(arg -> caster.call(compiler.at(position), value, arg))
+ );
+ }
+
+ default boolean canCastImplicitlyTo(TypeID target) {
+ return findCaster(target)
+ .filter(caster -> caster.getModifiers().isImplicit())
+ .isPresent();
+ }
+ Optional findStaticMethod(String name);
+
+ Optional findStaticGetter(String name);
+
+ Optional findStaticSetter(String name);
+
+ Optional findMethod(String name);
+
+ Optional findGetter(String name);
+
+ Optional findSetter(String name);
+
+ Optional findOperator(OperatorType operator);
+
+ Optional findField(String name);
+
+ Optional findInnerType(String name);
+
+ /**
+ * Finds a member that can be resolved directly in this context (eg. enum constant or variant option)
+ *
+ * @param name member name
+ * @return true if it's a resolved member
+ */
+ Optional getContextMember(String name);
+
+ Optional findSwitchMember(String name);
+
+ List comparators();
+
+ Optional findIterator(int variables);
+
+ Optional findStaticOperator(OperatorType operator);
+
+ List getInterfaceMethodsToImplement();
+
+ boolean extendsOrImplements(TypeID type);
+
+ interface SwitchMember {
+ SwitchValue toSwitchValue(List bindings);
+ }
+
+ interface Field {
+ TypeID getType();
+
+ boolean isStatic();
+
+ Expression get(ExpressionBuilder builder, Expression target);
+
+ Expression set(ExpressionBuilder builder, Expression target, Expression value);
+
+ Expression getStatic(ExpressionBuilder builder);
+
+ Expression setStatic(ExpressionBuilder builder, Expression value);
+ }
+
+ interface StaticField {
+ TypeID getType();
+
+ Expression get(ExpressionBuilder builder);
+
+ Expression set(ExpressionBuilder builder, Expression value);
+ }
+
+ @FunctionalInterface
+ interface Comparator {
+ CastedExpression compare(
+ ExpressionCompiler compiler,
+ CodePosition position,
+ Expression left,
+ CompilingExpression right,
+ CompareType type);
+ }
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ResolvingType.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ResolvingType.java
new file mode 100644
index 000000000..9c819eb47
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/ResolvingType.java
@@ -0,0 +1,12 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.identifiers.ExpansionSymbol;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.List;
+
+public interface ResolvingType {
+ TypeID getType();
+
+ ResolvedType withExpansions(List expansions);
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/StatementCompiler.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/StatementCompiler.java
new file mode 100644
index 000000000..affb740cd
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/StatementCompiler.java
@@ -0,0 +1,31 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.compilation.statement.CompilingLoopStatement;
+import org.openzen.zenscript.codemodel.expression.Expression;
+import org.openzen.zenscript.codemodel.statement.VarStatement;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.Optional;
+
+public interface StatementCompiler {
+ ExpressionCompiler expressions();
+
+ TypeBuilder types();
+
+ ResolvedType resolve(TypeID type);
+
+ StatementCompiler forBlock();
+
+ StatementCompiler forLoop(CompilingLoopStatement loop);
+
+ StatementCompiler forCatch(CompilingVariable exceptionVariable);
+
+ Optional getLoop(String name);
+
+ Optional getFunctionHeader();
+
+ Optional getThrownType();
+
+ void addLocalVariable(CompilingVariable variable);
+}
diff --git a/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/StaticCallable.java b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/StaticCallable.java
new file mode 100644
index 000000000..b124dd41f
--- /dev/null
+++ b/CodeModel/src/main/java/org/openzen/zenscript/codemodel/compilation/StaticCallable.java
@@ -0,0 +1,98 @@
+package org.openzen.zenscript.codemodel.compilation;
+
+import org.openzen.zencode.shared.CodePosition;
+import org.openzen.zenscript.codemodel.FunctionHeader;
+import org.openzen.zenscript.codemodel.compilation.impl.BoundStaticCallable;
+import org.openzen.zenscript.codemodel.expression.CallArguments;
+import org.openzen.zenscript.codemodel.expression.Expression;
+import org.openzen.zenscript.codemodel.type.TypeID;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public final class StaticCallable {
+ private final List overloads;
+
+ public StaticCallable(List overloads) {
+ this.overloads = overloads;
+ }
+
+ public StaticCallable(StaticCallableMethod method) {
+ this.overloads = Collections.singletonList(method);
+ }
+
+ public StaticCallable map(Function projection) {
+ return new StaticCallable(overloads.stream().map(projection).collect(Collectors.toList()));
+ }
+
+ public StaticCallable union(StaticCallable other) {
+ List concatenated = Stream.concat(overloads.stream(), other.overloads.stream()).collect(Collectors.toList());
+ return new StaticCallable(concatenated);
+ }
+
+ /**
+ * Merges the given callable into this one; skipping any overloads that are already present.
+ *
+ * @param other
+ * @return
+ */
+ public StaticCallable merge(StaticCallable other) {
+ List overloads = new ArrayList<>(this.overloads);
+ outer: for (StaticCallableMethod overload : other.overloads) {
+ for (StaticCallableMethod existing : this.overloads) {
+ if (overload.getHeader().isEquivalentTo(existing.getHeader()))
+ continue outer;
+ }
+
+ overloads.add(overload);
+ }
+ return new StaticCallable(overloads);
+ }
+
+ public boolean acceptsZeroArguments() {
+ for (StaticCallableMethod method : overloads) {
+ if (method.getHeader().accepts(0))
+ return true;
+ }
+ return false;
+ }
+
+ public Expression call(ExpressionCompiler compiler, CodePosition position, TypeID[] typeArguments, CompilingExpression... arguments) {
+ MatchedCallArguments matched = MatchedCallArguments.match(compiler, position, overloads, null, typeArguments, arguments);
+ return matched.eval(compiler.at(position), this::call);
+ }
+
+ public CastedExpression casted(ExpressionCompiler compiler, CodePosition position, CastedEval cast, TypeID[] typeArguments, CompilingExpression... arguments) {
+ MatchedCallArguments matched = MatchedCallArguments.match(compiler, position, overloads, cast.type, typeArguments, arguments);
+ return matched.cast(compiler.at(position), cast, this::call);
+ }
+
+ public MatchedCallArguments match(ExpressionCompiler compiler, CodePosition position, TypeID[] typeArguments, CompilingExpression... arguments) {
+ return MatchedCallArguments.match(compiler, position, overloads, null, typeArguments, arguments);
+ }
+
+ public MatchedCallArguments