package com.oracle.truffle.js.nodes.control;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import com.oracle.truffle.api.CompilerAsserts;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.RootCallTarget;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.TruffleContext;
import com.oracle.truffle.api.TruffleStackTraceElement;
import com.oracle.truffle.api.frame.Frame;
import com.oracle.truffle.api.frame.MaterializedFrame;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.instrumentation.Tag;
import com.oracle.truffle.api.interop.InteropLibrary;
import com.oracle.truffle.api.nodes.NodeCost;
import com.oracle.truffle.api.nodes.NodeInfo;
import com.oracle.truffle.api.nodes.RootNode;
import com.oracle.truffle.api.object.DynamicObject;
import com.oracle.truffle.api.source.SourceSection;
import com.oracle.truffle.js.nodes.JavaScriptNode;
import com.oracle.truffle.js.nodes.access.JSReadFrameSlotNode;
import com.oracle.truffle.js.nodes.access.JSWriteFrameSlotNode;
import com.oracle.truffle.js.nodes.access.PropertySetNode;
import com.oracle.truffle.js.nodes.access.ScopeFrameNode;
import com.oracle.truffle.js.nodes.function.SpecializedNewObjectNode;
import com.oracle.truffle.js.nodes.promise.AsyncRootNode;
import com.oracle.truffle.js.runtime.JSConfig;
import com.oracle.truffle.js.runtime.JSContext;
import com.oracle.truffle.js.runtime.JSFrameUtil;
import com.oracle.truffle.js.runtime.JSRealm;
import com.oracle.truffle.js.runtime.JavaScriptRootNode;
import com.oracle.truffle.js.runtime.builtins.JSFunction;
import com.oracle.truffle.js.runtime.builtins.JSFunction.AsyncGeneratorState;
import com.oracle.truffle.js.runtime.objects.AsyncGeneratorRequest;
import com.oracle.truffle.js.runtime.objects.Completion;
import com.oracle.truffle.js.runtime.objects.JSObjectUtil;
import com.oracle.truffle.js.runtime.objects.Undefined;
public final class AsyncGeneratorBodyNode extends JavaScriptNode {
@NodeInfo(cost = NodeCost.NONE, language = "JavaScript", description = "The root node of async generator functions in JavaScript.")
private static final class AsyncGeneratorRootNode extends JavaScriptRootNode implements AsyncRootNode {
private static final int ASYNC_FRAME_ARG_INDEX = 0;
@Child private PropertySetNode setGeneratorState;
@Child private JavaScriptNode functionBody;
@Child private JSWriteFrameSlotNode writeYieldValue;
@Child private JSReadFrameSlotNode readYieldResult;
@Child private JSReadFrameSlotNode readAsyncContext;
@Child private AsyncGeneratorResolveNode asyncGeneratorResolveNode;
@Child private AsyncGeneratorRejectNode asyncGeneratorRejectNode;
@Child private AsyncGeneratorResumeNextNode asyncGeneratorResumeNextNode;
@Child private TryCatchNode.GetErrorObjectNode getErrorObjectNode;
@Child private InteropLibrary exceptions;
private final JSContext context;
private final String functionName;
AsyncGeneratorRootNode(JSContext context, JavaScriptNode functionBody, JSWriteFrameSlotNode writeYieldValueNode, JSReadFrameSlotNode readYieldResultNode, JSReadFrameSlotNode readAsyncContext,
SourceSection functionSourceSection, String functionName) {
super(context.getLanguage(), functionSourceSection, null);
this.readAsyncContext = readAsyncContext;
this.functionName = functionName;
this.setGeneratorState = PropertySetNode.createSetHidden(JSFunction.ASYNC_GENERATOR_STATE_ID, context);
this.functionBody = functionBody;
this.writeYieldValue = writeYieldValueNode;
this.readYieldResult = readYieldResultNode;
this.context = context;
this.asyncGeneratorResolveNode = AsyncGeneratorResolveNode.create(context);
this.asyncGeneratorResumeNextNode = AsyncGeneratorResumeNextNode.createTailCall(context);
}
@Override
public Object execute(VirtualFrame frame) {
Object[] arguments = frame.getArguments();
VirtualFrame generatorFrame = JSFrameUtil.castMaterializedFrame(arguments[ASYNC_FRAME_ARG_INDEX]);
DynamicObject generatorObject = (DynamicObject) arguments[1];
Completion completion = (Completion) arguments[2];
final JSRealm currentRealm = context.getRealm();
final JSRealm realm;
final boolean enterContext;
if (context.neverCreatedChildRealms()) {
assert currentRealm == JSFunction.getRealm(JSFrameUtil.getFunctionObject(generatorFrame));
realm = currentRealm;
enterContext = false;
} else {
realm = JSFunction.getRealm(JSFrameUtil.getFunctionObject(generatorFrame));
enterContext = realm != currentRealm;
}
Object prev = null;
TruffleContext childContext = null;
if (enterContext) {
childContext = realm.getTruffleContext();
prev = childContext.enter(this);
}
try {
for (;;) {
assert JSObjectUtil.getHiddenProperty(generatorObject, JSFunction.ASYNC_GENERATOR_STATE_ID) == AsyncGeneratorState.Executing ||
JSObjectUtil.getHiddenProperty(generatorObject, JSFunction.ASYNC_GENERATOR_STATE_ID) == AsyncGeneratorState.SuspendedYield;
writeYieldValue.executeWrite(generatorFrame, completion);
try {
Object result = functionBody.execute(generatorFrame);
setGeneratorState.setValue(generatorObject, AsyncGeneratorState.Completed);
asyncGeneratorResolveNode.performResolve(frame, generatorObject, result, true);
} catch (YieldException e) {
if (e.isYield()) {
setGeneratorState.setValue(generatorObject, AsyncGeneratorState.SuspendedYield);
asyncGeneratorResolveNode.performResolve(frame, generatorObject, e.getResult(), false);
} else {
assert e.isAwait();
return Undefined.instance;
}
} catch (Throwable e) {
if (shouldCatch(e)) {
setGeneratorState.setValue(generatorObject, AsyncGeneratorState.Completed);
Object reason = getErrorObjectNode.execute(e);
asyncGeneratorRejectNode.performReject(generatorFrame, generatorObject, reason);
} else {
throw e;
}
}
Object nextCompletion = asyncGeneratorResumeNextNode.execute(generatorFrame, generatorObject);
if (nextCompletion instanceof Completion) {
completion = (Completion) nextCompletion;
continue;
} else {
return Undefined.instance;
}
}
} finally {
if (enterContext) {
childContext.leave(this, prev);
}
}
}
private boolean shouldCatch(Throwable exception) {
if (getErrorObjectNode == null || asyncGeneratorRejectNode == null || exceptions == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
getErrorObjectNode = insert(TryCatchNode.GetErrorObjectNode.create(context));
asyncGeneratorRejectNode = insert(AsyncGeneratorRejectNode.create(context));
exceptions = insert(InteropLibrary.getFactory().createDispatched(JSConfig.InteropLibraryLimit));
}
return TryCatchNode.shouldCatch(exception, exceptions);
}
@Override
public boolean isResumption() {
return true;
}
@Override
public String getName() {
if (functionName != null && !functionName.isEmpty()) {
return functionName;
}
return ":asyncgenerator";
}
@Override
public String toString() {
return getName();
}
@Override
public DynamicObject getAsyncFunctionPromise(Frame asyncFrame) {
Object[] initialState = (Object[]) readAsyncContext.execute((VirtualFrame) asyncFrame);
RootCallTarget resumeTarget = (RootCallTarget) initialState[AsyncRootNode.CALL_TARGET_INDEX];
assert resumeTarget.getRootNode() == this;
DynamicObject generatorObject = (DynamicObject) initialState[AsyncRootNode.GENERATOR_OBJECT_OR_PROMISE_CAPABILITY_INDEX];
Object queue = JSObjectUtil.getHiddenProperty(generatorObject, JSFunction.ASYNC_GENERATOR_QUEUE_ID);
if (queue instanceof ArrayDeque<?> && ((ArrayDeque<?>) queue).size() == 1) {
AsyncGeneratorRequest request = (AsyncGeneratorRequest) ((ArrayDeque<?>) queue).peekFirst();
return request.getPromiseCapability().getPromise();
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public List<TruffleStackTraceElement> getSavedStackTrace(Frame asyncFrame) {
Object[] initialState = (Object[]) readAsyncContext.execute((VirtualFrame) asyncFrame);
return (List<TruffleStackTraceElement>) initialState[AsyncRootNode.STACK_TRACE_INDEX];
}
@Override
protected List<TruffleStackTraceElement> findAsynchronousFrames(Frame frame) {
if (!context.isOptionAsyncStackTraces() || context.getLanguage().getAsyncStackDepth() == 0) {
return null;
}
VirtualFrame asyncFrame;
Object frameArg = frame.getArguments()[ASYNC_FRAME_ARG_INDEX];
if (frameArg instanceof MaterializedFrame) {
asyncFrame = (MaterializedFrame) frameArg;
} else {
asyncFrame = (VirtualFrame) ScopeFrameNode.getNonBlockScopeParentFrame(frame);
}
return getSavedStackTrace(asyncFrame);
}
}
@Child private SpecializedNewObjectNode createAsyncGeneratorObject;
@Child private PropertySetNode setGeneratorState;
@Child private PropertySetNode setGeneratorContext;
@Child private PropertySetNode setGeneratorTarget;
@Child private PropertySetNode setGeneratorQueue;
@CompilationFinal volatile RootCallTarget resumeTarget;
private final JSContext context;
@Child private JavaScriptNode functionBody;
@Child private JSWriteFrameSlotNode writeYieldValueNode;
@Child private JSReadFrameSlotNode readYieldResultNode;
@Child private JSWriteFrameSlotNode writeAsyncContext;
@Child private JSReadFrameSlotNode readAsyncContext;
public AsyncGeneratorBodyNode(JSContext context, JavaScriptNode body, JSWriteFrameSlotNode writeYieldValueNode, JSReadFrameSlotNode readYieldResultNode, JSWriteFrameSlotNode writeAsyncContext,
JSReadFrameSlotNode readAsyncContext) {
this.createAsyncGeneratorObject = SpecializedNewObjectNode.create(context, false, true, true, true);
this.setGeneratorState = PropertySetNode.createSetHidden(JSFunction.ASYNC_GENERATOR_STATE_ID, context);
this.setGeneratorContext = PropertySetNode.createSetHidden(JSFunction.ASYNC_GENERATOR_CONTEXT_ID, context);
this.setGeneratorTarget = PropertySetNode.createSetHidden(JSFunction.ASYNC_GENERATOR_TARGET_ID, context);
this.setGeneratorQueue = PropertySetNode.createSetHidden(JSFunction.ASYNC_GENERATOR_QUEUE_ID, context);
this.context = context;
this.writeAsyncContext = writeAsyncContext;
this.functionBody = Objects.requireNonNull(body);
this.writeYieldValueNode = Objects.requireNonNull(writeYieldValueNode);
this.readYieldResultNode = Objects.requireNonNull(readYieldResultNode);
this.readAsyncContext = Objects.requireNonNull(readAsyncContext);
}
public static JavaScriptNode create(JSContext context, JavaScriptNode body, JSWriteFrameSlotNode writeYieldValueNode, JSReadFrameSlotNode readYieldResultNode,
JSWriteFrameSlotNode writeAsyncContext, JSReadFrameSlotNode readAsyncContext) {
return new AsyncGeneratorBodyNode(context, body, writeYieldValueNode, readYieldResultNode, writeAsyncContext, readAsyncContext);
}
private void initializeCallTarget() {
CompilerAsserts.neverPartOfCompilation();
atomic(() -> {
if (resumeTarget == null) {
RootNode rootNode = getRootNode();
AsyncGeneratorRootNode asyncGeneratorRootNode = new AsyncGeneratorRootNode(context, functionBody, writeYieldValueNode, readYieldResultNode, readAsyncContext,
rootNode.getSourceSection(),
rootNode.getName());
this.resumeTarget = Truffle.getRuntime().createCallTarget(asyncGeneratorRootNode);
this.functionBody = null;
this.writeYieldValueNode = null;
this.readYieldResultNode = null;
this.readAsyncContext = null;
}
});
}
private void ensureCallTargetInitialized() {
if (resumeTarget == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
initializeCallTarget();
}
}
private void asyncGeneratorStart(VirtualFrame frame, DynamicObject generatorObject) {
MaterializedFrame materializedFrame = frame.materialize();
setGeneratorState.setValue(generatorObject, AsyncGeneratorState.SuspendedStart);
setGeneratorContext.setValue(generatorObject, materializedFrame);
setGeneratorTarget.setValue(generatorObject, resumeTarget);
setGeneratorQueue.setValue(generatorObject, new ArrayDeque<AsyncGeneratorRequest>(4));
writeAsyncContext.executeWrite(frame, AsyncRootNode.createAsyncContext(resumeTarget, generatorObject, materializedFrame));
}
@Override
public Object execute(VirtualFrame frame) {
ensureCallTargetInitialized();
DynamicObject generatorObject = createAsyncGeneratorObject.execute(frame, JSFrameUtil.getFunctionObject(frame));
asyncGeneratorStart(frame, generatorObject);
return generatorObject;
}
@Override
protected JavaScriptNode copyUninitialized(Set<Class<? extends Tag>> materializedTags) {
return atomic(() -> {
if (resumeTarget == null) {
return create(context, cloneUninitialized(functionBody, materializedTags),
cloneUninitialized(writeYieldValueNode, materializedTags),
cloneUninitialized(readYieldResultNode, materializedTags),
cloneUninitialized(writeAsyncContext, materializedTags),
cloneUninitialized(readAsyncContext, materializedTags));
} else {
AsyncGeneratorRootNode generatorRoot = (AsyncGeneratorRootNode) resumeTarget.getRootNode();
return create(context, cloneUninitialized(generatorRoot.functionBody, materializedTags),
cloneUninitialized(generatorRoot.writeYieldValue, materializedTags),
cloneUninitialized(generatorRoot.readYieldResult, materializedTags),
cloneUninitialized(writeAsyncContext, materializedTags),
cloneUninitialized(readAsyncContext, materializedTags));
}
});
}
}