net.sandius.rembulan.lib.impl.DefaultCoroutineLib Maven / Gradle / Ivy
/*
* Copyright 2016 Miroslav Janíček
*
* 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
*
* http://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 net.sandius.rembulan.lib.impl;
import net.sandius.rembulan.lib.CoroutineLib;
import net.sandius.rembulan.runtime.AbstractFunctionAnyArg;
import net.sandius.rembulan.runtime.Coroutine;
import net.sandius.rembulan.runtime.ExecutionContext;
import net.sandius.rembulan.runtime.LuaFunction;
import net.sandius.rembulan.runtime.ProtectedResumable;
import net.sandius.rembulan.runtime.ResolvedControlThrowable;
import net.sandius.rembulan.runtime.ReturnBuffer;
import net.sandius.rembulan.runtime.UnresolvedControlThrowable;
import net.sandius.rembulan.util.Check;
import java.util.ArrayList;
import java.util.Arrays;
public class DefaultCoroutineLib extends CoroutineLib {
@Override
protected LuaFunction _create() {
return Create.INSTANCE;
}
@Override
protected LuaFunction _resume() {
return Resume.INSTANCE;
}
@Override
protected LuaFunction _yield() {
return Yield.INSTANCE;
}
@Override
protected LuaFunction _isyieldable() {
return IsYieldable.INSTANCE;
}
@Override
protected LuaFunction _status() {
return Status.INSTANCE;
}
@Override
protected LuaFunction _running() {
return Running.INSTANCE;
}
@Override
protected LuaFunction _wrap() {
return Wrap.INSTANCE;
}
public static class Create extends AbstractLibFunction {
public static final Create INSTANCE = new Create();
@Override
protected String name() {
return "create";
}
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args) throws ResolvedControlThrowable {
LuaFunction func = args.nextFunction();
Coroutine c = context.newCoroutine(func);
context.getReturnBuffer().setTo(c);
}
}
public static class Resume extends AbstractLibFunction implements ProtectedResumable {
public static final Resume INSTANCE = new Resume();
@Override
protected String name() {
return "resume";
}
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args) throws ResolvedControlThrowable {
Coroutine coroutine = args.nextCoroutine();
Object[] resumeArgs = args.getTail();
context.getReturnBuffer().setTo();
try {
context.resume(coroutine, resumeArgs);
}
catch (UnresolvedControlThrowable ct) {
throw ct.resolve(this, null);
}
}
@Override
public void resume(ExecutionContext context, Object suspendedState) throws ResolvedControlThrowable {
ReturnBuffer rbuf = context.getReturnBuffer();
ArrayList