Skip to content

Commit 3d6204a

Browse files
committed
[GR-34999] intrinsify exceptions.py
PullRequest: graalpython/2036
2 parents a7aab78 + 7f031bb commit 3d6204a

File tree

89 files changed

+2892
-943
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

89 files changed

+2892
-943
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ def test_oserror_four_attribute(self):
154154
self.assertEqual(e.filename, "file1")
155155
self.assertEqual(e.filename2, None)
156156

157-
def test_oserror_four_attribute(self):
157+
def test_oserror_four_attribute_2(self):
158158
e = OSError(errno.EISDIR, "message", "file1", None, "file2")
159159
self.assertEqual(e.errno, 21)
160160
self.assertEqual(e.strerror, "message")

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,12 @@
3939

4040
String doc() default "";
4141

42+
/**
43+
* Most builtins are not OS specific. If specified, the builtin is included only if the os
44+
* matches
45+
*/
46+
PythonOS os() default PythonOS.PLATFORM_ANY;
47+
4248
PythonBuiltinClassType constructsClass() default PythonBuiltinClassType.nil;
4349

4450
PythonBuiltinClassType[] base() default {};

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,12 @@
3232
public @interface CoreFunctions {
3333
String defineModule() default "";
3434

35+
/**
36+
* Most builtins are not OS specific. If specified, the builtin is included only if the os
37+
* matches
38+
*/
39+
PythonOS os() default PythonOS.PLATFORM_ANY;
40+
3541
String publicName() default "";
3642

3743
PythonBuiltinClassType[] extendClasses() default {};

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

Lines changed: 48 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727

2828
import static com.oracle.graal.python.builtins.PythonBuiltinClassType.IndentationError;
2929
import static com.oracle.graal.python.builtins.PythonBuiltinClassType.TabError;
30+
import static com.oracle.graal.python.builtins.objects.exception.SyntaxErrorBuiltins.SYNTAX_ERROR_ATTR_FACTORY;
3031
import static com.oracle.graal.python.nodes.BuiltinNames.MODULES;
3132
import static com.oracle.graal.python.nodes.BuiltinNames.PRINT;
3233
import static com.oracle.graal.python.nodes.SpecialAttributeNames.__PACKAGE__;
@@ -45,7 +46,6 @@
4546
import java.util.regex.Matcher;
4647
import java.util.regex.Pattern;
4748

48-
import com.oracle.graal.python.builtins.objects.exception.SystemExitBuiltins;
4949
import org.graalvm.nativeimage.ImageInfo;
5050

5151
import com.oracle.graal.python.PythonLanguage;
@@ -160,7 +160,6 @@
160160
import com.oracle.graal.python.builtins.modules.zlib.ZlibCompressBuiltins;
161161
import com.oracle.graal.python.builtins.modules.zlib.ZlibDecompressBuiltins;
162162
import com.oracle.graal.python.builtins.objects.NotImplementedBuiltins;
163-
import com.oracle.graal.python.builtins.objects.PNone;
164163
import com.oracle.graal.python.builtins.objects.array.ArrayBuiltins;
165164
import com.oracle.graal.python.builtins.objects.bool.BoolBuiltins;
166165
import com.oracle.graal.python.builtins.objects.bytes.ByteArrayBuiltins;
@@ -180,7 +179,16 @@
180179
import com.oracle.graal.python.builtins.objects.ellipsis.EllipsisBuiltins;
181180
import com.oracle.graal.python.builtins.objects.enumerate.EnumerateBuiltins;
182181
import com.oracle.graal.python.builtins.objects.exception.BaseExceptionBuiltins;
182+
import com.oracle.graal.python.builtins.objects.exception.ImportErrorBuiltins;
183+
import com.oracle.graal.python.builtins.objects.exception.OsErrorBuiltins;
183184
import com.oracle.graal.python.builtins.objects.exception.PBaseException;
185+
import com.oracle.graal.python.builtins.objects.exception.StopIterationBuiltins;
186+
import com.oracle.graal.python.builtins.objects.exception.SyntaxErrorBuiltins;
187+
import com.oracle.graal.python.builtins.objects.exception.SystemExitBuiltins;
188+
import com.oracle.graal.python.builtins.objects.exception.UnicodeDecodeErrorBuiltins;
189+
import com.oracle.graal.python.builtins.objects.exception.UnicodeEncodeErrorBuiltins;
190+
import com.oracle.graal.python.builtins.objects.exception.UnicodeErrorBuiltins;
191+
import com.oracle.graal.python.builtins.objects.exception.UnicodeTranslateErrorBuiltins;
184192
import com.oracle.graal.python.builtins.objects.floats.FloatBuiltins;
185193
import com.oracle.graal.python.builtins.objects.floats.PFloat;
186194
import com.oracle.graal.python.builtins.objects.foreign.ForeignObjectBuiltins;
@@ -342,9 +350,11 @@ private static String[] initializeCoreFiles() {
342350
// add service loader defined python file extensions
343351
if (!ImageInfo.inImageRuntimeCode()) {
344352
ServiceLoader<PythonBuiltins> providers = ServiceLoader.load(PythonBuiltins.class, Python3Core.class.getClassLoader());
353+
PythonOS currentOs = PythonOS.getPythonOS();
345354
for (PythonBuiltins builtin : providers) {
346355
CoreFunctions annotation = builtin.getClass().getAnnotation(CoreFunctions.class);
347-
if (!annotation.pythonFile().isEmpty()) {
356+
if (!annotation.pythonFile().isEmpty() &&
357+
(annotation.os() == PythonOS.PLATFORM_ANY || annotation.os() == currentOs)) {
348358
coreFiles.add(annotation.pythonFile());
349359
}
350360
}
@@ -374,6 +384,16 @@ private static String[] initializeCoreFiles() {
374384
c = null;
375385
}
376386

387+
private static void filterBuiltins(List<PythonBuiltins> builtins) {
388+
PythonOS currentOs = PythonOS.getPythonOS();
389+
for (PythonBuiltins builtin : builtins) {
390+
CoreFunctions annotation = builtin.getClass().getAnnotation(CoreFunctions.class);
391+
if (annotation.os() != PythonOS.PLATFORM_ANY && annotation.os() != currentOs) {
392+
builtins.remove(builtin);
393+
}
394+
}
395+
}
396+
377397
private static PythonBuiltins[] initializeBuiltins(boolean nativeAccessAllowed) {
378398
List<PythonBuiltins> builtins = new ArrayList<>(Arrays.asList(
379399
new BuiltinConstructors(),
@@ -452,6 +472,14 @@ private static PythonBuiltins[] initializeBuiltins(boolean nativeAccessAllowed)
452472
new WarningsModuleBuiltins(),
453473
// exceptions
454474
new SystemExitBuiltins(),
475+
new ImportErrorBuiltins(),
476+
new StopIterationBuiltins(),
477+
new SyntaxErrorBuiltins(),
478+
new OsErrorBuiltins(),
479+
new UnicodeErrorBuiltins(),
480+
new UnicodeEncodeErrorBuiltins(),
481+
new UnicodeDecodeErrorBuiltins(),
482+
new UnicodeTranslateErrorBuiltins(),
455483

456484
// io
457485
new IOModuleBuiltins(),
@@ -625,6 +653,7 @@ private static PythonBuiltins[] initializeBuiltins(boolean nativeAccessAllowed)
625653
builtins.add(builtin);
626654
}
627655
}
656+
filterBuiltins(builtins);
628657
return builtins.toArray(new PythonBuiltins[builtins.size()]);
629658
}
630659

@@ -762,7 +791,7 @@ public final void postInitialize() {
762791

763792
for (PythonBuiltins builtin : builtins) {
764793
CoreFunctions annotation = builtin.getClass().getAnnotation(CoreFunctions.class);
765-
if (annotation.isEager()) {
794+
if (annotation.isEager() || annotation.extendClasses().length != 0) {
766795
builtin.postInitialize(this);
767796
}
768797
}
@@ -792,6 +821,11 @@ public final PythonModule getBuiltins() {
792821
return builtinsModule;
793822
}
794823

824+
public final void registerTypeInBuiltins(String name, PythonBuiltinClassType type) {
825+
assert builtinsModule != null : "builtins module was not yet initialized: cannot register type";
826+
builtinsModule.setAttribute(name, lookupType(type));
827+
}
828+
795829
public final PythonModule getSysModule() {
796830
return sysModule;
797831
}
@@ -1056,16 +1090,13 @@ public final RuntimeException raiseInvalidSyntax(PythonParser.ErrorType type, No
10561090
break;
10571091
}
10581092
instance = factory().createBaseException(cls, message, arguments);
1093+
final Object[] excAttrs = SYNTAX_ERROR_ATTR_FACTORY.create();
10591094
SourceSection section = location.getSourceSection();
10601095
Source source = section.getSource();
10611096
String path = source.getPath();
1062-
instance.setAttribute("filename", path != null ? path : source.getName() != null ? source.getName() : "<string>");
1063-
// Not very nice. This counts on the implementation in traceback.py where if the value of
1064-
// text attribute
1065-
// is NONE, then the line is not printed
1066-
instance.setAttribute("text", section.isAvailable() ? source.getCharacters(section.getStartLine()) : PNone.NONE);
1067-
instance.setAttribute("lineno", section.getStartLine());
1068-
instance.setAttribute("offset", section.getStartColumn());
1097+
excAttrs[SyntaxErrorBuiltins.IDX_FILENAME] = (path != null) ? path : source.getName() != null ? source.getName() : "<string>";
1098+
excAttrs[SyntaxErrorBuiltins.IDX_LINENO] = section.getStartLine();
1099+
excAttrs[SyntaxErrorBuiltins.IDX_OFFSET] = section.getStartColumn();
10691100
String msg = "invalid syntax";
10701101
if (type == PythonParser.ErrorType.Print) {
10711102
CharSequence line = source.getCharacters(section.getStartLine());
@@ -1086,7 +1117,12 @@ public final RuntimeException raiseInvalidSyntax(PythonParser.ErrorType type, No
10861117
} else if (message != null) {
10871118
msg = (new ErrorMessageFormatter()).format(message, arguments);
10881119
}
1089-
instance.setAttribute("msg", msg);
1120+
// Not very nice. This counts on the implementation in traceback.py where if the value of
1121+
// text attribute is NONE, then the line is not printed
1122+
final String text = section.isAvailable() ? source.getCharacters(section.getStartLine()).toString() : null;
1123+
excAttrs[SyntaxErrorBuiltins.IDX_MSG] = msg;
1124+
excAttrs[SyntaxErrorBuiltins.IDX_TEXT] = text;
1125+
instance.setExceptionAttributes(excAttrs);
10901126
throw PException.fromObject(instance, location, PythonOptions.isPExceptionWithJavaStacktrace(getLanguage()));
10911127
}
10921128

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ public enum PythonBuiltinClassType implements TruffleObject {
104104
PDictValueIterator(DICT_VALUEITERATOR, Flags.PRIVATE_DERIVED_WODICT),
105105
PDictReverseValueIterator(DICT_REVERSE_VALUEITERATOR, Flags.PRIVATE_DERIVED_WODICT),
106106
PDictValuesView(DICT_VALUES, Flags.PRIVATE_DERIVED_WODICT),
107-
PEllipsis("ellipsis", Flags.PRIVATE_DERIVED_WODICT),
107+
PEllipsis("ellipsis", BUILTINS, Flags.PRIVATE_DERIVED_WODICT),
108108
PEnumerate("enumerate", BUILTINS),
109109
PMap("map", BUILTINS),
110110
PFloat("float", BUILTINS),

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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -130,15 +130,18 @@ public void postInitialize(@SuppressWarnings("unused") Python3Core core) {
130130
private void initializeEachFactoryWith(BiConsumer<NodeFactory<? extends PythonBuiltinBaseNode>, Builtin> func) {
131131
List<? extends NodeFactory<? extends PythonBuiltinBaseNode>> factories = getNodeFactories();
132132
assert factories != null : "No factories found. Override getFactories() to resolve this.";
133+
PythonOS currentOs = PythonOS.getPythonOS();
133134
for (NodeFactory<? extends PythonBuiltinBaseNode> factory : factories) {
134135
Boolean needsFrame = null;
135136
for (Builtin builtin : factory.getNodeClass().getAnnotationsByType(Builtin.class)) {
136-
if (needsFrame == null) {
137-
needsFrame = builtin.needsFrame();
138-
} else if (needsFrame != builtin.needsFrame()) {
139-
throw new IllegalStateException(String.format("Implementation error in %s: all @Builtin annotations must agree if the node needs a frame.", factory.getNodeClass().getName()));
137+
if (builtin.os() == PythonOS.PLATFORM_ANY || builtin.os() == currentOs) {
138+
if (needsFrame == null) {
139+
needsFrame = builtin.needsFrame();
140+
} else if (needsFrame != builtin.needsFrame()) {
141+
throw new IllegalStateException(String.format("Implementation error in %s: all @Builtin annotations must agree if the node needs a frame.", factory.getNodeClass().getName()));
142+
}
143+
func.accept(factory, builtin);
140144
}
141-
func.accept(factory, builtin);
142145
}
143146
}
144147
}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+
*
5+
* The Universal Permissive License (UPL), Version 1.0
6+
*
7+
* Subject to the condition set forth below, permission is hereby granted to any
8+
* person obtaining a copy of this software, associated documentation and/or
9+
* data (collectively the "Software"), free of charge and under any and all
10+
* copyright rights in the Software, and any and all patent rights owned or
11+
* freely licensable by each licensor hereunder covering either (i) the
12+
* unmodified Software as contributed to or provided by such licensor, or (ii)
13+
* the Larger Works (as defined below), to deal in both
14+
*
15+
* (a) the Software, and
16+
*
17+
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
18+
* one is included with the Software each a "Larger Work" to which the Software
19+
* is contributed by such licensors),
20+
*
21+
* without restriction, including without limitation the rights to copy, create
22+
* derivative works of, display, perform, and distribute the Software and make,
23+
* use, sell, offer for sale, import, export, have made, and have sold the
24+
* Software and the Larger Work(s), and to sublicense the foregoing rights on
25+
* either these or other terms.
26+
*
27+
* This license is subject to the following condition:
28+
*
29+
* The above copyright notice and either this complete permission notice or at a
30+
* minimum a reference to the UPL must be included in all copies or substantial
31+
* portions of the Software.
32+
*
33+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
39+
* SOFTWARE.
40+
*/
41+
package com.oracle.graal.python.builtins;
42+
43+
import com.oracle.truffle.api.CompilerDirectives;
44+
45+
public enum PythonOS {
46+
PLATFORM_JAVA("java"),
47+
PLATFORM_CYGWIN("cygwin"),
48+
PLATFORM_LINUX("linux"),
49+
PLATFORM_DARWIN("darwin"),
50+
PLATFORM_WIN32("win32"),
51+
PLATFORM_SUNOS("sunos"),
52+
PLATFORM_FREEBSD("freebsd"),
53+
PLATFORM_ANY(null);
54+
55+
private final String name;
56+
57+
PythonOS(String name) {
58+
this.name = name;
59+
}
60+
61+
public String getName() {
62+
return name;
63+
}
64+
65+
@CompilerDirectives.TruffleBoundary
66+
public static PythonOS getPythonOS() {
67+
String property = System.getProperty("os.name");
68+
PythonOS os = PLATFORM_JAVA;
69+
if (property != null) {
70+
if (property.toLowerCase().contains("cygwin")) {
71+
os = PLATFORM_CYGWIN;
72+
} else if (property.toLowerCase().contains("linux")) {
73+
os = PLATFORM_LINUX;
74+
} else if (property.toLowerCase().contains("mac")) {
75+
os = PLATFORM_DARWIN;
76+
} else if (property.toLowerCase().contains("windows")) {
77+
os = PLATFORM_WIN32;
78+
} else if (property.toLowerCase().contains("sunos")) {
79+
os = PLATFORM_SUNOS;
80+
} else if (property.toLowerCase().contains("freebsd")) {
81+
os = PLATFORM_FREEBSD;
82+
}
83+
}
84+
return os;
85+
}
86+
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727

2828
import static com.oracle.graal.python.nodes.ErrorMessages.S_TAKES_AT_LEAST_D_ARGUMENTS_D_GIVEN;
2929
import static com.oracle.graal.python.nodes.ErrorMessages.S_TAKES_AT_MOST_D_ARGUMENTS_D_GIVEN;
30-
import static com.oracle.graal.python.nodes.ErrorMessages.TAKES_NO_KEYWORD_ARGS;
30+
import static com.oracle.graal.python.nodes.ErrorMessages.S_TAKES_NO_KEYWORD_ARGS;
3131
import static com.oracle.graal.python.runtime.exception.PythonErrorType.MemoryError;
3232
import static com.oracle.graal.python.runtime.exception.PythonErrorType.TypeError;
3333
import static com.oracle.graal.python.runtime.exception.PythonErrorType.ValueError;
@@ -138,7 +138,7 @@ Object error(Object cls, Object[] args, PKeyword[] kwargs) {
138138
private void checkKwargs(Object cls, PKeyword[] kwargs, IsBuiltinClassProfile isNotSubtypeProfile) {
139139
if (isNotSubtypeProfile.profileClass(cls, PythonBuiltinClassType.PArray)) {
140140
if (kwargs.length != 0) {
141-
throw raise(TypeError, TAKES_NO_KEYWORD_ARGS, "array.array()");
141+
throw raise(TypeError, S_TAKES_NO_KEYWORD_ARGS, "array.array()");
142142
}
143143
}
144144
}

0 commit comments

Comments
 (0)