summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/symtab/classfile/UnPickler.scala
blob: fea767d9dc3789010629c50f21d1bf4b4bcd7de5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/* NSC -- new scala compiler
 * Copyright 2005 LAMP/EPFL
 * @author  Martin Odersky
 */
// $Id$
package scala.tools.nsc.symtab.classfile;

import scala.tools.nsc.util.Position;
import scala.tools.util.UTF8Codec;
import java.lang.{Float, Double};

import Flags._;
import PickleFormat._;
import collection.mutable.HashMap;
import java.io.IOException;

abstract class UnPickler {
  val global: Global;
  import global._;

  def unpickle(bytes: Array[byte], offset: int, classRoot: Symbol, moduleRoot: Symbol, filename: String): unit = try {
    new UnPickle(bytes, offset, classRoot, moduleRoot);
  } catch {
    case ex: IOException =>
      throw ex
    case ex: Throwable =>
      if (settings.debug.value) ex.printStackTrace();
      throw new RuntimeException("error reading Scala signature of "+filename+": "+ex.getMessage())
  }

  private class UnPickle(bytes: Array[byte], offset: int, classRoot: Symbol, moduleRoot: Symbol) extends PickleBuffer(bytes, offset, -1) {
    if (settings.debug.value) global.log("unpickle " + classRoot + " and " + moduleRoot);
    checkVersion();
    private val index = createIndex;
    private val entries = new Array[AnyRef](index.length);
    private val symScopes = new HashMap[Symbol, Scope];

    for (val i <- Iterator.range(0, index.length)) {
      if (isSymbolEntry(i)) { at(i, readSymbol); () }
    }

    if (settings.debug.value) global.log("unpickled " + classRoot + ":" + classRoot.rawInfo + ", " + moduleRoot + ":" + moduleRoot.rawInfo);//debug

    private def checkVersion() = {
      val major = readNat();
      val minor = readNat();
      if (major != MajorVersion || minor > MinorVersion)
        throw new IOException("Scala signature " + classRoot.name +
                              " has wrong version\n expected: " +
                              MajorVersion + "." + MinorVersion +
                              "\n found: " + major + "." + minor)
    }

    /** The scope associated with given symbol */
    private def symScope(sym: Symbol) = symScopes.get(sym) match {
      case None => val s = new Scope(); symScopes(sym) = s; s
      case Some(s) => s
    }

    /** Does entry represent an (internal) symbol */
    private def isSymbolEntry(i: int): boolean = {
      val tag = bytes(index(i)) % PosOffset;
      (firstSymTag <= tag && tag <= lastSymTag &&
       (tag != CLASSsym || !isRefinementSymbolEntry(i)))
    }

    /** Does entry represent an (internal or external) symbol */
    private def isSymbolRef(i: int): boolean = {
      val tag = bytes(index(i)) % PosOffset;
      (firstSymTag <= tag && tag <= lastExtSymTag)
    }
    /** Does entry represent a refinement symbol?
     *  pre: Entry is a class symbol
     */
    private def isRefinementSymbolEntry(i: int): boolean = {
      val savedIndex = readIndex;
      readIndex = index(i);
      val tag = readByte();
      if (tag % PosOffset != CLASSsym) assert(false);
      readNat(); // read length
      if (tag > PosOffset) readNat(); // read position
      val result = readNameRef() == nme.REFINE_CLASS_NAME.toTypeName;
      readIndex = savedIndex;
      result
    }

    /** If entry at `i' is undefined, define it by performing operation `op' with
     *  readIndex at start of i'th entry. Restore readIndex afterwards. */
    private def at[T <: AnyRef](i: int, op: () => T): T = {
      var r = entries(i);
      if (r == null) {
	val savedIndex = readIndex;
	readIndex = index(i);
	r = op();
	assert(entries(i) == null, entries(i));
	entries(i) = r;
	readIndex = savedIndex;
      }
      r.asInstanceOf[T]
    }

    /** Read a name */
    private def readName(): Name = {
      val tag = readByte();
      val len = readNat();
      tag match {
	case TERMname => newTermName(bytes, readIndex, len)
	case TYPEname => newTypeName(bytes, readIndex, len)
	case _ => errorBadSignature("bad name tag: " + tag);
      }
    }

    /** Read a symbol */
    private def readSymbol(): Symbol = {
      val tag = readByte();
      val end = readNat() + readIndex;
      var sym: Symbol = NoSymbol;
      tag match {
	case EXTref | EXTMODCLASSref =>
	  val name = readNameRef();
	  val owner = if (readIndex == end) definitions.RootClass else readSymbolRef();
	  sym = if (tag == EXTref) owner.info.decl(name)
		else if (name.toTermName == nme.ROOT) definitions.RootClass
		else owner.info.decl(name).moduleClass;
	  if (sym == NoSymbol)
	    errorBadSignature(
	      "reference " + (if (name.isTypeName) "type " else "value ") +
	      name.decode + " of " + owner + " refers to nonexisting symbol.")
	case NONEsym =>
	  sym = NoSymbol
	case _ =>
          val pos = if (tag > PosOffset) readNat() else Position.NOPOS;
	  val name = readNameRef();
	  val owner = readSymbolRef();
	  val flags = readNat();
          var privateWithin: Symbol = NoSymbol;
          var inforef = readNat();
          if (isSymbolRef(inforef)) {
            privateWithin = at(inforef, readSymbol);
            inforef = readNat()
          }
	  (tag % PosOffset) match {
	    case TYPEsym =>
	      sym = owner.newAbstractType(pos, name);
	    case ALIASsym =>
	      sym = owner.newAliasType(pos, name);
	    case CLASSsym =>
	      sym =
                if (name == classRoot.name && owner == classRoot.owner)
                  (if ((flags & MODULE) != 0) moduleRoot.moduleClass
                   else classRoot).setPos(pos)
		else
                  if ((flags & MODULE) != 0) owner.newModuleClass(pos, name)
                  else owner.newClass(pos, name);
	      if (readIndex != end) sym.typeOfThis = new LazyTypeRef(readNat())
	    case MODULEsym =>
	      val clazz = at(inforef, readType).symbol;
	      sym =
                if (name == moduleRoot.name && owner == moduleRoot.owner) moduleRoot
		else {
		  assert(clazz.isInstanceOf[ModuleClassSymbol], clazz);
		  val mclazz = clazz.asInstanceOf[ModuleClassSymbol];
                  val m = owner.newModule(pos, name, mclazz);
                  mclazz.setSourceModule(m);
                  m
                }
	    case VALsym =>
	      sym = if (name == moduleRoot.name && owner == moduleRoot.owner) moduleRoot.resetFlag(MODULE)
		    else owner.newValue(pos, name)
	    case _ =>
	      errorBadSignature("bad symbol tag: " + tag);
	  }
	  sym.setFlag(flags);
          sym.privateWithin = privateWithin;
	  if (readIndex != end) assert(sym hasFlag (SUPERACCESSOR | PARAMACCESSOR));
	  if (sym hasFlag SUPERACCESSOR) assert(readIndex != end);
	  sym.setInfo(
	    if (readIndex != end) new LazyTypeRefAndAlias(inforef, readNat())
	    else new LazyTypeRef(inforef));
	  if (sym.owner.isClass && sym != classRoot && sym != moduleRoot &&
              !sym.isModuleClass && !sym.isRefinementClass && !sym.isTypeParameter)
            symScope(sym.owner) enter sym;
      }
      sym
    }

    /** Read a type */
    private def readType(): Type = {
      val tag = readByte();
      val end = readNat() + readIndex;
      tag match {
	case NOtpe =>
	  NoType
	case NOPREFIXtpe =>
	  NoPrefix
	case THIStpe =>
	  ThisType(readSymbolRef())
	case SINGLEtpe =>
	  singleType(readTypeRef(), readSymbolRef())
	case CONSTANTtpe =>
	  ConstantType(readConstantRef())
	case TYPEREFtpe =>
	  rawTypeRef(readTypeRef(), readSymbolRef(), until(end, readTypeRef))
        case TYPEBOUNDStpe =>
          TypeBounds(readTypeRef(), readTypeRef())
	case REFINEDtpe =>
	  val clazz = readSymbolRef();
/*
          val ps = until(end, readTypeRef);
          val dcls = symScope(clazz);
          new RefinedType(ps, dcls) { override def symbol = clazz }
*/
	  new RefinedType(until(end, readTypeRef), symScope(clazz)) { override def symbol = clazz }
	case CLASSINFOtpe =>
	  val clazz = readSymbolRef();
	  ClassInfoType(until(end, readTypeRef), symScope(clazz), clazz)
	case METHODtpe =>
	  val restpe = readTypeRef();
	  MethodType(until(end, readTypeRef), restpe)
	case IMPLICITMETHODtpe =>
	  val restpe = readTypeRef();
	  ImplicitMethodType(until(end, readTypeRef), restpe)
	case POLYtpe =>
	  val restpe = readTypeRef();
	  PolyType(until(end, readSymbolRef), restpe)
	case _ =>
	  errorBadSignature("bad type tag: " + tag);
      }
    }

    /** Read a constant */
    private def readConstant(): Constant = {
      val tag = readByte();
      val len = readNat();
      tag match {
	case LITERALunit    => Constant(())
	case LITERALboolean => Constant(if (readLong(len) == 0) false else true)
	case LITERALbyte    => Constant(readLong(len).asInstanceOf[byte])
	case LITERALshort   => Constant(readLong(len).asInstanceOf[short])
	case LITERALchar    => Constant(readLong(len).asInstanceOf[char])
	case LITERALint     => Constant(readLong(len).asInstanceOf[int])
	case LITERALlong    => Constant(readLong(len))
	case LITERALfloat   => Constant(Float.intBitsToFloat(readLong(len).asInstanceOf[int]))
	case LITERALdouble  => Constant(Double.longBitsToDouble(readLong(len)))
	case LITERALstring  => Constant(readNameRef().toString())
	case LITERALnull    => Constant(null)
	case _              => errorBadSignature("bad constant tag: " + tag)
      }
    };

    /** Read a reference to a name, symbol, type or constant */
    private def readNameRef(): Name = at(readNat(), readName);
    private def readSymbolRef(): Symbol = at(readNat(), readSymbol);
    private def readTypeRef(): Type = at(readNat(), readType);
    private def readConstantRef(): Constant = at(readNat(), readConstant);

    private def errorBadSignature(msg: String) =
      throw new RuntimeException("malformed Scala signature of " + classRoot.name + " at " + readIndex + "; " + msg);

    private class LazyTypeRef(i: int) extends LazyType {
      private val definedAtRun = currentRun;
      override def complete(sym: Symbol): unit = {
	val tp = at(i, readType);
	sym setInfo tp;
	if (currentRun != definedAtRun) tp.complete(sym)
      }
      override def load(sym: Symbol): unit = complete(sym)
    }

    private class LazyTypeRefAndAlias(i: int, j: int) extends LazyTypeRef(i) {
      override def complete(sym: Symbol): unit = {
	super.complete(sym);
	sym.asInstanceOf[TermSymbol].setAlias(at(j, readSymbol));
      }
    }
  }
}