|
12 | 12 | import java.io.FileNotFoundException;
|
13 | 13 | import java.io.IOException;
|
14 | 14 | import java.io.InputStream;
|
15 |
| -import java.io.InputStreamReader; |
16 |
| -import java.nio.charset.StandardCharsets; |
17 | 15 | import java.util.Locale;
|
18 | 16 |
|
19 |
| -import org.truffleruby.RubyContext; |
20 | 17 | import org.truffleruby.RubyLanguage;
|
| 18 | +import org.truffleruby.core.encoding.Encodings; |
| 19 | +import org.truffleruby.parser.MagicCommentParser; |
| 20 | +import org.truffleruby.parser.RubySource; |
21 | 21 | import org.truffleruby.shared.TruffleRuby;
|
22 | 22 |
|
23 | 23 | import com.oracle.truffle.api.source.Source;
|
|
27 | 27 | */
|
28 | 28 | public abstract class ResourceLoader {
|
29 | 29 |
|
30 |
| - public static Source loadResource(String path, boolean internal) throws IOException { |
| 30 | + public static RubySource loadResource(String path, boolean internal) throws IOException { |
31 | 31 | assert path.startsWith(RubyLanguage.RESOURCE_SCHEME);
|
32 | 32 |
|
33 | 33 | if (!path.toLowerCase(Locale.ENGLISH).endsWith(".rb")) {
|
34 | 34 | throw new FileNotFoundException(path);
|
35 | 35 | }
|
36 | 36 |
|
37 |
| - final Class<?> relativeClass = RubyContext.class; |
38 | 37 | final String resourcePath = path.substring(RubyLanguage.RESOURCE_SCHEME.length());
|
39 |
| - final InputStream stream = relativeClass.getResourceAsStream(resourcePath); |
40 | 38 |
|
41 |
| - if (stream == null) { |
42 |
| - throw new FileNotFoundException(resourcePath); |
| 39 | + final byte[] sourceBytes; |
| 40 | + try (InputStream stream = ResourceLoader.class.getResourceAsStream(resourcePath)) { |
| 41 | + if (stream == null) { |
| 42 | + throw new FileNotFoundException(resourcePath); |
| 43 | + } |
| 44 | + |
| 45 | + sourceBytes = stream.readAllBytes(); |
43 | 46 | }
|
44 | 47 |
|
45 |
| - final Source source; |
46 | 48 |
|
47 |
| - // We guarantee that we only put UTF-8 source files into resources |
48 |
| - try (final InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { |
49 |
| - source = Source.newBuilder(TruffleRuby.LANGUAGE_ID, reader, path).internal(internal).build(); |
50 |
| - } |
| 49 | + var sourceTString = MagicCommentParser.createSourceTStringBasedOnMagicEncodingComment(sourceBytes, |
| 50 | + Encodings.UTF_8); |
| 51 | + |
| 52 | + Source source = Source |
| 53 | + .newBuilder(TruffleRuby.LANGUAGE_ID, new ByteBasedCharSequence(sourceTString), path) |
| 54 | + .mimeType(RubyLanguage.getMimeType(false)) |
| 55 | + .internal(internal) |
| 56 | + .build(); |
51 | 57 |
|
52 |
| - return source; |
| 58 | + return new RubySource(source, path, sourceTString); |
53 | 59 | }
|
54 | 60 |
|
55 | 61 | }
|
0 commit comments