|
| 1 | +package org.python.compiler; |
| 2 | + |
| 3 | +import java.io.ByteArrayOutputStream; |
| 4 | +import java.io.OutputStream; |
| 5 | + |
| 6 | +import org.python.antlr.base.mod; |
| 7 | +import org.python.core.BytecodeLoader; |
| 8 | +import org.python.core.CompilerFlags; |
| 9 | +import org.python.core.Py; |
| 10 | +import org.python.core.PyCode; |
| 11 | +import org.python.core.PythonCodeBundle; |
| 12 | +import org.python.core.PythonCompiler; |
| 13 | + |
| 14 | +public class LegacyCompiler implements PythonCompiler { |
| 15 | + |
| 16 | + public PythonCodeBundle compile(mod node, String name, String filename, |
| 17 | + boolean linenumbers, boolean printResults, CompilerFlags cflags) { |
| 18 | + return new LazyLegacyBundle(node, name, filename, linenumbers, |
| 19 | + printResults, cflags); |
| 20 | + } |
| 21 | + |
| 22 | + private static class LazyLegacyBundle implements PythonCodeBundle { |
| 23 | + |
| 24 | + private final mod node; |
| 25 | + private final String name; |
| 26 | + private final String filename; |
| 27 | + private final boolean linenumbers; |
| 28 | + private final boolean printResults; |
| 29 | + private final CompilerFlags cflags; |
| 30 | + private ByteArrayOutputStream ostream = null; |
| 31 | + |
| 32 | + public LazyLegacyBundle(mod node, String name, String filename, |
| 33 | + boolean linenumbers, boolean printResults, CompilerFlags cflags) { |
| 34 | + this.node = node; |
| 35 | + this.name = name; |
| 36 | + this.filename = filename; |
| 37 | + this.linenumbers = linenumbers; |
| 38 | + this.printResults = printResults; |
| 39 | + this.cflags = cflags; |
| 40 | + } |
| 41 | + |
| 42 | + public PyCode loadCode() throws Exception { |
| 43 | + return BytecodeLoader.makeCode(name, ostream().toByteArray(), |
| 44 | + filename); |
| 45 | + } |
| 46 | + |
| 47 | + public void writeTo(OutputStream stream) throws Exception { |
| 48 | + if (this.ostream != null) { |
| 49 | + stream.write(ostream.toByteArray()); |
| 50 | + } else { |
| 51 | + Module.compile(node, stream, name, filename, linenumbers, |
| 52 | + printResults, cflags); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + public void saveCode(String directory) throws Exception { |
| 57 | + // FIXME: this is slightly broken, it should use the directory |
| 58 | + Py.saveClassFile(name, ostream()); |
| 59 | + } |
| 60 | + |
| 61 | + private ByteArrayOutputStream ostream() throws Exception { |
| 62 | + if (ostream == null) { |
| 63 | + ostream = new ByteArrayOutputStream(); |
| 64 | + Module.compile(node, ostream, name, filename, linenumbers, |
| 65 | + printResults, cflags); |
| 66 | + } |
| 67 | + return ostream; |
| 68 | + } |
| 69 | + |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments