Skip to content

Commit

Permalink
BuiltinObject guards cached builtin type with WeakReference to context
Browse files Browse the repository at this point in the history
  • Loading branch information
Akirathan committed Dec 16, 2024
1 parent 78002d1 commit fcd043f
Showing 1 changed file with 14 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.oracle.truffle.api.library.ExportLibrary;
import com.oracle.truffle.api.library.ExportMessage;
import com.oracle.truffle.api.nodes.Node;
import java.lang.ref.WeakReference;
import org.enso.interpreter.node.expression.builtin.Builtin;
import org.enso.interpreter.runtime.EnsoContext;
import org.enso.interpreter.runtime.data.EnsoObject;
Expand All @@ -27,7 +28,15 @@ public abstract class BuiltinObject extends EnsoObject {

private final String builtinName;

@CompilationFinal private Builtin cachedBuiltinType;
/**
* A weak reference to the context in which this node was last executed.
*
* <p>Inspired by {@link
* org.enso.interpreter.node.expression.builtin.meta.EnsoProjectNode#previousCtxRef}
*/
@CompilationFinal private WeakReference<EnsoContext> previousCtxRef = new WeakReference<>(null);

private Builtin cachedBuiltinType;

/**
* @param builtinName Simple name of the builtin that should be contained in {@link
Expand All @@ -44,9 +53,11 @@ public final boolean hasType() {

@ExportMessage
public final Type getType(@Bind("$node") Node node) {
if (cachedBuiltinType == null) {
var ctx = EnsoContext.get(node);
var previousCtx = previousCtxRef.get();
if (previousCtx == null || cachedBuiltinType == null || previousCtx != ctx) {
CompilerDirectives.transferToInterpreterAndInvalidate();
var ctx = EnsoContext.get(node);
previousCtxRef = new WeakReference<>(ctx);
cachedBuiltinType = ctx.getBuiltins().getBuiltinType(builtinName);
}
return cachedBuiltinType.getType();
Expand Down

0 comments on commit fcd043f

Please sign in to comment.