01: // Copyright (c) Corporation for National Research Initiatives
02:
03: package org.python.compiler;
04:
05: import java.io.ByteArrayOutputStream;
06: import java.io.DataOutputStream;
07: import java.io.IOException;
08:
09: class Label {
10: int position;
11: int[] offsets, positions, sizes;
12: int noffsets;
13: Code code;
14: int stack;
15:
16: public Label(Code code) {
17: this .code = code;
18: position = -1;
19: noffsets = 0;
20: offsets = new int[4];
21: positions = new int[4];
22: sizes = new int[4];
23: stack = -1;
24: }
25:
26: public void fix(byte[] data) throws IOException {
27: ByteArrayOutputStream array = new ByteArrayOutputStream();
28: DataOutputStream stream = new DataOutputStream(array);
29:
30: if (noffsets > 0 && position == -1)
31: throw new InternalError("position never set for label");
32:
33: for (int i = 0; i < noffsets; i++) {
34: //System.out.println("o: "+offsets[i]+", "+position+", "+
35: // positions[i]);
36: int off = position - offsets[i];
37: int p = positions[i];
38: if (sizes[i] == 2) {
39: stream.writeShort(off);
40: } else {
41: stream.writeInt(off);
42: }
43:
44: System.arraycopy(array.toByteArray(), 0, data, p, sizes[i]);
45: array.reset();
46: //data[p] = (byte)(off >>> 8);
47: //data[p+1] = (byte)(off & 0xff00);
48: }
49: }
50:
51: public void setStack(int stack) {
52: if (this .stack == -1) {
53: this .stack = stack;
54: } else {
55: if (this .stack != stack) {
56: throw new InternalError("stack sizes don't agree: "
57: + this .stack + ", " + stack);
58: }
59: }
60: }
61:
62: public int getPosition() {
63: if (position == -1)
64: throw new InternalError("position never set for label");
65: return position;
66: }
67:
68: public void setPosition() {
69: position = code.size();
70: //code.addLabel(this);
71: }
72:
73: public void setBranch(int offset, int size) throws IOException {
74: if (noffsets >= offsets.length) {
75: int[] new_offsets = new int[offsets.length * 2];
76: System.arraycopy(offsets, 0, new_offsets, 0, noffsets);
77: offsets = new_offsets;
78:
79: int[] new_positions = new int[positions.length * 2];
80: System.arraycopy(positions, 0, new_positions, 0, noffsets);
81: positions = new_positions;
82:
83: int[] new_sizes = new int[sizes.length * 2];
84: System.arraycopy(sizes, 0, new_sizes, 0, noffsets);
85: sizes = new_sizes;
86: }
87: positions[noffsets] = code.size();
88: offsets[noffsets] = offset;
89: sizes[noffsets] = size;
90: noffsets = noffsets + 1;
91: if (size == 2) {
92: code.code.writeShort(0);
93: } else {
94: code.code.writeInt(0);
95: }
96: }
97: }
|