Add this as a self type (#1708)
This commit is contained in:
1 parent
1208fa9438
commit
2b697015c7
305 files changed
+1487
-561
No files matched your search
@@ -57,6 +57,17 @@ public abstract class PType implements Serializable {
|
||||
}
|
||||
};
|
||||
|
||||
/** The {@code this} type. */
|
||||
public static final PType THIS =
|
||||
new PType() {
|
||||
@Serial private static final long serialVersionUID = 0L;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "this";
|
||||
}
|
||||
};
|
||||
|
||||
private PType() {}
|
||||
|
||||
public List<PType> getTypeArguments() {
|
||||
|
||||
@@ -131,6 +131,7 @@ import org.pkl.core.ast.expression.primary.GetMemberKeyNode;
|
||||
import org.pkl.core.ast.expression.primary.GetModuleNode;
|
||||
import org.pkl.core.ast.expression.primary.GetModuleOwnerNode;
|
||||
import org.pkl.core.ast.expression.primary.GetOwnerNode;
|
||||
import org.pkl.core.ast.expression.primary.GetReceiverClassNode;
|
||||
import org.pkl.core.ast.expression.primary.GetReceiverNode;
|
||||
import org.pkl.core.ast.expression.primary.GetTypeAliasModuleNode;
|
||||
import org.pkl.core.ast.expression.primary.OuterNode;
|
||||
@@ -208,6 +209,7 @@ import org.pkl.core.stdlib.registry.ExternalMemberRegistry;
|
||||
import org.pkl.core.stdlib.registry.MemberRegistryFactory;
|
||||
import org.pkl.core.util.CollectionUtils;
|
||||
import org.pkl.core.util.EconomicMaps;
|
||||
import org.pkl.core.util.ErrorMessages;
|
||||
import org.pkl.core.util.IoUtils;
|
||||
import org.pkl.core.util.Pair;
|
||||
import org.pkl.parser.Span;
|
||||
@@ -279,6 +281,7 @@ import org.pkl.parser.syntax.Type.NothingType;
|
||||
import org.pkl.parser.syntax.Type.NullableType;
|
||||
import org.pkl.parser.syntax.Type.ParenthesizedType;
|
||||
import org.pkl.parser.syntax.Type.StringConstantType;
|
||||
import org.pkl.parser.syntax.Type.ThisType;
|
||||
import org.pkl.parser.syntax.Type.UnionType;
|
||||
import org.pkl.parser.syntax.Type.UnknownType;
|
||||
import org.pkl.parser.syntax.TypeAlias;
|
||||
@@ -370,7 +373,105 @@ public class AstBuilder extends AbstractAstBuilder<Object> {
|
||||
|
||||
@Override
|
||||
public UnresolvedTypeNode visitModuleType(ModuleType type) {
|
||||
return new UnresolvedTypeNode.Module(createSourceSection(type));
|
||||
var sourceSection = createSourceSection(type);
|
||||
checkModuleType(type, sourceSection);
|
||||
return new UnresolvedTypeNode.Module(sourceSection);
|
||||
}
|
||||
|
||||
private void checkModuleType(ModuleType type, SourceSection sourceSection) {
|
||||
// `class X extends module` is fine
|
||||
if (type.parent() instanceof Class classNode && classNode.getSuperClass() == type) {
|
||||
return;
|
||||
}
|
||||
var currentScope = symbolTable.getCurrentScope();
|
||||
if (!currentScope.getConstLevel().isConst()) {
|
||||
return;
|
||||
}
|
||||
String errorMessage = null;
|
||||
// only classes/typealiases/annotations will apply "MODULE" const level
|
||||
if (currentScope.getConstLevel() == ConstLevel.MODULE) {
|
||||
for (var scope = currentScope; scope != null; scope = scope.getParent()) {
|
||||
if (scope.isAnnotationScope()) {
|
||||
errorMessage = ErrorMessages.create("invalidModuleTypeInAnnotation");
|
||||
break;
|
||||
} else if (scope.isClassScope()) {
|
||||
errorMessage = ErrorMessages.create("invalidModuleTypeInClass");
|
||||
break;
|
||||
} else if (scope.isTypeAliasScope()) {
|
||||
errorMessage = ErrorMessages.create("invalidModuleTypeInTypeAlias");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Only properties and methods will apply "ALL" const level
|
||||
else {
|
||||
for (var scope = currentScope; scope != null; scope = scope.getParent()) {
|
||||
if (scope.isPropertyScope() || scope.isMethodScope()) {
|
||||
var parentScope = scope.getParent();
|
||||
assert parentScope != null;
|
||||
// if the parent also has "ALL", we haven't found the originating const property/method
|
||||
// yet.
|
||||
if (parentScope.getConstLevel() == ConstLevel.ALL) {
|
||||
continue;
|
||||
}
|
||||
var message =
|
||||
scope.isPropertyScope() ? "invalidModuleTypeInProperty" : "invalidModuleTypeInMethod";
|
||||
errorMessage = ErrorMessages.create(message, scope.getQualifiedName());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert errorMessage != null;
|
||||
// TODO: when making this an error, update comment on moduleClass in ReferenceTypeNode.eval
|
||||
VmContext.get(null)
|
||||
.getLogger()
|
||||
.warn(
|
||||
errorMessage + " This will be an error in a future release.",
|
||||
VmUtils.createStackFrame(sourceSection, null));
|
||||
}
|
||||
|
||||
@Override
|
||||
public UnresolvedTypeNode visitThisType(ThisType type) {
|
||||
var sourceSection = createSourceSection(type);
|
||||
// need to pass explicit class name for property and method arg/return type annotations.
|
||||
// this is because type annotations on class properties/methods are initialized when the
|
||||
// ClassNode
|
||||
// is executed, and the frame's receiver is the enclosing module rather than the class.
|
||||
// do not need: when in any object or at the module level (where `this` is the receiver's class)
|
||||
org.pkl.core.runtime.Identifier className = null;
|
||||
for (var scope = symbolTable.getCurrentScope(); scope != null; scope = scope.getParent()) {
|
||||
if (scope.isObjectScope() || scope.isCustomThisScope()) {
|
||||
break;
|
||||
}
|
||||
if (scope instanceof ClassScope foundClassScope) {
|
||||
className = foundClassScope.getName();
|
||||
break;
|
||||
}
|
||||
// it's still safe to break on ObjectScope because this is valid:
|
||||
// typealias Foo = List(any((it) -> it == new Dynamic { it is this })) // this == Dynamic
|
||||
if (scope.isTypeAliasScope()) {
|
||||
throw exceptionBuilder()
|
||||
.withSourceSection(sourceSection)
|
||||
.evalError("invalidThisTypeInTypeAlias")
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
ExpressionNode getClassNode;
|
||||
if (isBaseModule && className != null) {
|
||||
getClassNode = new GetBaseModuleClassNode(className);
|
||||
} else if (className == null) {
|
||||
getClassNode = new GetReceiverClassNode(sourceSection);
|
||||
} else if (className.isLocalProp()) {
|
||||
getClassNode =
|
||||
new ReadQualifiedLocalPropertyNode(
|
||||
sourceSection, className, false, new GetModuleNode(sourceSection));
|
||||
} else {
|
||||
getClassNode =
|
||||
ReadPropertyNodeGen.create(
|
||||
sourceSection, className, false, new GetModuleNode(sourceSection));
|
||||
}
|
||||
return new UnresolvedTypeNode.This(sourceSection, getClassNode);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -410,6 +410,18 @@ public final class SymbolTable {
|
||||
return curr;
|
||||
}
|
||||
|
||||
public final boolean isAnnotationScope() {
|
||||
return this instanceof AnnotationScope;
|
||||
}
|
||||
|
||||
public final boolean isPropertyScope() {
|
||||
return this instanceof PropertyScope;
|
||||
}
|
||||
|
||||
public final boolean isMethodScope() {
|
||||
return this instanceof MethodScope;
|
||||
}
|
||||
|
||||
public final boolean isLetScope() {
|
||||
return this instanceof LetExpressionScope;
|
||||
}
|
||||
@@ -422,6 +434,10 @@ public final class SymbolTable {
|
||||
return this instanceof ClassScope;
|
||||
}
|
||||
|
||||
public final boolean isObjectScope() {
|
||||
return this instanceof ObjectScope;
|
||||
}
|
||||
|
||||
public final boolean isClassMemberScope() {
|
||||
var effectiveScope = skipLambdaAndLetScopes();
|
||||
var parent = effectiveScope.parent;
|
||||
@@ -454,6 +470,10 @@ public final class SymbolTable {
|
||||
return this instanceof ForGeneratorScope;
|
||||
}
|
||||
|
||||
public final boolean isTypeAliasScope() {
|
||||
return this instanceof TypeAliasScope;
|
||||
}
|
||||
|
||||
public ConstLevel getConstLevel() {
|
||||
return constLevel;
|
||||
}
|
||||
@@ -1010,7 +1030,6 @@ public final class SymbolTable {
|
||||
|
||||
@Override
|
||||
public @Nullable VariableResolution doResolveProperty(String name, int levelsUp) {
|
||||
|
||||
var member = properties.get(name);
|
||||
if (member == null) return null;
|
||||
return new LexicalProperty(false, member.modifiers, levelsUp);
|
||||
@@ -1018,7 +1037,6 @@ public final class SymbolTable {
|
||||
|
||||
@Override
|
||||
public @Nullable MethodResolution doResolveMethod(String name, int levelsUp) {
|
||||
|
||||
var member = methods.get(name);
|
||||
if (member == null) return null;
|
||||
return new LexicalMethod(false, isClosed, false, member.modifiers, levelsUp);
|
||||
|
||||
@@ -25,6 +25,9 @@ import org.pkl.core.runtime.VmUtils;
|
||||
@NodeInfo(shortName = "module")
|
||||
public final class GetModuleNode extends ExpressionNode {
|
||||
|
||||
// NB: When used in an open module, this may resolve to instances of a regular class that extends
|
||||
// the module.
|
||||
|
||||
public GetModuleNode(SourceSection sourceSection) {
|
||||
super(sourceSection);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.pkl.core.ast.expression.primary;
|
||||
|
||||
import com.oracle.truffle.api.frame.VirtualFrame;
|
||||
import com.oracle.truffle.api.source.SourceSection;
|
||||
import org.pkl.core.ast.ExpressionNode;
|
||||
import org.pkl.core.runtime.VmUtils;
|
||||
|
||||
public final class GetReceiverClassNode extends ExpressionNode {
|
||||
|
||||
public GetReceiverClassNode(SourceSection sourceSection) {
|
||||
super(sourceSection);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object executeGeneric(VirtualFrame frame) {
|
||||
return VmUtils.getClass(VmUtils.getReceiver(frame));
|
||||
}
|
||||
}
|
||||
@@ -58,8 +58,8 @@ public final class GetParentForTypeNode extends ExpressionNode {
|
||||
var defaultValue =
|
||||
typeNode.createDefaultValue(frame, VmLanguage.get(this), sourceSection, qualifiedName);
|
||||
|
||||
// can't cache default value for `module` type in a non-final module because it's a self-type
|
||||
// (the default value changes when inherited).
|
||||
// can't cache default value for `module`/`this` types in a non-final modules/classes because
|
||||
// they're self types (the default value changes when inherited).
|
||||
if (typeNode.isFinalType() && defaultValue != null) {
|
||||
unresolvedTypeNode = null;
|
||||
this.defaultValue = defaultValue;
|
||||
|
||||
@@ -46,6 +46,8 @@ import org.pkl.core.TypeParameter;
|
||||
import org.pkl.core.ast.*;
|
||||
import org.pkl.core.ast.builder.SymbolTable.CustomThisScope;
|
||||
import org.pkl.core.ast.expression.primary.GetModuleNode;
|
||||
import org.pkl.core.ast.expression.primary.GetReceiverClassNode;
|
||||
import org.pkl.core.ast.expression.primary.GetReceiverNode;
|
||||
import org.pkl.core.ast.frame.WriteFrameSlotNode;
|
||||
import org.pkl.core.ast.frame.WriteFrameSlotNodeGen;
|
||||
import org.pkl.core.ast.internal.SyntheticNode;
|
||||
@@ -54,6 +56,7 @@ import org.pkl.core.ast.member.ListingOrMappingTypeCastNode;
|
||||
import org.pkl.core.ast.member.ObjectMember;
|
||||
import org.pkl.core.ast.member.UntypedObjectMemberNode;
|
||||
import org.pkl.core.runtime.*;
|
||||
import org.pkl.core.stdlib.VmObjectFactory;
|
||||
import org.pkl.core.util.EconomicMaps;
|
||||
import org.pkl.core.util.EconomicSets;
|
||||
import org.pkl.core.util.LateInit;
|
||||
@@ -144,7 +147,7 @@ public abstract class TypeNode extends PklNode {
|
||||
true,
|
||||
typeNode -> {
|
||||
// assumption: don't need to worry about `NonFinalClassTypeNode`
|
||||
if (typeNode instanceof NonFinalModuleTypeNode) {
|
||||
if (typeNode instanceof NonFinalSelfTypeNode) {
|
||||
ret.set(false);
|
||||
return false;
|
||||
}
|
||||
@@ -411,43 +414,61 @@ public abstract class TypeNode extends PklNode {
|
||||
}
|
||||
}
|
||||
|
||||
/** The `module` type for a final module. */
|
||||
public static final class FinalModuleTypeNode extends ObjectSlotTypeNode {
|
||||
private final VmClass moduleClass;
|
||||
/** The `module` or `this` type for a final module or class. */
|
||||
public static final class FinalSelfTypeNode extends ObjectSlotTypeNode {
|
||||
private final VmClass clazz;
|
||||
private final PType pType;
|
||||
private final VmObjectFactory<Void> mirrorFactory;
|
||||
|
||||
public FinalModuleTypeNode(SourceSection sourceSection, VmClass moduleClass) {
|
||||
private FinalSelfTypeNode(
|
||||
SourceSection sourceSection,
|
||||
VmClass clazz,
|
||||
PType pType,
|
||||
VmObjectFactory<Void> mirrorFactory) {
|
||||
super(sourceSection);
|
||||
this.moduleClass = moduleClass;
|
||||
this.clazz = clazz;
|
||||
this.pType = pType;
|
||||
this.mirrorFactory = mirrorFactory;
|
||||
}
|
||||
|
||||
public static FinalSelfTypeNode moduleType(SourceSection sourceSection, VmClass clazz) {
|
||||
return new FinalSelfTypeNode(
|
||||
sourceSection, clazz, PType.MODULE, MirrorFactories.moduleTypeFactory);
|
||||
}
|
||||
|
||||
public static FinalSelfTypeNode thisType(SourceSection sourceSection, VmClass clazz) {
|
||||
return new FinalSelfTypeNode(
|
||||
sourceSection, clazz, PType.THIS, MirrorFactories.thisTypeFactory);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object executeLazily(VirtualFrame frame, Object value) {
|
||||
if (value instanceof VmTyped typed && typed.getVmClass() == moduleClass) return value;
|
||||
if (VmUtils.getClass(value) == clazz) return value;
|
||||
|
||||
throw typeMismatch(value, moduleClass);
|
||||
throw typeMismatch(value, clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VmTyped getMirror() {
|
||||
return MirrorFactories.moduleTypeFactory.create(null);
|
||||
return mirrorFactory.create(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doIsEquivalentTo(TypeNode other) {
|
||||
if (!(other instanceof FinalModuleTypeNode finalModuleTypeNode)) {
|
||||
if (!(other instanceof FinalSelfTypeNode finalSelfTypeNode)) {
|
||||
return false;
|
||||
}
|
||||
return moduleClass.equals(finalModuleTypeNode.moduleClass);
|
||||
return clazz.equals(finalSelfTypeNode.clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected PType doExport() {
|
||||
return PType.MODULE;
|
||||
return pType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VmClass getVmClass() {
|
||||
return moduleClass;
|
||||
return clazz;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -461,54 +482,77 @@ public abstract class TypeNode extends PklNode {
|
||||
VmLanguage language,
|
||||
SourceSection headerSection,
|
||||
String qualifiedName) {
|
||||
return TypeNode.createDefaultValue(moduleClass);
|
||||
return TypeNode.createDefaultValue(clazz);
|
||||
}
|
||||
}
|
||||
|
||||
/** The `module` type for an open module. */
|
||||
public static final class NonFinalModuleTypeNode extends ObjectSlotTypeNode {
|
||||
private final VmClass moduleClass; // only used by getVmClass()
|
||||
@Child private ExpressionNode getModuleNode;
|
||||
/** The `module` or `this` type for an open module or class. */
|
||||
public static final class NonFinalSelfTypeNode extends ObjectSlotTypeNode {
|
||||
private final VmClass clazz; // only used by getVmClass()
|
||||
@Child private ExpressionNode getTargetNode;
|
||||
private final PType pType;
|
||||
private final VmObjectFactory<Void> mirrorFactory;
|
||||
|
||||
public NonFinalModuleTypeNode(SourceSection sourceSection, VmClass moduleClass) {
|
||||
private NonFinalSelfTypeNode(
|
||||
SourceSection sourceSection,
|
||||
VmClass clazz,
|
||||
ExpressionNode getTargetNode,
|
||||
PType pType,
|
||||
VmObjectFactory<Void> mirrorFactory) {
|
||||
super(sourceSection);
|
||||
this.moduleClass = moduleClass;
|
||||
getModuleNode = new GetModuleNode(sourceSection);
|
||||
this.clazz = clazz;
|
||||
this.getTargetNode = getTargetNode;
|
||||
this.pType = pType;
|
||||
this.mirrorFactory = mirrorFactory;
|
||||
}
|
||||
|
||||
public static NonFinalSelfTypeNode moduleType(SourceSection sourceSection, VmClass clazz) {
|
||||
return new NonFinalSelfTypeNode(
|
||||
sourceSection,
|
||||
clazz,
|
||||
new GetModuleNode(sourceSection),
|
||||
PType.MODULE,
|
||||
MirrorFactories.moduleTypeFactory);
|
||||
}
|
||||
|
||||
public static NonFinalSelfTypeNode thisType(SourceSection sourceSection, VmClass clazz) {
|
||||
return new NonFinalSelfTypeNode(
|
||||
sourceSection, clazz, new GetReceiverNode(), PType.THIS, MirrorFactories.thisTypeFactory);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object executeLazily(VirtualFrame frame, Object value) {
|
||||
var moduleClass = ((VmTyped) getModuleNode.executeGeneric(frame)).getVmClass();
|
||||
var clazz = ((VmObjectLike) getTargetNode.executeGeneric(frame)).getVmClass();
|
||||
|
||||
if (value instanceof VmTyped typed) {
|
||||
var valueClass = typed.getVmClass();
|
||||
if (moduleClass.isSuperclassOf(valueClass)) return value;
|
||||
if (clazz.isSuperclassOf(valueClass)) return value;
|
||||
}
|
||||
|
||||
throw typeMismatch(value, moduleClass);
|
||||
throw typeMismatch(value, clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VmTyped getMirror() {
|
||||
return MirrorFactories.moduleTypeFactory.create(null);
|
||||
return mirrorFactory.create(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doIsEquivalentTo(TypeNode other) {
|
||||
if (!(other instanceof NonFinalModuleTypeNode nonFinalModuleTypeNode)) {
|
||||
if (!(other instanceof NonFinalSelfTypeNode nonFinalSelfTypeNode)) {
|
||||
return false;
|
||||
}
|
||||
return moduleClass.equals(nonFinalModuleTypeNode.moduleClass);
|
||||
return clazz.equals(nonFinalSelfTypeNode.clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected PType doExport() {
|
||||
return PType.MODULE;
|
||||
return pType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VmClass getVmClass() {
|
||||
return moduleClass;
|
||||
return clazz;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -522,8 +566,8 @@ public abstract class TypeNode extends PklNode {
|
||||
VmLanguage language,
|
||||
SourceSection headerSection,
|
||||
String qualifiedName) {
|
||||
var moduleClass = ((VmTyped) getModuleNode.executeGeneric(frame)).getVmClass();
|
||||
return TypeNode.createDefaultValue(moduleClass);
|
||||
var clazz = ((VmObjectLike) getTargetNode.executeGeneric(frame)).getVmClass();
|
||||
return TypeNode.createDefaultValue(clazz);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1954,7 +1998,7 @@ public abstract class TypeNode extends PklNode {
|
||||
protected final PType doExport() {
|
||||
var parameterTypes =
|
||||
Arrays.stream(parameterTypeNodes).map(TypeNode::export).collect(Collectors.toList());
|
||||
return new PType.Function(parameterTypes, TypeNode.export(returnTypeNode));
|
||||
return new PType.Function(parameterTypes, returnTypeNode.doExport());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -2005,8 +2049,7 @@ public abstract class TypeNode extends PklNode {
|
||||
|
||||
@Override
|
||||
protected final PType doExport() {
|
||||
return new PType.Class(
|
||||
BaseModule.getFunctionClass().export(), TypeNode.export(typeArgumentNode));
|
||||
return new PType.Class(BaseModule.getFunctionClass().export(), typeArgumentNode.doExport());
|
||||
}
|
||||
|
||||
@Specialization
|
||||
@@ -2119,6 +2162,7 @@ public abstract class TypeNode extends PklNode {
|
||||
public abstract static class ReferenceTypeNode extends ValidatingObjectSlotTypeNode {
|
||||
@Child private TypeNode domainTypeNode;
|
||||
@Child private TypeNode referentTypeNode;
|
||||
@Child private ExpressionNode getReceiverClassNode;
|
||||
@Child private ExpressionNode getModuleNode;
|
||||
|
||||
public ReferenceTypeNode(
|
||||
@@ -2126,6 +2170,7 @@ public abstract class TypeNode extends PklNode {
|
||||
super(sourceSection);
|
||||
this.domainTypeNode = domainTypeNode;
|
||||
this.referentTypeNode = referentTypeNode;
|
||||
this.getReceiverClassNode = new GetReceiverClassNode(sourceSection);
|
||||
this.getModuleNode = new GetModuleNode(sourceSection);
|
||||
validate();
|
||||
}
|
||||
@@ -2168,25 +2213,30 @@ public abstract class TypeNode extends PklNode {
|
||||
} catch (VmTypeMismatchException e) {
|
||||
CompilerDirectives.transferToInterpreter();
|
||||
throw new VmTypeMismatchException.Reference(
|
||||
sourceSection,
|
||||
value,
|
||||
TypeNode.export(domainTypeNode),
|
||||
TypeNode.export(referentTypeNode));
|
||||
sourceSection, value, domainTypeNode.doExport(), referentTypeNode.doExport());
|
||||
}
|
||||
|
||||
var module = (VmTyped) getModuleNode.executeGeneric(frame);
|
||||
return doEval(value, module);
|
||||
// NB: this is correct because the `this` type is not allowed in typealias bodies.
|
||||
// So `this` can only correspond to the receiver where the type check/annotation is written.
|
||||
var thisClass = ((VmClass) getReceiverClassNode.executeGeneric(frame));
|
||||
|
||||
// NB: This will be wrong for deprecated usage of the `module` type in typealias bodies.
|
||||
// It will always resolve to the module where the type check/annotation is written
|
||||
// not the type itself. This is no _more_ broken than it was before.
|
||||
var moduleClass = VmUtils.getClass(getModuleNode.executeGeneric(frame));
|
||||
|
||||
return doEval(value, thisClass, moduleClass);
|
||||
}
|
||||
|
||||
@TruffleBoundary
|
||||
private Object doEval(VmReference value, VmTyped module) {
|
||||
var referentType = TypeNode.export(referentTypeNode);
|
||||
if (value.referentTypeIsSubtypeOf(referentType, module.getVmClass().export())) {
|
||||
private Object doEval(VmReference value, VmClass thisClass, VmClass moduleClass) {
|
||||
var referentType = referentTypeNode.doExport();
|
||||
if (value.referentTypeIsSubtypeOf(referentType, thisClass.export(), moduleClass.export())) {
|
||||
return value;
|
||||
}
|
||||
|
||||
throw new VmTypeMismatchException.Reference(
|
||||
sourceSection, value, TypeNode.export(domainTypeNode), referentType);
|
||||
sourceSection, value, domainTypeNode.doExport(), referentType);
|
||||
}
|
||||
|
||||
@Fallback
|
||||
@@ -2739,6 +2789,7 @@ public abstract class TypeNode extends PklNode {
|
||||
return aliasedTypeNode.executeLazily(frame, value);
|
||||
}
|
||||
|
||||
/** See docstring on {@link TypeAliasTypeNode#executeLazily}. */
|
||||
@Override
|
||||
public Object executeEagerly(VirtualFrame frame, Object value) {
|
||||
return aliasedTypeNode.executeEagerly(frame, value);
|
||||
@@ -3334,6 +3385,7 @@ public abstract class TypeNode extends PklNode {
|
||||
if (clazz.isInstantiable()) {
|
||||
if (clazz.isListingClass()) return VmListing.empty();
|
||||
if (clazz.isMappingClass()) return VmMapping.empty();
|
||||
if (clazz.isDynamicClass()) return VmDynamic.empty();
|
||||
return clazz.getPrototype();
|
||||
}
|
||||
|
||||
|
||||
@@ -103,8 +103,28 @@ public abstract class UnresolvedTypeNode extends PklNode {
|
||||
var module = (VmTyped) getModuleNode.executeGeneric(frame);
|
||||
var moduleClass = module.getVmClass();
|
||||
return moduleClass.isClosed()
|
||||
? new FinalModuleTypeNode(sourceSection, moduleClass)
|
||||
: new NonFinalModuleTypeNode(sourceSection, moduleClass);
|
||||
? FinalSelfTypeNode.moduleType(sourceSection, moduleClass)
|
||||
: NonFinalSelfTypeNode.moduleType(sourceSection, moduleClass);
|
||||
}
|
||||
}
|
||||
|
||||
/** The `this` type. */
|
||||
public static final class This extends UnresolvedTypeNode {
|
||||
@Child private ExpressionNode getClassNode;
|
||||
|
||||
public This(SourceSection sourceSection, ExpressionNode getClassNode) {
|
||||
super(sourceSection);
|
||||
this.getClassNode = getClassNode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeNode execute(VirtualFrame frame) {
|
||||
CompilerDirectives.transferToInterpreter();
|
||||
|
||||
var clazz = (VmClass) getClassNode.executeGeneric(frame);
|
||||
return clazz.isClosed()
|
||||
? FinalSelfTypeNode.thisType(sourceSection, clazz)
|
||||
: NonFinalSelfTypeNode.thisType(sourceSection, clazz);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,6 +97,9 @@ public final class MirrorFactories {
|
||||
public static final VmObjectFactory<Void> moduleTypeFactory =
|
||||
new VmObjectFactory<>(ReflectModule::getModuleTypeClass);
|
||||
|
||||
public static final VmObjectFactory<Void> thisTypeFactory =
|
||||
new VmObjectFactory<>(ReflectModule::getThisTypeClass);
|
||||
|
||||
public static final VmObjectFactory<Void> unknownTypeFactory =
|
||||
new VmObjectFactory<>(ReflectModule::getUnknownTypeClass);
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
|
||||
* Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -84,6 +84,10 @@ public final class ReflectModule extends StdLibModule {
|
||||
return ModuleTypeClass.instance;
|
||||
}
|
||||
|
||||
public static VmClass getThisTypeClass() {
|
||||
return ThisTypeClass.instance;
|
||||
}
|
||||
|
||||
public static VmClass getFunctionTypeClass() {
|
||||
return FunctionTypeClass.instance;
|
||||
}
|
||||
@@ -152,6 +156,10 @@ public final class ReflectModule extends StdLibModule {
|
||||
static final VmClass instance = loadClass("ModuleType");
|
||||
}
|
||||
|
||||
private static final class ThisTypeClass {
|
||||
static final VmClass instance = loadClass("ThisType");
|
||||
}
|
||||
|
||||
private static final class FunctionTypeClass {
|
||||
static final VmClass instance = loadClass("FunctionType");
|
||||
}
|
||||
|
||||
@@ -57,11 +57,7 @@ public final class VmReference extends VmValue {
|
||||
|
||||
@TruffleBoundary
|
||||
public VmReference(VmTyped domain, VmClass clazz, Object data) {
|
||||
this(
|
||||
domain,
|
||||
data,
|
||||
RrbTree.empty(),
|
||||
normalizeTypes(new PType.Class(clazz.export()), clazz.getModule().getVmClass().export()));
|
||||
this(domain, data, RrbTree.empty(), normalizeTypes(new PType.Class(clazz.export())));
|
||||
}
|
||||
|
||||
public VmReference(VmTyped domain, Object data, ImRrbt<VmTyped> path, PType referentType) {
|
||||
@@ -92,14 +88,18 @@ public final class VmReference extends VmValue {
|
||||
// * transforming T? into T|Null
|
||||
// * dereferencing aliases (except for well-known stdlib alias types)
|
||||
// * flattening unions
|
||||
// * when moduleClass is supplied, replace PType.MODULE with appropriate PType.Class
|
||||
// * drop PType.Function and PType.TypeVariable
|
||||
private static PType normalizeTypes(PType type, PClass moduleClass) {
|
||||
private static PType normalizeTypes(
|
||||
PType type, @Nullable PType thisClass, @Nullable PType moduleClass) {
|
||||
var types = new HashSet<PType>();
|
||||
normalizeTypes(type, moduleClass, types);
|
||||
normalizeTypes(type, types, thisClass, moduleClass);
|
||||
return minimizeTypes(types);
|
||||
}
|
||||
|
||||
private static PType normalizeTypes(PType type) {
|
||||
return normalizeTypes(type, null, null);
|
||||
}
|
||||
|
||||
private static PType minimizeTypes(Set<PType> types) {
|
||||
if (types.size() == 1) return types.iterator().next();
|
||||
// optimization: unknown allows all references, erase all candidates to only unknown
|
||||
@@ -112,7 +112,8 @@ public final class VmReference extends VmValue {
|
||||
return new PType.Union(typesList);
|
||||
}
|
||||
|
||||
private static void normalizeTypes(PType type, PClass moduleClass, Set<PType> result) {
|
||||
private static void normalizeTypes(
|
||||
PType type, Set<PType> result, @Nullable PType thisClass, @Nullable PType moduleClass) {
|
||||
if (type == PType.UNKNOWN || type == PType.NOTHING || type instanceof PType.StringLiteral) {
|
||||
result.add(type);
|
||||
} else if (type instanceof PType.Class clazz) {
|
||||
@@ -128,35 +129,51 @@ public final class VmReference extends VmValue {
|
||||
} else {
|
||||
var typeArgs = new ArrayList<PType>(clazz.getTypeArguments().size());
|
||||
for (var arg : clazz.getTypeArguments()) {
|
||||
typeArgs.add(normalizeTypes(arg, moduleClass));
|
||||
typeArgs.add(normalizeTypes(arg, thisClass, moduleClass));
|
||||
}
|
||||
result.add(new PType.Class(clazz.getPClass(), typeArgs));
|
||||
}
|
||||
}
|
||||
// normalize `T?` to `T | Null`
|
||||
else if (type instanceof PType.Nullable nullable) {
|
||||
normalizeTypes(nullable.getBaseType(), moduleClass, result);
|
||||
normalizeTypes(nullable.getBaseType(), result, thisClass, moduleClass);
|
||||
result.add(new PType.Class(BaseModule.getNullClass().export()));
|
||||
// erase `T(someConstraint)` to `T`
|
||||
} else if (type instanceof PType.Constrained constrained) {
|
||||
normalizeTypes(constrained.getBaseType(), moduleClass, result);
|
||||
normalizeTypes(constrained.getBaseType(), result, thisClass, moduleClass);
|
||||
} else if (type instanceof PType.Alias alias) {
|
||||
if (isPreservedTypeAlias(alias.getTypeAlias())) {
|
||||
result.add(alias);
|
||||
} else {
|
||||
normalizeTypes(alias.getAliasedType(), alias.getTypeAlias().getModuleClass(), result);
|
||||
normalizeTypes(alias.getAliasedType(), result, thisClass, moduleClass);
|
||||
}
|
||||
} else if (type instanceof PType.Union union) {
|
||||
for (var t : union.getElementTypes()) {
|
||||
normalizeTypes(t, moduleClass, result);
|
||||
normalizeTypes(t, result, thisClass, moduleClass);
|
||||
}
|
||||
} else if (type == PType.THIS) {
|
||||
assert thisClass != null;
|
||||
// there are 4 entrypoints here:
|
||||
// 1. init via the Reference constructor can only normalize an unparameterized PType.Class
|
||||
// 2. typecheck via ReferenceTypeNode erases self types to their actual PType.Class
|
||||
// 3. subscript access can only be achieved by first performing property access, at which time
|
||||
// self types are erased
|
||||
// 4. property access uses the enclosing receiver's class to substitute for these self types
|
||||
// only property access and typecheck can produce THIS or MODULE.
|
||||
// getCandidatePropertyType and referentTypeIsSubtypeOf always pass non-null `thisClass`.
|
||||
result.add(thisClass);
|
||||
} else if (type == PType.MODULE) {
|
||||
result.add(new PType.Class(moduleClass));
|
||||
// this can be incorrect for usage of the module type in a class's property type annotation,
|
||||
// which is deprecated!!
|
||||
assert moduleClass != null;
|
||||
// see PType.THIS case above
|
||||
result.add(moduleClass);
|
||||
} else {
|
||||
// remaining types: PType.Function, PType.TypeVariable. no normalizing needed; TypeVariable
|
||||
// gets replaced upon instantiation, and Function can bubble up to users as a reference error
|
||||
// if accessed.
|
||||
result.add(type);
|
||||
// PType.MODULE and PType.THIS can never be encountered here; caller must deref self types
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,7 +260,8 @@ public final class VmReference extends VmValue {
|
||||
throw new VmReferenceAccessError(type, VmReferenceAccessErrorType.EXTERNAL_MEMBER);
|
||||
}
|
||||
|
||||
normalizeTypes(prop.getType(), clazz.getPClass().getModuleClass(), result);
|
||||
normalizeTypes(
|
||||
prop.getType(), result, clazz, new PType.Class(clazz.getPClass().getModuleClass()));
|
||||
}
|
||||
|
||||
private static PClassInfo<?> getClassInfo(Object value) {
|
||||
@@ -273,19 +291,19 @@ public final class VmReference extends VmValue {
|
||||
if (!(key instanceof Long)) {
|
||||
throw new VmReferenceAccessError(type, VmReferenceAccessErrorType.CANNOT_FIND_MEMBER);
|
||||
}
|
||||
normalizeTypes(clazz.getTypeArguments().get(0), clazz.getPClass().getModuleClass(), result);
|
||||
normalizeTypes(clazz.getTypeArguments().get(0), result, null, null);
|
||||
return;
|
||||
}
|
||||
if (clazz.getPClass().getInfo() == PClassInfo.Mapping
|
||||
|| clazz.getPClass().getInfo() == PClassInfo.Map) {
|
||||
var typeArgs = clazz.getTypeArguments();
|
||||
var keyTypes = normalizeTypes(typeArgs.get(0), clazz.getPClass().getModuleClass());
|
||||
var keyTypes = normalizeTypes(typeArgs.get(0));
|
||||
for (var kt : iterateTypes(keyTypes)) {
|
||||
if (kt == PType.UNKNOWN
|
||||
|| (kt instanceof PType.Class klazz && klazz.getPClass().getInfo() == getClassInfo(key))
|
||||
|| (kt instanceof PType.StringLiteral stringLiteral
|
||||
&& stringLiteral.getLiteral().equals(key))) {
|
||||
normalizeTypes(typeArgs.get(1), clazz.getPClass().getModuleClass(), result);
|
||||
normalizeTypes(typeArgs.get(1), result, null, null);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -303,13 +321,14 @@ public final class VmReference extends VmValue {
|
||||
/**
|
||||
* Tells if this reference's referent type is a subtype of {@code type}. Does not check domain.
|
||||
*/
|
||||
public boolean referentTypeIsSubtypeOf(PType type, PClass moduleClass) {
|
||||
@TruffleBoundary
|
||||
public boolean referentTypeIsSubtypeOf(PType type, PClass thisClass, PClass moduleClass) {
|
||||
// fast path: if referent is unknown it can match any type check
|
||||
if (referentType == PType.UNKNOWN) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var checkType = normalizeTypes(type, moduleClass);
|
||||
var checkType = normalizeTypes(type, new PType.Class(thisClass), new PType.Class(moduleClass));
|
||||
// fast path: short circuit if any referent is accepted
|
||||
if (checkType == PType.UNKNOWN || isClass(checkType, BaseModule.getAnyClass().export())) {
|
||||
return true;
|
||||
|
||||
@@ -137,6 +137,14 @@ public final class ReflectNodes {
|
||||
}
|
||||
}
|
||||
|
||||
public abstract static class thisType extends ExternalPropertyNode {
|
||||
@Specialization
|
||||
@TruffleBoundary
|
||||
protected VmTyped eval(VmTyped self) {
|
||||
return MirrorFactories.thisTypeFactory.create(null);
|
||||
}
|
||||
}
|
||||
|
||||
public abstract static class unknownType extends ExternalPropertyNode {
|
||||
@Specialization
|
||||
@TruffleBoundary
|
||||
|
||||
@@ -1218,3 +1218,21 @@ Class `{0}` should either be declared `abstract`, or should implement method `{1
|
||||
noImplementationForAbstractMethods=\
|
||||
Class `{0}` should either be declared `abstract`, or should implement the following methods:\n\
|
||||
{1}
|
||||
|
||||
invalidModuleTypeInProperty=\
|
||||
Cannot reference `module` type from const property `{0}`.
|
||||
|
||||
invalidModuleTypeInMethod=\
|
||||
Cannot reference `module` type from const method `{0}`.
|
||||
|
||||
invalidModuleTypeInClass=\
|
||||
Cannot reference `module` type within a class body.
|
||||
|
||||
invalidModuleTypeInAnnotation=\
|
||||
Cannot reference `module` type within an annotation body.
|
||||
|
||||
invalidModuleTypeInTypeAlias=\
|
||||
Cannot reference `module` type within a type alias body.
|
||||
|
||||
invalidThisTypeInTypeAlias=\
|
||||
Cannot reference `this` type within a type alias body.
|
||||
Reference in new issue
Block a user