Skip to content

Commit 5018139

Browse files
committed
[GR-73709] Add pyexpat java backend
PullRequest: graalpython/4288
2 parents bf43f88 + 9202456 commit 5018139

22 files changed

Lines changed: 2489 additions & 26 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ language runtime. The main focus is on user-observable behavior of the engine.
1717
* Add `polyglot.gil_locked_during_interop` context manager. By default, the global interpreter lock (GIL) is unlocked when interacting with objects from another language, to give other Python threads a chance to run in parallel. While this avoids potential deadlocks, repeated unlocking and locking of the GIL can decrease performance, so this context manager can be used to keep the lock held around short-running interop.
1818
* Add Github workflows that run our gates from the same job definitions as our internal CI. This will make it easier for contributors opening PRs on Github to ensure code contributions pass the same tests that we are running internally.
1919
* Added support for specifying generics on foreign classes, and inheriting from such classes. Especially when using Java classes that support generics, this allows expressing the generic types in Python type annotations as well.
20+
* Added a new `java` backend for the `pyexpat` module that uses a Java XML parser instead of the native `expat` library. It can be useful when running without native access or multiple-context scenarios. This backend is the default when embedding and can be switched back to native `expat` by setting `python.PyExpatModuleBackend` option to `native`. Standalone distribution still defaults to native expat backend.
2021

2122
## Version 25.0.1
2223
* Allow users to keep going on unsupported JDK/OS/ARCH combinations at their own risk by opting out of early failure using `-Dtruffle.UseFallbackRuntime=true`, `-Dpolyglot.engine.userResourceCache=/set/to/a/writeable/dir`, `-Dpolyglot.engine.allowUnsupportedPlatform=true`, and `-Dpolyglot.python.UnsupportedPlatformEmulates=[linux|macos|windows]` and `-Dorg.graalvm.python.resources.exclude=native.files`.

ci.jsonnet

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -159,11 +159,6 @@
159159
"python-unittest-arrow-storage": gpgate + require(GPY_JVM_STANDALONE) + platform_spec(no_jobs) + platform_spec({
160160
"linux:amd64:jdk-latest" : tier2,
161161
}),
162-
"python-unittest-posix": gpgate + platform_spec(no_jobs) + platform_spec({
163-
"linux:amd64:jdk-latest" : tier2 + require(GPY_JVM_STANDALONE),
164-
"linux:aarch64:jdk-latest" : tier3 + require(GPY_JVM_STANDALONE),
165-
"darwin:aarch64:jdk-latest" : tier3 + require(GPY_JVM_STANDALONE),
166-
}),
167162
"python-unittest-standalone": gpgate_maven + platform_spec(no_jobs) + platform_spec({
168163
"linux:amd64:jdk21" : daily + t("02:00:00") + require(GPY_JVM21_STANDALONE),
169164
"linux:aarch64:jdk21" : daily + t("02:00:00") + require(GPY_JVM21_STANDALONE),
@@ -277,9 +272,11 @@
277272
"style-ecj": style_gate + task_spec({ tags:: "style,ecjbuild" }) + platform_spec(no_jobs) + platform_spec({
278273
"linux:amd64:jdk-latest" : tier1,
279274
}),
280-
// tests with sandboxed backends for various modules (posix, sha3, ctypes, ...)
275+
// tests with sandboxed backends for various modules (posix, sha3, compression, pyexpat, ...)
281276
"python-unittest-sandboxed": gpgate_ee + platform_spec(no_jobs) + platform_spec({
282-
"linux:amd64:jdk-latest" : tier3,
277+
"linux:amd64:jdk-latest" : tier2,
278+
"linux:aarch64:jdk-latest" : tier3,
279+
"darwin:aarch64:jdk-latest" : tier3,
283280
}),
284281
"python-svm-unittest-sandboxed": gpgate_ee + platform_spec(no_jobs) + platform_spec({
285282
"linux:amd64:jdk-latest" : tier3 + provide(GPYEE_NATIVE_STANDALONE),

graalpython/com.oracle.graal.python.shell/src/com/oracle/graal/python/shell/GraalPythonMain.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ protected List<String> preprocessArguments(List<String> givenArgs, Map<String, S
182182
boolean posixBackendSpecified = false;
183183
boolean sha3BackendSpecified = false;
184184
boolean compressionBackendSpecified = false;
185+
boolean pyExpatBackendSpecified = false;
185186
boolean installSignalHandlersSpecified = false;
186187
boolean isolateNativeModulesSpecified = false;
187188
for (Iterator<String> argumentIterator = arguments.iterator(); argumentIterator.hasNext();) {
@@ -272,7 +273,8 @@ protected List<String> preprocessArguments(List<String> givenArgs, Map<String, S
272273
matchesPythonOption(arg, "CAPI") ||
273274
matchesPythonOption(arg, "PosixModuleBackend") ||
274275
matchesPythonOption(arg, "Sha3ModuleBackend") ||
275-
matchesPythonOption(arg, "CompressionModulesBackend")) {
276+
matchesPythonOption(arg, "CompressionModulesBackend") ||
277+
matchesPythonOption(arg, "PyExpatModuleBackend")) {
276278
addRelaunchArg(arg);
277279
}
278280
if (matchesPythonOption(arg, "PosixModuleBackend")) {
@@ -284,6 +286,9 @@ protected List<String> preprocessArguments(List<String> givenArgs, Map<String, S
284286
if (matchesPythonOption(arg, "CompressionModulesBackend")) {
285287
compressionBackendSpecified = true;
286288
}
289+
if (matchesPythonOption(arg, "PyExpatModuleBackend")) {
290+
pyExpatBackendSpecified = true;
291+
}
287292
if (matchesPythonOption(arg, "InstallSignalHandlers")) {
288293
installSignalHandlersSpecified = true;
289294
}
@@ -451,6 +456,9 @@ protected List<String> preprocessArguments(List<String> givenArgs, Map<String, S
451456
if (!compressionBackendSpecified) {
452457
polyglotOptions.put("python.CompressionModulesBackend", "native");
453458
}
459+
if (!pyExpatBackendSpecified) {
460+
polyglotOptions.put("python.PyExpatModuleBackend", "native");
461+
}
454462
if (!installSignalHandlersSpecified) {
455463
polyglotOptions.put("python.InstallSignalHandlers", "true");
456464
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Copyright (c) 2026, 2026, Oracle and/or its affiliates. All rights reserved.
2+
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3+
#
4+
# The Universal Permissive License (UPL), Version 1.0
5+
#
6+
# Subject to the condition set forth below, permission is hereby granted to any
7+
# person obtaining a copy of this software, associated documentation and/or
8+
# data (collectively the "Software"), free of charge and under any and all
9+
# copyright rights in the Software, and any and all patent rights owned or
10+
# freely licensable by each licensor hereunder covering either (i) the
11+
# unmodified Software as contributed to or provided by such licensor, or (ii)
12+
# the Larger Works (as defined below), to deal in both
13+
#
14+
# (a) the Software, and
15+
#
16+
# (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
17+
# one is included with the Software each a "Larger Work" to which the Software
18+
# is contributed by such licensors),
19+
#
20+
# without restriction, including without limitation the rights to copy, create
21+
# derivative works of, display, perform, and distribute the Software and make,
22+
# use, sell, offer for sale, import, export, have made, and have sold the
23+
# Software and the Larger Work(s), and to sublicense the foregoing rights on
24+
# either these or other terms.
25+
#
26+
# This license is subject to the following condition:
27+
#
28+
# The above copyright notice and either this complete permission notice or at a
29+
# minimum a reference to the UPL must be included in all copies or substantial
30+
# portions of the Software.
31+
#
32+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
33+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
35+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
36+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
37+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
38+
# SOFTWARE.
39+
40+
import unittest
41+
from xml.parsers import expat
42+
43+
44+
class PyExpatXmlTest(unittest.TestCase):
45+
46+
def test_xml_decl_handler_not_called_without_xml_declaration(self):
47+
parser = expat.ParserCreate()
48+
xml_decl_calls = []
49+
50+
parser.XmlDeclHandler = lambda *args: xml_decl_calls.append(args)
51+
parser.Parse(b"<doc/>", True)
52+
53+
self.assertEqual([], xml_decl_calls)
54+
55+
def test_parser_create_encoding_is_used_for_byte_input(self):
56+
parser = expat.ParserCreate(encoding="iso-8859-1")
57+
character_data = []
58+
59+
parser.CharacterDataHandler = character_data.append
60+
parser.Parse(b"<doc>\xe9</doc>", True)
61+
62+
self.assertEqual(["\xe9"], character_data)
63+
64+
def test_external_doctype_reports_no_internal_subset(self):
65+
parser = expat.ParserCreate()
66+
doctype_calls = []
67+
68+
parser.StartDoctypeDeclHandler = lambda *args: doctype_calls.append(args)
69+
parser.ExternalEntityRefHandler = lambda *args: 1
70+
parser.Parse(b'<!DOCTYPE doc SYSTEM "x.dtd"><doc/>', True)
71+
72+
self.assertEqual([("doc", "x.dtd", None, 0)], doctype_calls)
73+
74+
75+
if __name__ == '__main__':
76+
unittest.main()

graalpython/com.oracle.graal.python/src/META-INF/native-image/org.graalvm.python/python-language/reflect-config.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,15 @@
6565
}
6666
]
6767
},
68+
{
69+
"name": "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl",
70+
"methods": [
71+
{
72+
"name": "<init>",
73+
"parameterTypes": []
74+
}
75+
]
76+
},
6877
{
6978
"name": "com.sun.crypto.provider.AESCipher$General",
7079
"methods": [
Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
{
2-
"resources":[
3-
{"pattern":"org/graalvm/shadowed/org/jline.*"}
2+
"resources": [
3+
{
4+
"pattern": "org/graalvm/shadowed/org/jline.*"
5+
},
6+
{
7+
"pattern": "com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties"
8+
}
49
]
510
}

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/Python3Core.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@
9898
import com.oracle.graal.python.builtins.modules.PosixShMemModuleBuiltins;
9999
import com.oracle.graal.python.builtins.modules.PosixSubprocessModuleBuiltins;
100100
import com.oracle.graal.python.builtins.modules.PwdModuleBuiltins;
101+
import com.oracle.graal.python.builtins.modules.pyexpat.PyExpatModuleBuiltins;
101102
import com.oracle.graal.python.builtins.modules.QueueModuleBuiltins;
102103
import com.oracle.graal.python.builtins.modules.RandomModuleBuiltins;
103104
import com.oracle.graal.python.builtins.modules.ReadlineModuleBuiltins;
@@ -365,6 +366,7 @@
365366
import com.oracle.graal.python.builtins.objects.tuple.InstantiableStructSequenceBuiltins;
366367
import com.oracle.graal.python.builtins.objects.tuple.StructSequenceBuiltins;
367368
import com.oracle.graal.python.builtins.objects.tuple.TupleBuiltins;
369+
import com.oracle.graal.python.builtins.modules.pyexpat.XMLParserBuiltins;
368370
import com.oracle.graal.python.builtins.objects.tuple.TupleGetterBuiltins;
369371
import com.oracle.graal.python.builtins.objects.type.PythonBuiltinClass;
370372
import com.oracle.graal.python.builtins.objects.type.PythonManagedClass;
@@ -659,8 +661,10 @@ private static PythonBuiltins[] initializeBuiltins(TruffleLanguage.Env env) {
659661
new JavaModuleBuiltins(),
660662
new JArrayModuleBuiltins(),
661663
new CSVModuleBuiltins(),
664+
new PyExpatModuleBuiltins(),
662665
new JSONModuleBuiltins(),
663666
new SREModuleBuiltins(),
667+
new XMLParserBuiltins(),
664668
new AstModuleBuiltins(),
665669
PythonImageBuildOptions.WITHOUT_NATIVE_POSIX && (PythonImageBuildOptions.WITHOUT_JAVA_INET || !env.isSocketIOAllowed()) ? null : new SelectModuleBuiltins(),
666670
PythonImageBuildOptions.WITHOUT_NATIVE_POSIX && (PythonImageBuildOptions.WITHOUT_JAVA_INET || !env.isSocketIOAllowed()) ? null : new SocketModuleBuiltins(),

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/PythonBuiltinClassType.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@
129129
import com.oracle.graal.python.builtins.modules.pickle.PicklerMemoProxyBuiltins;
130130
import com.oracle.graal.python.builtins.modules.pickle.UnpicklerBuiltins;
131131
import com.oracle.graal.python.builtins.modules.pickle.UnpicklerMemoProxyBuiltins;
132+
import com.oracle.graal.python.builtins.modules.pyexpat.XMLParserBuiltins;
132133
import com.oracle.graal.python.builtins.modules.re.MatchBuiltins;
133134
import com.oracle.graal.python.builtins.modules.re.PatternBuiltins;
134135
import com.oracle.graal.python.builtins.modules.weakref.ProxyTypeBuiltins;
@@ -777,6 +778,7 @@ It can be called either on the class (e.g. C.f()) or on an instance
777778
TimeoutError("TimeoutError", OSError, newBuilder().publishInModule(J_BUILTINS).basetype().addDict()),
778779
ZLibError("error", Exception, newBuilder().publishInModule("zlib").basetype().addDict()),
779780
CSVError("Error", Exception, newBuilder().publishInModule("_csv").basetype().addDict()),
781+
PyExpatError("error", Exception, newBuilder().publishInModule("pyexpat").basetype().addDict()),
780782
LZMAError("LZMAError", Exception, newBuilder().publishInModule("_lzma").basetype().addDict()),
781783
StructError("StructError", Exception, newBuilder().publishInModule(J__STRUCT).basetype().addDict()),
782784
PickleError("PickleError", Exception, newBuilder().publishInModule("_pickle").basetype().addDict()),
@@ -1171,6 +1173,11 @@ def takewhile(predicate, iterable):
11711173
PythonObject,
11721174
newBuilder().publishInModule("_json").basetype().slots(JSONEncoderBuiltins.SLOTS).doc("""
11731175
_iterencode(obj, _current_indent_level) -> iterable""")),
1176+
XMLParser(
1177+
"xmlparser",
1178+
PythonObject,
1179+
newBuilder().publishInModule("pyexpat").basetype().disallowInstantiation().slots(XMLParserBuiltins.SLOTS).doc("""
1180+
pyexpat XML parser object""")),
11741181

11751182
// datetime
11761183
PDate(

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
import static com.oracle.graal.python.nodes.BuiltinNames.J___GRAALPYTHON__;
5353
import static com.oracle.graal.python.nodes.BuiltinNames.T_FORMAT;
5454
import static com.oracle.graal.python.nodes.BuiltinNames.T_MTIME;
55+
import static com.oracle.graal.python.nodes.BuiltinNames.T_PYEXPAT;
5556
import static com.oracle.graal.python.nodes.BuiltinNames.T_SHA3;
5657
import static com.oracle.graal.python.nodes.BuiltinNames.T_SIZE;
5758
import static com.oracle.graal.python.nodes.BuiltinNames.T__IMP;
@@ -935,6 +936,15 @@ TruffleString sha3ModuleBackend() {
935936
}
936937
}
937938

939+
@Builtin(name = "pyexpat_module_backend", minNumOfPositionalArgs = 0)
940+
@GenerateNodeFactory
941+
public abstract static class PyExpatModuleBackendNode extends PythonBuiltinNode {
942+
@Specialization
943+
TruffleString pyexpatModuleBackend() {
944+
return getContext().lookupBuiltinModule(T_PYEXPAT) == null ? T_NATIVE : T_JAVA;
945+
}
946+
}
947+
938948
@Builtin(name = "time_millis", minNumOfPositionalArgs = 0, maxNumOfPositionalArgs = 1, doc = "Like time.time() but in milliseconds resolution.")
939949
@GenerateNodeFactory
940950
public abstract static class TimeMillis extends PythonUnaryBuiltinNode {

0 commit comments

Comments
 (0)