Skip to content

Commit aa0ea11

Browse files
committed
[GR-24112] Ord build in function doesn't work with multi byte character.
1 parent 6a2611b commit aa0ea11

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,16 @@ def test_getitem_typeerror(self):
5050
def test_ascii(self):
5151
self.assertEqual(ascii(1), "1")
5252
self.assertEqual(ascii("錦蛇 \t \0 a \x03"), "'\\u9326\\u86c7 \\t \\x00 a \\x03'")
53+
54+
def test_chr(self):
55+
self.assertEqual(chr(32), ' ')
56+
self.assertEqual(chr(97), 'a')
57+
self.assertEqual(chr(0xfff), '\u0fff')
58+
self.assertEqual(chr(0xf0000), '\U000f0000')
59+
60+
def test_ord(self):
61+
self.assertEqual(ord(' '), 32)
62+
self.assertEqual(ord('a'), 97)
63+
self.assertEqual(ord('\u0fff'), 0xfff)
64+
self.assertEqual(ord('\U000f0000'), 0xf0000)
65+

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

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,7 @@ public abstract static class ChrNode extends PythonBuiltinNode {
425425
@Specialization
426426
public String charFromInt(int arg) {
427427
if (arg >= 0 && arg <= 1114111) {
428-
return Character.toString((char) arg);
428+
return new String(Character.toChars(arg));
429429
} else {
430430
throw raise(ValueError, ErrorMessages.ARG_NOT_IN_RANGE, "chr()", "0x110000");
431431
}
@@ -1508,16 +1508,24 @@ protected static NextNode create() {
15081508
public abstract static class OrdNode extends PythonBuiltinNode {
15091509

15101510
@Specialization
1511+
@TruffleBoundary
15111512
public int ord(String chr) {
1512-
if (chr.length() != 1) {
1513+
if (chr.codePointCount(0, chr.length()) != 1) {
15131514
throw raise(TypeError, ErrorMessages.EXPECTED_CHARACTER_BUT_STRING_FOUND, "ord()", chr.length());
15141515
}
1515-
return chr.charAt(0);
1516+
return chr.codePointAt(0);
15161517
}
15171518

15181519
@Specialization
1519-
public int ord(PString chr) {
1520-
return ord(chr.getValue());
1520+
public int ord(PString pchr,
1521+
@Cached CastToJavaStringNode castToJavaStringNode) {
1522+
String chr;
1523+
try {
1524+
chr = castToJavaStringNode.execute(pchr);
1525+
} catch (CannotCastException e) {
1526+
throw CompilerDirectives.shouldNotReachHere(e);
1527+
}
1528+
return ord(chr);
15211529
}
15221530

15231531
@Specialization

0 commit comments

Comments
 (0)