Skip to content

Commit d90e23b

Browse files
committed
add builtin oct
1 parent 320caf3 commit d90e23b

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/BuiltinFunctions.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
import static com.oracle.graal.python.nodes.BuiltinNames.MAX;
4848
import static com.oracle.graal.python.nodes.BuiltinNames.MIN;
4949
import static com.oracle.graal.python.nodes.BuiltinNames.NEXT;
50+
import static com.oracle.graal.python.nodes.BuiltinNames.OCT;
5051
import static com.oracle.graal.python.nodes.BuiltinNames.ORD;
5152
import static com.oracle.graal.python.nodes.BuiltinNames.POW;
5253
import static com.oracle.graal.python.nodes.BuiltinNames.PRINT;
@@ -286,6 +287,60 @@ protected static BinNode create() {
286287
}
287288
}
288289

290+
// oct(object)
291+
@Builtin(name = OCT, fixedNumOfPositionalArgs = 1)
292+
@TypeSystemReference(PythonArithmeticTypes.class)
293+
@GenerateNodeFactory
294+
public abstract static class OctNode extends PythonUnaryBuiltinNode {
295+
296+
public abstract String executeObject(Object x);
297+
298+
@TruffleBoundary
299+
private static String buildString(boolean isNegative, String number) {
300+
StringBuilder sb = new StringBuilder();
301+
if (isNegative) {
302+
sb.append('-');
303+
}
304+
sb.append("0o");
305+
sb.append(number);
306+
return sb.toString();
307+
}
308+
309+
@Specialization
310+
public String doL(long x) {
311+
return buildString(x < 0, longToOctString(x));
312+
}
313+
314+
@TruffleBoundary
315+
private static String longToOctString(long x) {
316+
return Long.toOctalString(Math.abs(x));
317+
}
318+
319+
@Specialization
320+
public String doD(double x) {
321+
throw raise(TypeError, "'%p' object cannot be interpreted as an integer", x);
322+
}
323+
324+
@Specialization
325+
@TruffleBoundary
326+
public String doPI(PInt x) {
327+
BigInteger value = x.getValue();
328+
return buildString(value.compareTo(BigInteger.ZERO) == -1, value.abs().toString(8));
329+
}
330+
331+
@Specialization
332+
public String doO(Object x,
333+
@Cached("create()") CastToIntegerFromIndexNode toIntNode,
334+
@Cached("create()") OctNode recursiveNode) {
335+
Object value = toIntNode.execute(x);
336+
return recursiveNode.executeObject(value);
337+
}
338+
339+
protected static OctNode create() {
340+
return BuiltinFunctionsFactory.OctNodeFactory.create();
341+
}
342+
}
343+
289344
// callable(object)
290345
@Builtin(name = CALLABLE, fixedNumOfPositionalArgs = 1)
291346
@GenerateNodeFactory

0 commit comments

Comments
 (0)