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 ToFloat extends ForeignToLLVM {
@Specialization
protected float fromInt(int value) {
return value;
}
@Specialization
protected float fromLong(long value) {
return value;
}
@Specialization
protected float fromChar(char value) {
return value;
}
@Specialization
protected float fromShort(short value) {
return value;
}
@Specialization
protected float fromByte(byte value) {
return value;
}
@Specialization
protected float fromFloat(float value) {
return value;
}
@Specialization
protected float fromDouble(double value) {
return (float) value;
}
@Specialization
protected float fromBoolean(boolean value) {
return (value ? 1.0f : 0.0f);
}
@Specialization
protected float fromString(String value) {
return getSingleStringCharacter(value);
}
@Specialization(limit = "5", guards = {"foreigns.isForeign(obj)", "interop.isNumber(foreigns.asForeign(obj))"})
protected float fromForeign(Object obj,
@CachedLibrary("obj") LLVMAsForeignLibrary foreigns,
@CachedLibrary(limit = "3") InteropLibrary interop,
@Cached BranchProfile exception) {
try {
return interop.asFloat(foreigns.asForeign(obj));
} catch (UnsupportedMessageException ex) {
exception.enter();
throw new LLVMPolyglotException(this, "Polyglot number can't be converted to float.");
}
}
@TruffleBoundary
static float slowPathPrimitiveConvert(ForeignToLLVM thiz, Object value) throws UnsupportedTypeException {
if (value instanceof Number) {
return ((Number) value).floatValue();
} else if (value instanceof Boolean) {
return (boolean) value ? 1.0f : 0.0f;
} else if (value instanceof Character) {
return (char) value;
} else if (value instanceof String) {
return thiz.getSingleStringCharacter((String) value);
} else {
try {
return InteropLibrary.getFactory().getUncached().asFloat(value);
} catch (UnsupportedMessageException ex) {
throw UnsupportedTypeException.create(new Object[]{value});
}
}
}
}