Skip to content

Commit 8dfe17d

Browse files
committed
[GR-12597] Fix __getitem__ access with arbitrary keys for array-like foreign objects
PullRequest: graalpython/318
2 parents dfe6086 + bf8a047 commit 8dfe17d

File tree

2 files changed

+18
-11
lines changed

2 files changed

+18
-11
lines changed

graalpython/com.oracle.graal.python.test/src/tests/test_interop.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,3 +258,13 @@ def test_internal_languages_dont_eval():
258258
assert "internal language" in str(e)
259259

260260
assert polyglot.eval(language="python", string="21 * 2") == 42
261+
262+
def test_non_index_array_access():
263+
import java
264+
try:
265+
al = java.type("java.util.ArrayList")()
266+
assert al.size() == al["size"]()
267+
except IndexError:
268+
assert False, "using __getitem__ to access keys of an array-like foreign object should work"
269+
except NotImplementedError as e:
270+
assert "host lookup is not allowed" in str(e)

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/foreign/AccessForeignItemNodes.java

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -139,14 +139,18 @@ public Object doForeignObject(TruffleObject object, Object idx,
139139
}
140140

141141
private Object readForeignValue(TruffleObject object, Object key, Node foreignRead, boolean indexed) {
142-
Object index = indexed ? checkNumber(getIndexNode().executeObject(key)) : key;
142+
Object index = key;
143+
if (indexed) {
144+
// getIndexNode() is branch profile
145+
Object indexKey = getIndexNode().executeObject(key);
146+
if (object instanceof Number || PTypeToForeignNode.isBoxed(object)) {
147+
index = indexKey;
148+
}
149+
}
143150
try {
144151
return getToPythonNode().executeConvert(ForeignAccess.sendRead(foreignRead, object, getToForeignNode().executeConvert(index)));
145152
} catch (UnsupportedMessageException ex) {
146153
throw raise(AttributeError, "%s instance has no attribute '__getitem__'", object);
147-
} catch (IndexOutOfBoundsException ex) {
148-
// TODO remove this; workaround for TRegex
149-
throw raise(IndexError, "invalid index %s", index);
150154
} catch (UnknownIdentifierException ex) {
151155
if (indexed) {
152156
throw raise(IndexError, "invalid index %s", index);
@@ -156,13 +160,6 @@ private Object readForeignValue(TruffleObject object, Object key, Node foreignRe
156160
}
157161
}
158162

159-
private Object checkNumber(Object object) {
160-
if (object instanceof Number || PTypeToForeignNode.isBoxed(object)) {
161-
return object;
162-
}
163-
throw raiseIndexError();
164-
}
165-
166163
protected boolean isArray(TruffleObject o) {
167164
if (hasSizeNode == null) {
168165
CompilerDirectives.transferToInterpreterAndInvalidate();

0 commit comments

Comments
 (0)