package com.oracle.truffle.llvm.runtime.interop.convert;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.interop.InteropLibrary;
import com.oracle.truffle.api.interop.UnsupportedMessageException;
import com.oracle.truffle.api.interop.UnsupportedTypeException;
import com.oracle.truffle.api.library.CachedLibrary;
import com.oracle.truffle.api.profiles.BranchProfile;
import com.oracle.truffle.llvm.runtime.except.LLVMPolyglotException;
import com.oracle.truffle.llvm.runtime.library.internal.LLVMAsForeignLibrary;
public abstract class ToI16 extends ForeignToLLVM {
@Specialization
protected short fromInt(int value) {
return (short) value;
}
@Specialization
protected short fromChar(char value) {
return (short) value;
}
@Specialization
protected short fromShort(short value) {
return value;
}
@Specialization
protected short fromLong(long value) {
return (short) value;
}
@Specialization
protected short fromByte(byte value) {
return value;
}
@Specialization
protected short fromFloat(float value) {
return (short) value;
}
@Specialization
protected short fromDouble(double value) {
return (short) value;
}
@Specialization
protected short fromBoolean(boolean value) {
return (short) (value ? 1 : 0);
}
@Specialization
protected short fromString(String value) {
return (short) getSingleStringCharacter(value);
}
@Specialization(limit = "5", guards = {"foreigns.isForeign(obj)", "interop.isNumber(foreigns.asForeign(obj))"})
protected short fromForeign(Object obj,
@CachedLibrary("obj") LLVMAsForeignLibrary foreigns,
@CachedLibrary(limit = "3") InteropLibrary interop,
@Cached BranchProfile exception) {
try {
return interop.asShort(foreigns.asForeign(obj));
} catch (UnsupportedMessageException ex) {
exception.enter();
throw new LLVMPolyglotException(this, "Polyglot number can't be converted to short.");
}
}
@TruffleBoundary
static short slowPathPrimitiveConvert(ForeignToLLVM thiz, Object value) throws UnsupportedTypeException {
if (value instanceof Number) {
return ((Number) value).shortValue();
} else if (value instanceof Boolean) {
return (short) ((boolean) value ? 1 : 0);
} else if (value instanceof Character) {
return (short) (char) value;
} else if (value instanceof String) {
return (short) thiz.getSingleStringCharacter((String) value);
} else {
try {
return InteropLibrary.getFactory().getUncached().asShort(value);
} catch (UnsupportedMessageException ex) {
throw UnsupportedTypeException.create(new Object[]{value});
}
}
}
}