|
71 | 71 | import static com.oracle.graal.python.runtime.exception.PythonErrorType.ValueError;
|
72 | 72 |
|
73 | 73 | import java.math.BigInteger;
|
| 74 | +import java.nio.charset.Charset; |
74 | 75 | import java.util.List;
|
75 | 76 |
|
| 77 | +import com.oracle.graal.python.PythonFileDetector; |
76 | 78 | import com.oracle.graal.python.PythonLanguage;
|
77 | 79 | import com.oracle.graal.python.builtins.Builtin;
|
78 | 80 | import com.oracle.graal.python.builtins.CoreFunctions;
|
@@ -719,9 +721,23 @@ public CompileNode() {
|
719 | 721 | public abstract PCode execute(VirtualFrame frame, Object source, String filename, String mode, Object kwFlags, Object kwDontInherit, Object kwOptimize);
|
720 | 722 |
|
721 | 723 | @Specialization
|
722 |
| - PCode compile(VirtualFrame frame, PBytes source, String filename, String mode, Object kwFlags, Object kwDontInherit, Object kwOptimize, |
| 724 | + PCode compile(VirtualFrame frame, PBytes pBytes, String filename, String mode, Object kwFlags, Object kwDontInherit, Object kwOptimize, |
723 | 725 | @Cached("create()") BytesNodes.ToBytesNode toBytesNode) {
|
724 |
| - return compile(createString(toBytesNode.execute(frame, source)), filename, mode, kwFlags, kwDontInherit, kwOptimize); |
| 726 | + try { |
| 727 | + byte[] bytes = toBytesNode.execute(frame, pBytes); |
| 728 | + Charset charset = PythonFileDetector.findEncodingStrict(bytes); |
| 729 | + return compile(createString(bytes, charset), filename, mode, kwFlags, kwDontInherit, kwOptimize); |
| 730 | + } catch (PythonFileDetector.InvalidEncodingException e) { |
| 731 | + throw handleInvalidEncoding(filename, e); |
| 732 | + } |
| 733 | + } |
| 734 | + |
| 735 | + @TruffleBoundary |
| 736 | + private RuntimeException handleInvalidEncoding(String filename, PythonFileDetector.InvalidEncodingException e) { |
| 737 | + PythonContext context = getContext(); |
| 738 | + // Create non-empty source to avoid overwriting the message with "unexpected EOF" |
| 739 | + Source source = PythonLanguage.newSource(context, " ", filename, mayBeFromFile); |
| 740 | + throw getCore().raiseInvalidSyntax(source, source.createUnavailableSection(), "encoding problem: %s", e.getEncodingName()); |
725 | 741 | }
|
726 | 742 |
|
727 | 743 | @SuppressWarnings("unused")
|
@@ -766,8 +782,8 @@ PCode compile(PCode code, String filename, String mode, Object flags, Object don
|
766 | 782 | }
|
767 | 783 |
|
768 | 784 | @TruffleBoundary
|
769 |
| - private static String createString(byte[] bytes) { |
770 |
| - return new String(bytes); |
| 785 | + private static String createString(byte[] bytes, Charset charset) { |
| 786 | + return new String(bytes, charset); |
771 | 787 |
|
772 | 788 | }
|
773 | 789 |
|
|
0 commit comments