From 0b2f1bcf75d31c59b25e19eebcb80f39c155365b Mon Sep 17 00:00:00 2001 From: Eugene Burmako Date: Fri, 8 Jun 2012 02:36:10 +0200 Subject: Introduces scala-reflect.jar --- src/compiler/scala/reflect/api/JavaUniverse.scala | 19 - src/compiler/scala/reflect/api/TagInterop.scala | 38 - .../scala/reflect/internal/AbstractFileApi.scala | 7 - .../reflect/internal/AnnotationCheckers.scala | 121 - .../scala/reflect/internal/AnnotationInfos.scala | 293 - .../scala/reflect/internal/BaseTypeSeqs.scala | 260 - .../scala/reflect/internal/BuildUtils.scala | 69 - .../scala/reflect/internal/CapturedVariables.scala | 36 - src/compiler/scala/reflect/internal/Chars.scala | 98 - .../reflect/internal/ClassfileConstants.scala | 390 -- .../scala/reflect/internal/Constants.scala | 240 - .../scala/reflect/internal/Definitions.scala | 1241 ---- .../reflect/internal/ExistentialsAndSkolems.scala | 50 - .../scala/reflect/internal/FatalError.scala | 6 - src/compiler/scala/reflect/internal/FlagSets.scala | 66 - src/compiler/scala/reflect/internal/Flags.scala | 483 -- src/compiler/scala/reflect/internal/HasFlags.scala | 169 - .../scala/reflect/internal/Importers.scala | 451 -- .../scala/reflect/internal/InfoTransformers.scala | 51 - src/compiler/scala/reflect/internal/Kinds.scala | 232 - src/compiler/scala/reflect/internal/Mirrors.scala | 243 - .../reflect/internal/MissingRequirementError.scala | 24 - src/compiler/scala/reflect/internal/Names.scala | 527 -- src/compiler/scala/reflect/internal/Phase.scala | 66 - .../scala/reflect/internal/Positions.scala | 63 - src/compiler/scala/reflect/internal/Required.scala | 17 - src/compiler/scala/reflect/internal/Scopes.scala | 359 -- .../scala/reflect/internal/StdAttachments.scala | 12 - .../scala/reflect/internal/StdCreators.scala | 21 - src/compiler/scala/reflect/internal/StdNames.scala | 1218 ---- .../scala/reflect/internal/SymbolTable.scala | 332 - src/compiler/scala/reflect/internal/Symbols.scala | 3190 --------- src/compiler/scala/reflect/internal/TreeGen.scala | 280 - src/compiler/scala/reflect/internal/TreeInfo.scala | 571 -- .../scala/reflect/internal/TreePrinters.scala | 478 -- src/compiler/scala/reflect/internal/Trees.scala | 1592 ----- .../scala/reflect/internal/TypeDebugging.scala | 71 - src/compiler/scala/reflect/internal/Types.scala | 6820 -------------------- src/compiler/scala/reflect/internal/package.scala | 6 - .../reflect/internal/pickling/ByteCodecs.scala | 221 - .../reflect/internal/pickling/PickleBuffer.scala | 188 - .../reflect/internal/pickling/PickleFormat.scala | 225 - .../reflect/internal/pickling/UnPickler.scala | 871 --- .../reflect/internal/settings/AbsSettings.scala | 23 - .../internal/settings/MutableSettings.scala | 48 - .../scala/reflect/internal/transform/Erasure.scala | 336 - .../reflect/internal/transform/RefChecks.scala | 13 - .../reflect/internal/transform/Transforms.scala | 41 - .../scala/reflect/internal/transform/UnCurry.scala | 64 - .../scala/reflect/internal/util/Collections.scala | 213 - .../scala/reflect/internal/util/HashSet.scala | 106 - .../scala/reflect/internal/util/Origins.scala | 119 - .../scala/reflect/internal/util/Position.scala | 277 - src/compiler/scala/reflect/internal/util/Set.scala | 28 - .../scala/reflect/internal/util/SourceFile.scala | 161 - .../scala/reflect/internal/util/StatBase.scala | 97 - .../scala/reflect/internal/util/Statistics.scala | 34 - .../scala/reflect/internal/util/StringOps.scala | 99 - .../scala/reflect/internal/util/TableDef.scala | 94 - .../internal/util/TraceSymbolActivity.scala | 169 - .../scala/reflect/internal/util/WeakHashSet.scala | 61 - .../scala/reflect/runtime/AbstractFile.scala | 7 - .../scala/reflect/runtime/JavaMirrors.scala | 981 --- .../scala/reflect/runtime/JavaUniverse.scala | 33 - .../scala/reflect/runtime/ReflectSetup.scala | 12 - .../scala/reflect/runtime/ReflectionUtils.scala | 80 - src/compiler/scala/reflect/runtime/Settings.scala | 39 - .../scala/reflect/runtime/SymbolLoaders.scala | 152 - .../scala/reflect/runtime/SymbolTable.scala | 17 - .../scala/reflect/runtime/SynchronizedOps.scala | 51 - .../reflect/runtime/SynchronizedSymbols.scala | 140 - .../scala/reflect/runtime/SynchronizedTypes.scala | 88 - .../scala/reflect/runtime/TwoWayCache.scala | 52 - src/compiler/scala/reflect/runtime/package.scala | 26 - src/compiler/scala/tools/nsc/io/AbstractFile.scala | 259 - src/compiler/scala/tools/nsc/io/Directory.scala | 76 - src/compiler/scala/tools/nsc/io/File.scala | 194 - .../tools/nsc/io/FileOperationException.scala | 13 - .../scala/tools/nsc/io/NoAbstractFile.scala | 32 - src/compiler/scala/tools/nsc/io/Path.scala | 289 - src/compiler/scala/tools/nsc/io/PlainFile.scala | 102 - src/compiler/scala/tools/nsc/io/Streamable.scala | 122 - .../scala/tools/nsc/io/VirtualDirectory.scala | 70 - src/compiler/scala/tools/nsc/io/VirtualFile.scala | 102 - src/compiler/scala/tools/nsc/io/ZipArchive.scala | 221 - 85 files changed, 26856 deletions(-) delete mode 100644 src/compiler/scala/reflect/api/JavaUniverse.scala delete mode 100644 src/compiler/scala/reflect/api/TagInterop.scala delete mode 100644 src/compiler/scala/reflect/internal/AbstractFileApi.scala delete mode 100644 src/compiler/scala/reflect/internal/AnnotationCheckers.scala delete mode 100644 src/compiler/scala/reflect/internal/AnnotationInfos.scala delete mode 100644 src/compiler/scala/reflect/internal/BaseTypeSeqs.scala delete mode 100644 src/compiler/scala/reflect/internal/BuildUtils.scala delete mode 100644 src/compiler/scala/reflect/internal/CapturedVariables.scala delete mode 100644 src/compiler/scala/reflect/internal/Chars.scala delete mode 100644 src/compiler/scala/reflect/internal/ClassfileConstants.scala delete mode 100644 src/compiler/scala/reflect/internal/Constants.scala delete mode 100644 src/compiler/scala/reflect/internal/Definitions.scala delete mode 100644 src/compiler/scala/reflect/internal/ExistentialsAndSkolems.scala delete mode 100644 src/compiler/scala/reflect/internal/FatalError.scala delete mode 100644 src/compiler/scala/reflect/internal/FlagSets.scala delete mode 100644 src/compiler/scala/reflect/internal/Flags.scala delete mode 100644 src/compiler/scala/reflect/internal/HasFlags.scala delete mode 100644 src/compiler/scala/reflect/internal/Importers.scala delete mode 100644 src/compiler/scala/reflect/internal/InfoTransformers.scala delete mode 100644 src/compiler/scala/reflect/internal/Kinds.scala delete mode 100644 src/compiler/scala/reflect/internal/Mirrors.scala delete mode 100644 src/compiler/scala/reflect/internal/MissingRequirementError.scala delete mode 100644 src/compiler/scala/reflect/internal/Names.scala delete mode 100644 src/compiler/scala/reflect/internal/Phase.scala delete mode 100644 src/compiler/scala/reflect/internal/Positions.scala delete mode 100644 src/compiler/scala/reflect/internal/Required.scala delete mode 100644 src/compiler/scala/reflect/internal/Scopes.scala delete mode 100644 src/compiler/scala/reflect/internal/StdAttachments.scala delete mode 100644 src/compiler/scala/reflect/internal/StdCreators.scala delete mode 100644 src/compiler/scala/reflect/internal/StdNames.scala delete mode 100644 src/compiler/scala/reflect/internal/SymbolTable.scala delete mode 100644 src/compiler/scala/reflect/internal/Symbols.scala delete mode 100644 src/compiler/scala/reflect/internal/TreeGen.scala delete mode 100644 src/compiler/scala/reflect/internal/TreeInfo.scala delete mode 100644 src/compiler/scala/reflect/internal/TreePrinters.scala delete mode 100644 src/compiler/scala/reflect/internal/Trees.scala delete mode 100644 src/compiler/scala/reflect/internal/TypeDebugging.scala delete mode 100644 src/compiler/scala/reflect/internal/Types.scala delete mode 100644 src/compiler/scala/reflect/internal/package.scala delete mode 100644 src/compiler/scala/reflect/internal/pickling/ByteCodecs.scala delete mode 100644 src/compiler/scala/reflect/internal/pickling/PickleBuffer.scala delete mode 100644 src/compiler/scala/reflect/internal/pickling/PickleFormat.scala delete mode 100644 src/compiler/scala/reflect/internal/pickling/UnPickler.scala delete mode 100644 src/compiler/scala/reflect/internal/settings/AbsSettings.scala delete mode 100644 src/compiler/scala/reflect/internal/settings/MutableSettings.scala delete mode 100644 src/compiler/scala/reflect/internal/transform/Erasure.scala delete mode 100644 src/compiler/scala/reflect/internal/transform/RefChecks.scala delete mode 100644 src/compiler/scala/reflect/internal/transform/Transforms.scala delete mode 100644 src/compiler/scala/reflect/internal/transform/UnCurry.scala delete mode 100644 src/compiler/scala/reflect/internal/util/Collections.scala delete mode 100644 src/compiler/scala/reflect/internal/util/HashSet.scala delete mode 100644 src/compiler/scala/reflect/internal/util/Origins.scala delete mode 100644 src/compiler/scala/reflect/internal/util/Position.scala delete mode 100644 src/compiler/scala/reflect/internal/util/Set.scala delete mode 100644 src/compiler/scala/reflect/internal/util/SourceFile.scala delete mode 100644 src/compiler/scala/reflect/internal/util/StatBase.scala delete mode 100644 src/compiler/scala/reflect/internal/util/Statistics.scala delete mode 100644 src/compiler/scala/reflect/internal/util/StringOps.scala delete mode 100644 src/compiler/scala/reflect/internal/util/TableDef.scala delete mode 100644 src/compiler/scala/reflect/internal/util/TraceSymbolActivity.scala delete mode 100644 src/compiler/scala/reflect/internal/util/WeakHashSet.scala delete mode 100644 src/compiler/scala/reflect/runtime/AbstractFile.scala delete mode 100644 src/compiler/scala/reflect/runtime/JavaMirrors.scala delete mode 100644 src/compiler/scala/reflect/runtime/JavaUniverse.scala delete mode 100644 src/compiler/scala/reflect/runtime/ReflectSetup.scala delete mode 100644 src/compiler/scala/reflect/runtime/ReflectionUtils.scala delete mode 100644 src/compiler/scala/reflect/runtime/Settings.scala delete mode 100644 src/compiler/scala/reflect/runtime/SymbolLoaders.scala delete mode 100644 src/compiler/scala/reflect/runtime/SymbolTable.scala delete mode 100644 src/compiler/scala/reflect/runtime/SynchronizedOps.scala delete mode 100644 src/compiler/scala/reflect/runtime/SynchronizedSymbols.scala delete mode 100644 src/compiler/scala/reflect/runtime/SynchronizedTypes.scala delete mode 100644 src/compiler/scala/reflect/runtime/TwoWayCache.scala delete mode 100644 src/compiler/scala/reflect/runtime/package.scala delete mode 100644 src/compiler/scala/tools/nsc/io/AbstractFile.scala delete mode 100644 src/compiler/scala/tools/nsc/io/Directory.scala delete mode 100644 src/compiler/scala/tools/nsc/io/File.scala delete mode 100644 src/compiler/scala/tools/nsc/io/FileOperationException.scala delete mode 100644 src/compiler/scala/tools/nsc/io/NoAbstractFile.scala delete mode 100644 src/compiler/scala/tools/nsc/io/Path.scala delete mode 100644 src/compiler/scala/tools/nsc/io/PlainFile.scala delete mode 100644 src/compiler/scala/tools/nsc/io/Streamable.scala delete mode 100644 src/compiler/scala/tools/nsc/io/VirtualDirectory.scala delete mode 100644 src/compiler/scala/tools/nsc/io/VirtualFile.scala delete mode 100644 src/compiler/scala/tools/nsc/io/ZipArchive.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/reflect/api/JavaUniverse.scala b/src/compiler/scala/reflect/api/JavaUniverse.scala deleted file mode 100644 index 8bf62a357c..0000000000 --- a/src/compiler/scala/reflect/api/JavaUniverse.scala +++ /dev/null @@ -1,19 +0,0 @@ -package scala.reflect -package api - -// [Martin] Moved to compiler because it needs to see runtime.Universe -// The two will be united in scala-reflect anyway. -trait JavaUniverse extends Universe with Mirrors with TagInterop { self => - - type RuntimeClass = java.lang.Class[_] - - override type Mirror >: Null <: JavaMirror - - trait JavaMirror extends MirrorOf[self.type] with RuntimeMirror { - val classLoader: ClassLoader - override def toString = s"JavaMirror with ${runtime.ReflectionUtils.show(classLoader)}" - } - - def runtimeMirror(cl: ClassLoader): Mirror -} - diff --git a/src/compiler/scala/reflect/api/TagInterop.scala b/src/compiler/scala/reflect/api/TagInterop.scala deleted file mode 100644 index e10b89d1c6..0000000000 --- a/src/compiler/scala/reflect/api/TagInterop.scala +++ /dev/null @@ -1,38 +0,0 @@ -package scala.reflect -package api - -import scala.reflect.base.TypeCreator -import scala.reflect.base.{Universe => BaseUniverse} - -// [Martin] Moved to compiler because it needs to see runtime.Universe -// The two will be united in scala-reflect anyway. -trait TagInterop { self: JavaUniverse => - - // [Eugene++] would be great if we could approximate the interop without any mirrors - // todo. think how to implement that - - override def concreteTypeTagToManifest[T: ClassTag](mirror0: Any, tag: base.Universe # ConcreteTypeTag[T]): Manifest[T] = { - // [Eugene++] implement more sophisticated logic - // Martin said it'd be okay to simply copypaste `Implicits.manifestOfType` - val mirror = mirror0.asInstanceOf[Mirror] - val runtimeClass = mirror.runtimeClass(tag.in(mirror).tpe) - Manifest.classType(runtimeClass).asInstanceOf[Manifest[T]] - } - - override def manifestToConcreteTypeTag[T](mirror0: Any, manifest: Manifest[T]): base.Universe # ConcreteTypeTag[T] = - ConcreteTypeTag(mirror0.asInstanceOf[Mirror], new TypeCreator { - def apply[U <: BaseUniverse with Singleton](mirror: MirrorOf[U]): U # Type = { - mirror.universe match { - case ju: JavaUniverse => - val jm = mirror.asInstanceOf[ju.Mirror] - val sym = jm.reflectClass(manifest.erasure).symbol - val tpe = - if (manifest.typeArguments.isEmpty) sym.asType - else ju.appliedType(sym.asTypeConstructor, manifest.typeArguments map (targ => ju.manifestToConcreteTypeTag(jm, targ)) map (_.in(jm).tpe)) - tpe.asInstanceOf[U # Type] - case u => - u.manifestToConcreteTypeTag(mirror.asInstanceOf[u.Mirror], manifest).in(mirror).tpe - } - } - }) -} diff --git a/src/compiler/scala/reflect/internal/AbstractFileApi.scala b/src/compiler/scala/reflect/internal/AbstractFileApi.scala deleted file mode 100644 index 9f37f4536f..0000000000 --- a/src/compiler/scala/reflect/internal/AbstractFileApi.scala +++ /dev/null @@ -1,7 +0,0 @@ -package scala.reflect -package internal - -trait AbstractFileApi { - def path: String - def canonicalPath: String -} diff --git a/src/compiler/scala/reflect/internal/AnnotationCheckers.scala b/src/compiler/scala/reflect/internal/AnnotationCheckers.scala deleted file mode 100644 index 449b0ca0bc..0000000000 --- a/src/compiler/scala/reflect/internal/AnnotationCheckers.scala +++ /dev/null @@ -1,121 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2007-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -/** Additions to the type checker that can be added at - * run time. Typically these are added by - * compiler plugins. */ -trait AnnotationCheckers { - self: SymbolTable => - - - /** An additional checker for annotations on types. - * Typically these are registered by compiler plugins - * with the addAnnotationChecker method. */ - abstract class AnnotationChecker { - /** Check the annotations on two types conform. */ - def annotationsConform(tpe1: Type, tpe2: Type): Boolean - - /** Refine the computed least upper bound of a list of types. - * All this should do is add annotations. */ - def annotationsLub(tp: Type, ts: List[Type]): Type = tp - - /** Refine the computed greatest lower bound of a list of types. - * All this should do is add annotations. */ - def annotationsGlb(tp: Type, ts: List[Type]): Type = tp - - /** Refine the bounds on type parameters to the given type arguments. */ - def adaptBoundsToAnnotations(bounds: List[TypeBounds], - tparams: List[Symbol], targs: List[Type]): List[TypeBounds] = bounds - - /** Modify the type that has thus far been inferred - * for a tree. All this should do is add annotations. */ - def addAnnotations(tree: Tree, tpe: Type): Type = tpe - - /** Decide whether this annotation checker can adapt a tree - * that has an annotated type to the given type tp, taking - * into account the given mode (see method adapt in trait Typers).*/ - def canAdaptAnnotations(tree: Tree, mode: Int, pt: Type): Boolean = false - - /** Adapt a tree that has an annotated type to the given type tp, - * taking into account the given mode (see method adapt in trait Typers). - * An implementation cannot rely on canAdaptAnnotations being called - * before. If the implementing class cannot do the adaptiong, it - * should return the tree unchanged.*/ - def adaptAnnotations(tree: Tree, mode: Int, pt: Type): Tree = tree - } - - // Syncnote: Annotation checkers inaccessible to reflection, so no sync in var necessary. - /** The list of annotation checkers that have been registered */ - private var annotationCheckers: List[AnnotationChecker] = Nil - - /** Register an annotation checker. Typically these - * are added by compiler plugins. */ - def addAnnotationChecker(checker: AnnotationChecker) { - if (!(annotationCheckers contains checker)) - annotationCheckers = checker :: annotationCheckers - } - - /** Remove all annotation checkers */ - def removeAllAnnotationCheckers() { - annotationCheckers = Nil - } - - /** Check that the annotations on two types conform. To do - * so, consult all registered annotation checkers. */ - def annotationsConform(tp1: Type, tp2: Type): Boolean = { - /* Finish quickly if there are no annotations */ - if (tp1.annotations.isEmpty && tp2.annotations.isEmpty) - true - else - annotationCheckers.forall( - _.annotationsConform(tp1,tp2)) - } - - /** Refine the computed least upper bound of a list of types. - * All this should do is add annotations. */ - def annotationsLub(tpe: Type, ts: List[Type]): Type = { - annotationCheckers.foldLeft(tpe)((tpe, checker) => - checker.annotationsLub(tpe, ts)) - } - - /** Refine the computed greatest lower bound of a list of types. - * All this should do is add annotations. */ - def annotationsGlb(tpe: Type, ts: List[Type]): Type = { - annotationCheckers.foldLeft(tpe)((tpe, checker) => - checker.annotationsGlb(tpe, ts)) - } - - /** Refine the bounds on type parameters to the given type arguments. */ - def adaptBoundsToAnnotations(bounds: List[TypeBounds], - tparams: List[Symbol], targs: List[Type]): List[TypeBounds] = { - annotationCheckers.foldLeft(bounds)((bounds, checker) => - checker.adaptBoundsToAnnotations(bounds, tparams, targs)) - } - - /** Let all annotations checkers add extra annotations - * to this tree's type. */ - def addAnnotations(tree: Tree, tpe: Type): Type = { - annotationCheckers.foldLeft(tpe)((tpe, checker) => - checker.addAnnotations(tree, tpe)) - } - - /** Find out whether any annotation checker can adapt a tree - * to a given type. Called by Typers.adapt. */ - def canAdaptAnnotations(tree: Tree, mode: Int, pt: Type): Boolean = { - annotationCheckers.exists(_.canAdaptAnnotations(tree, mode, pt)) - } - - /** Let registered annotation checkers adapt a tree - * to a given type (called by Typers.adapt). Annotation checkers - * that cannot do the adaption should pass the tree through - * unchanged. */ - def adaptAnnotations(tree: Tree, mode: Int, pt: Type): Tree = { - annotationCheckers.foldLeft(tree)((tree, checker) => - checker.adaptAnnotations(tree, mode, pt)) - } -} diff --git a/src/compiler/scala/reflect/internal/AnnotationInfos.scala b/src/compiler/scala/reflect/internal/AnnotationInfos.scala deleted file mode 100644 index c283ae408e..0000000000 --- a/src/compiler/scala/reflect/internal/AnnotationInfos.scala +++ /dev/null @@ -1,293 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2007-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import util._ -import pickling.ByteCodecs - -/** AnnotationInfo and its helpers */ -trait AnnotationInfos extends api.AnnotationInfos { self: SymbolTable => - import definitions.{ ThrowsClass, StaticAnnotationClass, isMetaAnnotation } - - // Common annotation code between Symbol and Type. - // For methods altering the annotation list, on Symbol it mutates - // the Symbol's field directly. For Type, a new AnnotatedType is - // created which wraps the original type. - trait Annotatable[Self] { - /** The annotations on this type. */ - def annotations: List[AnnotationInfo] // Annotations on this type. - def setAnnotations(annots: List[AnnotationInfo]): Self // Replace annotations with argument list. - def withAnnotations(annots: List[AnnotationInfo]): Self // Add annotations to this type. - def filterAnnotations(p: AnnotationInfo => Boolean): Self // Retain only annotations meeting the condition. - def withoutAnnotations: Self // Remove all annotations from this type. - - /** Symbols of any @throws annotations on this symbol. - */ - def throwsAnnotations(): List[Symbol] = annotations collect { - case AnnotationInfo(tp, Literal(Constant(tpe: Type)) :: Nil, _) if tp.typeSymbol == ThrowsClass => tpe.typeSymbol - } - - /** Test for, get, or remove an annotation */ - def hasAnnotation(cls: Symbol) = annotations exists (_ matches cls) - def getAnnotation(cls: Symbol) = annotations find (_ matches cls) - def removeAnnotation(cls: Symbol): Self = filterAnnotations(ann => !(ann matches cls)) - final def withAnnotation(annot: AnnotationInfo): Self = withAnnotations(List(annot)) - } - - /** Arguments to classfile annotations (which are written to - * bytecode as java annotations) are either: - * - * - constants - * - arrays of constants - * - or nested classfile annotations - */ - abstract class ClassfileAnnotArg extends Product - implicit val ClassfileAnnotArgTag = ClassTag[ClassfileAnnotArg](classOf[ClassfileAnnotArg]) - - /** Represents a compile-time Constant (`Boolean`, `Byte`, `Short`, - * `Char`, `Int`, `Long`, `Float`, `Double`, `String`, `java.lang.Class` or - * an instance of a Java enumeration value). - */ - case class LiteralAnnotArg(const: Constant) - extends ClassfileAnnotArg with LiteralAnnotArgApi { - override def toString = const.escapedStringValue - } - implicit val LiteralAnnotArgTag = ClassTag[LiteralAnnotArg](classOf[LiteralAnnotArg]) - - object LiteralAnnotArg extends LiteralAnnotArgExtractor - - /** Represents an array of classfile annotation arguments */ - case class ArrayAnnotArg(args: Array[ClassfileAnnotArg]) - extends ClassfileAnnotArg with ArrayAnnotArgApi { - override def toString = args.mkString("[", ", ", "]") - } - implicit val ArrayAnnotArgTag = ClassTag[ArrayAnnotArg](classOf[ArrayAnnotArg]) - - object ArrayAnnotArg extends ArrayAnnotArgExtractor - - /** A specific annotation argument that encodes an array of bytes as an - * array of `Long`. The type of the argument declared in the annotation - * must be `String`. This specialised class is used to encode Scala - * signatures for reasons of efficiency, both in term of class-file size - * and in term of compiler performance. - */ - case class ScalaSigBytes(bytes: Array[Byte]) extends ClassfileAnnotArg { - override def toString = (bytes map { byte => (byte & 0xff).toHexString }).mkString("[ ", " ", " ]") - lazy val encodedBytes = ByteCodecs.encode(bytes) // TODO remove after migration to ASM-based GenJVM complete - def isLong: Boolean = (encodedBytes.length > 65535) // TODO remove after migration to ASM-based GenJVM complete - lazy val sevenBitsMayBeZero: Array[Byte] = { - mapToNextModSevenBits(scala.reflect.internal.pickling.ByteCodecs.encode8to7(bytes)) - } - def fitsInOneString: Boolean = { - val numZeros = (sevenBitsMayBeZero count { b => b == 0 }) - val res = (sevenBitsMayBeZero.length + numZeros) <= 65535 - assert(this.isLong == !res, "As things stand, can't just swap in `fitsInOneString()` for `isLong()`") - res - } - def sigAnnot: Type = - if (this.isLong) - definitions.ScalaLongSignatureAnnotation.tpe - else - definitions.ScalaSignatureAnnotation.tpe - - private def mapToNextModSevenBits(src: Array[Byte]): Array[Byte] = { - var i = 0 - val srclen = src.length - while (i < srclen) { - val in = src(i) - src(i) = (if (in == 0x7f) 0.toByte else (in + 1).toByte) - i += 1 - } - src - } - - } - - /** Represents a nested classfile annotation */ - case class NestedAnnotArg(annInfo: AnnotationInfo) extends ClassfileAnnotArg with NestedAnnotArgApi { - // The nested annotation should not have any Scala annotation arguments - assert(annInfo.args.isEmpty, annInfo.args) - override def toString = annInfo.toString - } - implicit val NestedAnnotArgTag = ClassTag[NestedAnnotArg](classOf[NestedAnnotArg]) - - object NestedAnnotArg extends NestedAnnotArgExtractor - - object AnnotationInfo extends AnnotationInfoExtractor { - def marker(atp: Type): AnnotationInfo = - apply(atp, Nil, Nil) - - def lazily(lazyInfo: => AnnotationInfo) = - new LazyAnnotationInfo(lazyInfo) - - def apply(atp: Type, args: List[Tree], assocs: List[(Name, ClassfileAnnotArg)]): AnnotationInfo = - new CompleteAnnotationInfo(atp, args, assocs) - - def unapply(info: AnnotationInfo): Option[(Type, List[Tree], List[(Name, ClassfileAnnotArg)])] = - Some((info.atp, info.args, info.assocs)) - } - - class CompleteAnnotationInfo( - val atp: Type, - val args: List[Tree], - val assocs: List[(Name, ClassfileAnnotArg)] - ) extends AnnotationInfo { - // Classfile annot: args empty. Scala annot: assocs empty. - assert(args.isEmpty || assocs.isEmpty, atp) - - // necessary for reification, see Reifiers.scala for more info - private var orig: Tree = EmptyTree - def original = orig - def setOriginal(t: Tree): this.type = { - orig = t - this setPos t.pos - this - } - - override def toString = ( - atp + - (if (!args.isEmpty) args.mkString("(", ", ", ")") else "") + - (if (!assocs.isEmpty) (assocs map { case (x, y) => x+" = "+y } mkString ("(", ", ", ")")) else "") - ) - } - - /** Symbol annotations parsed in `Namer` (typeCompleter of - * definitions) have to be lazy (#1782) - */ - final class LazyAnnotationInfo(lazyInfo: => AnnotationInfo) extends AnnotationInfo { - private var forced = false - private lazy val forcedInfo = - try { - val result = lazyInfo - if (result.pos == NoPosition) result setPos pos - result - } finally forced = true - - def atp: Type = forcedInfo.atp - def args: List[Tree] = forcedInfo.args - def assocs: List[(Name, ClassfileAnnotArg)] = forcedInfo.assocs - def original: Tree = forcedInfo.original - def setOriginal(t: Tree): this.type = { forcedInfo.setOriginal(t); this } - - // We should always be able to print things without forcing them. - override def toString = if (forced) forcedInfo.toString else "@" - - override def pos: Position = if (forced) forcedInfo.pos else NoPosition - } - - /** Typed information about an annotation. It can be attached to either - * a symbol or an annotated type. - * - * Annotations are written to the classfile as Java annotations - * if `atp` conforms to `ClassfileAnnotation` (the classfile parser adds - * this interface to any Java annotation class). - * - * Annotations are pickled (written to scala symtab attribute in the - * classfile) if `atp` inherits form `StaticAnnotation`. - * - * `args` stores arguments to Scala annotations, represented as typed - * trees. Note that these trees are not transformed by any phases - * following the type-checker. - * - * `assocs` stores arguments to classfile annotations as name-value pairs. - */ - sealed abstract class AnnotationInfo extends AnnotationInfoApi { - def atp: Type - def args: List[Tree] - def assocs: List[(Name, ClassfileAnnotArg)] - - // necessary for reification, see Reifiers.scala for more info - def original: Tree - def setOriginal(t: Tree): this.type - - // see annotationArgRewriter - lazy val isTrivial = atp.isTrivial && !hasArgWhich(_.isInstanceOf[This]) - - private var rawpos: Position = NoPosition - def pos = rawpos - def setPos(pos: Position): this.type = { // Syncnote: Setpos inaccessible to reflection, so no sync in rawpos necessary. - rawpos = pos - this - } - - /** Annotations annotating annotations are confusing so I drew - * an example. Given the following code: - * - * class A { - * @(deprecated @setter) @(inline @getter) - * var x: Int = 0 - * } - * - * For the setter `x_=` in A, annotations contains one AnnotationInfo = - * List(deprecated @setter) - * The single AnnotationInfo in that list, i.e. `@(deprecated @setter)`, has metaAnnotations = - * List(setter) - * - * Similarly, the getter `x` in A has an @inline annotation, which has - * metaAnnotations = List(getter). - */ - def symbol = atp.typeSymbol - - /** These are meta-annotations attached at the use site; they - * only apply to this annotation usage. For instance, in - * `@(deprecated @setter @field) val ...` - * metaAnnotations = List(setter, field). - */ - def metaAnnotations: List[AnnotationInfo] = atp match { - case AnnotatedType(metas, _, _) => metas - case _ => Nil - } - - /** The default kind of members to which this annotation is attached. - * For instance, for scala.deprecated defaultTargets = - * List(getter, setter, beanGetter, beanSetter). - */ - def defaultTargets = symbol.annotations map (_.symbol) filter isMetaAnnotation - // Test whether the typeSymbol of atp conforms to the given class. - def matches(clazz: Symbol) = symbol isNonBottomSubClass clazz - // All subtrees of all args are considered. - def hasArgWhich(p: Tree => Boolean) = args exists (_ exists p) - - /** Check whether the type or any of the arguments are erroneous */ - def isErroneous = atp.isErroneous || args.exists(_.isErroneous) - - def isStatic = symbol isNonBottomSubClass StaticAnnotationClass - - /** Check whether any of the arguments mention a symbol */ - def refsSymbol(sym: Symbol) = hasArgWhich(_.symbol == sym) - - /** Change all ident's with Symbol "from" to instead use symbol "to" */ - def substIdentSyms(from: Symbol, to: Symbol) = - AnnotationInfo(atp, args map (_ substituteSymbols (List(from), List(to))), assocs) setPos pos - - def stringArg(index: Int) = constantAtIndex(index) map (_.stringValue) - def intArg(index: Int) = constantAtIndex(index) map (_.intValue) - def symbolArg(index: Int) = argAtIndex(index) collect { - case Apply(fun, Literal(str) :: Nil) if fun.symbol == definitions.Symbol_apply => - newTermName(str.stringValue) - } - - // !!! when annotation arguments are not literals, but any sort of - // expression, there is a fair chance they will turn up here not as - // Literal(const) but some arbitrary AST. - def constantAtIndex(index: Int): Option[Constant] = - argAtIndex(index) collect { case Literal(x) => x } - - def argAtIndex(index: Int): Option[Tree] = - if (index < args.size) Some(args(index)) else None - - override def hashCode = atp.## + args.## + assocs.## - override def equals(other: Any) = other match { - case x: AnnotationInfo => (atp == x.atp) && (args == x.args) && (assocs == x.assocs) - case _ => false - } - } - - implicit val AnnotationInfoTag = ClassTag[AnnotationInfo](classOf[AnnotationInfo]) - - object UnmappableAnnotation extends CompleteAnnotationInfo(NoType, Nil, Nil) -} diff --git a/src/compiler/scala/reflect/internal/BaseTypeSeqs.scala b/src/compiler/scala/reflect/internal/BaseTypeSeqs.scala deleted file mode 100644 index e07f1bac49..0000000000 --- a/src/compiler/scala/reflect/internal/BaseTypeSeqs.scala +++ /dev/null @@ -1,260 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ -package scala.reflect -package internal - -// todo implement in terms of BitSet -import scala.collection.{ mutable, immutable } -import math.max -import util.Statistics._ - -/** A base type sequence (BaseTypeSeq) is an ordered sequence spanning all the base types - * of a type. It characterized by the following two laws: - * - * (1) Each element of `tp.baseTypeSeq` is a basetype of `tp` - * (2) For each basetype `bt1` of `tp` there is an element `bt` in `tp.baseTypeSeq` such that - * - * bt.typeSymbol = bt1.typeSymbol - * bt <: bt1 - * - * (3) The type symbols of different elements are different. - * - * Elements in the sequence are ordered by Symbol.isLess. - * @note base type sequences were called closures up to 2.7.1. The name has been changed - * to avoid confusion with function closures. - */ -trait BaseTypeSeqs { - this: SymbolTable => - import definitions._ - - protected def newBaseTypeSeq(parents: List[Type], elems: Array[Type]) = - new BaseTypeSeq(parents, elems) - - /** Note: constructor is protected to force everyone to use the factory method newBaseTypeSeq instead. - * This is necessary because when run from reflection every base type sequence needs to have a - * SynchronizedBaseTypeSeq as mixin. - */ - class BaseTypeSeq protected[BaseTypeSeqs] (private[BaseTypeSeqs] val parents: List[Type], private[BaseTypeSeqs] val elems: Array[Type]) { - self => - incCounter(baseTypeSeqCount) - incCounter(baseTypeSeqLenTotal, elems.length) - - /** The number of types in the sequence */ - def length: Int = elems.length - - // #3676 shows why we can't store NoType in elems to mark cycles - // (while NoType is in there to indicate a cycle in this BTS, during the execution of - // the mergePrefixAndArgs below, the elems get copied without the pending map, - // so that NoType's are seen instead of the original type --> spurious compile error) - private val pending = new mutable.BitSet(length) - - /** The type at i'th position in this sequence; lazy types are returned evaluated. */ - def apply(i: Int): Type = - if(pending contains i) { - pending.clear() - throw CyclicInheritance - } else - elems(i) match { - case rtp @ RefinedType(variants, decls) => - // can't assert decls.isEmpty; see t0764 - //if (!decls.isEmpty) assert(false, "computing closure of "+this+":"+this.isInstanceOf[RefinedType]+"/"+closureCache(j)) - //Console.println("compute closure of "+this+" => glb("+variants+")") - pending += i - try { - mergePrefixAndArgs(variants, -1, lubDepth(variants)) match { - case Some(tp0) => - pending(i) = false - elems(i) = tp0 - tp0 - case None => - typeError( - "no common type instance of base types "+(variants mkString ", and ")+" exists.") - } - } catch { - case CyclicInheritance => - typeError( - "computing the common type instance of base types "+(variants mkString ", and ")+" leads to a cycle.") - } - case tp => - tp - } - - def rawElem(i: Int) = elems(i) - - /** The type symbol of the type at i'th position in this sequence; - * no evaluation needed. - */ - def typeSymbol(i: Int): Symbol = { - elems(i) match { - case RefinedType(v :: vs, _) => v.typeSymbol - case tp => tp.typeSymbol - } - } - - /** Return all evaluated types in this sequence as a list */ - def toList: List[Type] = elems.toList - - def copy(head: Type, offset: Int): BaseTypeSeq = { - val arr = new Array[Type](elems.length + offset) - compat.Platform.arraycopy(elems, 0, arr, offset, elems.length) - arr(0) = head - newBaseTypeSeq(parents, arr) - } - - /** Compute new base type sequence with `tp` prepended to this sequence */ - def prepend(tp: Type): BaseTypeSeq = copy(tp, 1) - - /** Compute new base type sequence with `tp` replacing the head of this sequence */ - def updateHead(tp: Type): BaseTypeSeq = copy(tp, 0) - - /** Compute new base type sequence where every element is mapped - * with function `f`. Lazy types are mapped but not evaluated */ - def map(f: Type => Type): BaseTypeSeq = { - // inlined `elems map f` for performance - val len = length - var arr = new Array[Type](len) - var i = 0 - while (i < len) { - arr(i) = f(elems(i)) - i += 1 - } - newBaseTypeSeq(parents, arr) - } - - def lateMap(f: Type => Type): BaseTypeSeq = new MappedBaseTypeSeq(this, f) - - def exists(p: Type => Boolean): Boolean = elems exists p - - lazy val maxDepth: Int = maxDepthOfElems - - protected def maxDepthOfElems = { - var d = 0 - for (i <- 0 until length) d = max(d, maxDpth(elems(i))) - d - } - - /** The maximum depth of type `tp` */ - protected def maxDpth(tp: Type): Int = tp match { - case TypeRef(pre, sym, args) => - max(maxDpth(pre), maxDpth(args) + 1) - case RefinedType(parents, decls) => - max(maxDpth(parents), maxDpth(decls.toList.map(_.info)) + 1) - case TypeBounds(lo, hi) => - max(maxDpth(lo), maxDpth(hi)) - case MethodType(paramtypes, result) => - maxDpth(result) - case NullaryMethodType(result) => - maxDpth(result) - case PolyType(tparams, result) => - max(maxDpth(result), maxDpth(tparams map (_.info)) + 1) - case ExistentialType(tparams, result) => - max(maxDpth(result), maxDpth(tparams map (_.info)) + 1) - case _ => - 1 - } - - /** The maximum depth of all types `tps` */ - private def maxDpth(tps: Seq[Type]): Int = { - var d = 0 - for (tp <- tps) d = max(d, maxDpth(tp)) - d - } - - override def toString = elems.mkString("BTS(", ",", ")") - - private def typeError(msg: String): Nothing = - throw new TypeError( - "the type intersection "+(parents mkString " with ")+" is malformed"+ - "\n --- because ---\n"+msg) - } - - /** A merker object for a base type sequence that's no yet computed. - * used to catch inheritance cycles - */ - val undetBaseTypeSeq: BaseTypeSeq = newBaseTypeSeq(List(), Array()) - - /** Create a base type sequence consisting of a single type */ - def baseTypeSingletonSeq(tp: Type): BaseTypeSeq = newBaseTypeSeq(List(), Array(tp)) - - /** Create the base type sequence of a compound type wuth given tp.parents */ - def compoundBaseTypeSeq(tp: Type): BaseTypeSeq = { - val tsym = tp.typeSymbol - val parents = tp.parents -// Console.println("computing baseTypeSeq of " + tsym.tpe + " " + parents)//DEBUG - val buf = new mutable.ListBuffer[Type] - buf += tsym.tpe - var btsSize = 1 - if (parents.nonEmpty) { - val nparents = parents.length - val pbtss = new Array[BaseTypeSeq](nparents) - val index = new Array[Int](nparents) - var i = 0 - for (p <- parents) { - pbtss(i) = - if (p.baseTypeSeq eq undetBaseTypeSeq) AnyClass.info.baseTypeSeq - else p.baseTypeSeq - index(i) = 0 - i += 1 - } - def nextTypeSymbol(i: Int): Symbol = { - val j = index(i) - val pbts = pbtss(i) - if (j < pbts.length) pbts.typeSymbol(j) else AnyClass - } - def nextRawElem(i: Int): Type = { - val j = index(i) - val pbts = pbtss(i) - if (j < pbts.length) pbts.rawElem(j) else AnyClass.tpe - } - var minSym: Symbol = NoSymbol - while (minSym != AnyClass) { - minSym = nextTypeSymbol(0) - i = 1 - while (i < nparents) { - val nextSym = nextTypeSymbol(i) - if (nextSym isLess minSym) - minSym = nextSym - i += 1 - } - var minTypes: List[Type] = List() - i = 0 - while (i < nparents) { - if (nextTypeSymbol(i) == minSym) { - nextRawElem(i) match { - case RefinedType(variants, decls) => - for (tp <- variants) - if (!(minTypes exists (tp =:= _))) minTypes = tp :: minTypes - case tp => - if (!(minTypes exists (tp =:= _))) minTypes = tp :: minTypes - } - index(i) = index(i) + 1 - } - i += 1 - } - buf += intersectionType(minTypes) - btsSize += 1 - } - } - val elems = new Array[Type](btsSize) - buf.copyToArray(elems, 0) -// Console.println("computed baseTypeSeq of " + tsym.tpe + " " + parents + ": "+elems.toString)//DEBUG - newBaseTypeSeq(parents, elems) - } - - class MappedBaseTypeSeq(orig: BaseTypeSeq, f: Type => Type) extends BaseTypeSeq(orig.parents map f, orig.elems) { - override def apply(i: Int) = f(orig.apply(i)) - override def rawElem(i: Int) = f(orig.rawElem(i)) - override def typeSymbol(i: Int) = orig.typeSymbol(i) - override def toList = orig.toList map f - override def copy(head: Type, offset: Int) = (orig map f).copy(head, offset) - override def map(g: Type => Type) = lateMap(g) - override def lateMap(g: Type => Type) = orig.lateMap(x => g(f(x))) - override def exists(p: Type => Boolean) = elems exists (x => p(f(x))) - override protected def maxDepthOfElems: Int = (elems map (x => maxDpth(f(x)))).max - override def toString = elems.mkString("MBTS(", ",", ")") - } - - val CyclicInheritance = new Throwable -} diff --git a/src/compiler/scala/reflect/internal/BuildUtils.scala b/src/compiler/scala/reflect/internal/BuildUtils.scala deleted file mode 100644 index 3bde57ded8..0000000000 --- a/src/compiler/scala/reflect/internal/BuildUtils.scala +++ /dev/null @@ -1,69 +0,0 @@ -package scala.reflect -package internal - -import Flags._ - -trait BuildUtils extends base.BuildUtils { self: SymbolTable => - - class BuildImpl extends BuildBase { - - def selectType(owner: Symbol, name: String): TypeSymbol = { - val result = owner.info.decl(newTypeName(name)) - if (result ne NoSymbol) result.asTypeSymbol - else MissingRequirementError.notFound("type %s in %s".format(name, owner.fullName)) - } - - def selectTerm(owner: Symbol, name: String): TermSymbol = { - val sym = owner.info.decl(newTermName(name)) - val result = - if (sym.isOverloaded) sym.suchThat(!_.isMethod) - else sym - if (result ne NoSymbol) result.asTermSymbol - else MissingRequirementError.notFound("term %s in %s".format(name, owner.fullName)) - } - - def selectOverloadedMethod(owner: Symbol, name: String, index: Int): MethodSymbol = { - val result = owner.info.decl(newTermName(name)).alternatives(index) - if (result ne NoSymbol) result.asMethodSymbol - else MissingRequirementError.notFound("overloaded method %s #%d in %s".format(name, index, owner.fullName)) - } - - def newFreeTerm(name: String, info: Type, value: => Any, flags: Long = 0L, origin: String = null): FreeTermSymbol = - newFreeTermSymbol(newTermName(name), info, value, flags, origin) - - def newFreeType(name: String, info: Type, value: => Any, flags: Long = 0L, origin: String = null): FreeTypeSymbol = - newFreeTypeSymbol(newTypeName(name), info, value, (if (flags == 0L) PARAM else flags) | DEFERRED, origin) - - def newFreeExistential(name: String, info: Type, value: => Any, flags: Long = 0L, origin: String = null): FreeTypeSymbol = - newFreeTypeSymbol(newTypeName(name), info, value, (if (flags == 0L) EXISTENTIAL else flags) | DEFERRED, origin) - - def newNestedSymbol(owner: Symbol, name: Name, pos: Position, flags: Long, isClass: Boolean): Symbol = - owner.newNestedSymbol(name, pos, flags, isClass) - - def setAnnotations[S <: Symbol](sym: S, annots: List[AnnotationInfo]): S = - sym.setAnnotations(annots) - - def setTypeSignature[S <: Symbol](sym: S, tpe: Type): S = - sym.setTypeSignature(tpe) - - def flagsFromBits(bits: Long): FlagSet = bits - - def emptyValDef: ValDef = self.emptyValDef - - def This(sym: Symbol): Tree = self.This(sym) - - def Select(qualifier: Tree, sym: Symbol): Select = self.Select(qualifier, sym) - - def Ident(sym: Symbol): Ident = self.Ident(sym) - - def TypeTree(tp: Type): TypeTree = self.TypeTree(tp) - - def thisPrefix(sym: Symbol): Type = sym.thisPrefix - - def setType[T <: Tree](tree: T, tpe: Type): T = { tree.setType(tpe); tree } - - def setSymbol[T <: Tree](tree: T, sym: Symbol): T = { tree.setSymbol(sym); tree } - } - - val build: BuildBase = new BuildImpl -} diff --git a/src/compiler/scala/reflect/internal/CapturedVariables.scala b/src/compiler/scala/reflect/internal/CapturedVariables.scala deleted file mode 100644 index 77909d9157..0000000000 --- a/src/compiler/scala/reflect/internal/CapturedVariables.scala +++ /dev/null @@ -1,36 +0,0 @@ -package scala.reflect -package internal - -import Flags._ - -trait CapturedVariables { self: SymbolTable => - - import definitions._ - - /** Mark a variable as captured; i.e. force boxing in a *Ref type. - */ - def captureVariable(vble: Symbol): Unit = vble setFlag CAPTURED - - /** Mark given identifier as a reference to a captured variable itself - * suppressing dereferencing with the `elem` field. - */ - def referenceCapturedVariable(vble: Symbol): Tree = ReferenceToBoxed(Ident(vble)) - - /** Convert type of a captured variable to *Ref type. - */ - def capturedVariableType(vble: Symbol): Type = - capturedVariableType(vble, NoType, false) - - /** Convert type of a captured variable to *Ref type. - */ - def capturedVariableType(vble: Symbol, tpe: Type = NoType, erasedTypes: Boolean = false): Type = { - val tpe1 = if (tpe == NoType) vble.tpe else tpe - val symClass = tpe1.typeSymbol - def refType(valueRef: Map[Symbol, Symbol], objectRefClass: Symbol) = - if (isPrimitiveValueClass(symClass) && symClass != UnitClass) valueRef(symClass).tpe - else if (erasedTypes) objectRefClass.tpe - else appliedType(objectRefClass, tpe) - if (vble.hasAnnotation(VolatileAttr)) refType(volatileRefClass, VolatileObjectRefClass) - else refType(refClass, ObjectRefClass) - } -} diff --git a/src/compiler/scala/reflect/internal/Chars.scala b/src/compiler/scala/reflect/internal/Chars.scala deleted file mode 100644 index 50ec71094a..0000000000 --- a/src/compiler/scala/reflect/internal/Chars.scala +++ /dev/null @@ -1,98 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2006-2011 LAMP/EPFL - * @author Martin Odersky - */ -package scala.reflect -package internal - -import annotation.{ tailrec, switch } -import java.lang.{ Character => JCharacter } -import language.postfixOps - -/** Contains constants and classifier methods for characters */ -trait Chars { - // Be very careful touching these. - // Apparently trivial changes to the way you write these constants - // will cause Scanners.scala to go from a nice efficient switch to - // a ghastly nested if statement which will bring the type checker - // to its knees. See ticket #1456 - // Martin: (this should be verified now that the pattern rules have been redesigned). - final val LF = '\u000A' - final val FF = '\u000C' - final val CR = '\u000D' - final val SU = '\u001A' - - /** Convert a character digit to an Int according to given base, - * -1 if no success - */ - def digit2int(ch: Char, base: Int): Int = { - val num = ( - if (ch <= '9') ch - '0' - else if ('a' <= ch && ch <= 'z') ch - 'a' + 10 - else if ('A' <= ch && ch <= 'Z') ch - 'A' + 10 - else -1 - ) - if (0 <= num && num < base) num else -1 - } - /** Buffer for creating '\ u XXXX' strings. */ - private[this] val char2uescapeArray = Array[Char]('\\', 'u', 0, 0, 0, 0) - - /** Convert a character to a backslash-u escape */ - def char2uescape(c: Char): String = { - @inline def hexChar(ch: Int): Char = - ( if (ch < 10) '0' else 'A' - 10 ) + ch toChar - - char2uescapeArray(2) = hexChar((c >> 12) ) - char2uescapeArray(3) = hexChar((c >> 8) % 16) - char2uescapeArray(4) = hexChar((c >> 4) % 16) - char2uescapeArray(5) = hexChar((c ) % 16) - - new String(char2uescapeArray) - } - - /** Is character a line break? */ - @inline def isLineBreakChar(c: Char) = (c: @switch) match { - case LF|FF|CR|SU => true - case _ => false - } - - /** Is character a whitespace character (but not a new line)? */ - def isWhitespace(c: Char) = - c == ' ' || c == '\t' || c == CR - - /** Can character form part of a doc comment variable $xxx? */ - def isVarPart(c: Char) = - '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' - - /** Can character start an alphanumeric Scala identifier? */ - def isIdentifierStart(c: Char): Boolean = - (c == '_') || (c == '$') || Character.isUnicodeIdentifierStart(c) - - /** Can character form part of an alphanumeric Scala identifier? */ - def isIdentifierPart(c: Char) = - (c == '$') || Character.isUnicodeIdentifierPart(c) - - /** Is character a math or other symbol in Unicode? */ - def isSpecial(c: Char) = { - val chtp = Character.getType(c) - chtp == Character.MATH_SYMBOL.toInt || chtp == Character.OTHER_SYMBOL.toInt - } - - private final val otherLetters = Set[Char]('\u0024', '\u005F') // '$' and '_' - private final val letterGroups = { - import JCharacter._ - Set[Byte](LOWERCASE_LETTER, UPPERCASE_LETTER, OTHER_LETTER, TITLECASE_LETTER, LETTER_NUMBER) - } - def isScalaLetter(ch: Char) = letterGroups(JCharacter.getType(ch).toByte) || otherLetters(ch) - - /** Can character form part of a Scala operator name? */ - def isOperatorPart(c : Char) : Boolean = (c: @switch) match { - case '~' | '!' | '@' | '#' | '%' | - '^' | '*' | '+' | '-' | '<' | - '>' | '?' | ':' | '=' | '&' | - '|' | '/' | '\\' => true - case c => isSpecial(c) - } -} - -object Chars extends Chars { } diff --git a/src/compiler/scala/reflect/internal/ClassfileConstants.scala b/src/compiler/scala/reflect/internal/ClassfileConstants.scala deleted file mode 100644 index 3346e9cccb..0000000000 --- a/src/compiler/scala/reflect/internal/ClassfileConstants.scala +++ /dev/null @@ -1,390 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import annotation.switch - -object ClassfileConstants { - - final val JAVA_MAGIC = 0xCAFEBABE - final val JAVA_MAJOR_VERSION = 45 - final val JAVA_MINOR_VERSION = 3 - - /** (see http://java.sun.com/docs/books/jvms/second_edition/jvms-clarify.html) - * - * If the `ACC_INTERFACE` flag is set, the `ACC_ABSTRACT` flag must also - * be set (ch. 2.13.1). - * - * A class file cannot have both its `ACC_FINAL` and `ACC_ABSTRACT` flags - * set (ch. 2.8.2). - * - * A field may have at most one of its `ACC_PRIVATE`, `ACC_PROTECTED`, - * `ACC_PUBLIC` flags set (ch. 2.7.4). - * - * A field may not have both its `ACC_FINAL` and `ACC_VOLATILE` flags set - * (ch. 2.9.1). - * - * If a method has its `ACC_ABSTRACT` flag set it must not have any of its - * `ACC_FINAL`, `ACC_NATIVE`, `ACC_PRIVATE`, `ACC_STATIC`, `ACC_STRICT`, - * or `ACC_SYNCHRONIZED` flags set (ch. 2.13.3.2). - * - * All interface methods must have their `ACC_ABSTRACT` and - * `ACC_PUBLIC` flags set. - * - * Note for future reference: see this thread on ACC_SUPER and - * how its enforcement differs on the android vm. - * https://groups.google.com/forum/?hl=en#!topic/jvm-languages/jVhzvq8-ZIk - * - */ // Class Field Method - final val JAVA_ACC_PUBLIC = 0x0001 // X X X - final val JAVA_ACC_PRIVATE = 0x0002 // X X - final val JAVA_ACC_PROTECTED = 0x0004 // X X - final val JAVA_ACC_STATIC = 0x0008 // X X - final val JAVA_ACC_FINAL = 0x0010 // X X X - final val JAVA_ACC_SUPER = 0x0020 // X - final val JAVA_ACC_SYNCHRONIZED = 0x0020 // X - final val JAVA_ACC_VOLATILE = 0x0040 // X - final val JAVA_ACC_BRIDGE = 0x0040 // X - final val JAVA_ACC_TRANSIENT = 0x0080 // X - final val JAVA_ACC_VARARGS = 0x0080 // X - final val JAVA_ACC_NATIVE = 0x0100 // X - final val JAVA_ACC_INTERFACE = 0x0200 // X - final val JAVA_ACC_ABSTRACT = 0x0400 // X X - final val JAVA_ACC_STRICT = 0x0800 // X - final val JAVA_ACC_SYNTHETIC = 0x1000 // X X X - final val JAVA_ACC_ANNOTATION = 0x2000 // X - final val JAVA_ACC_ENUM = 0x4000 // X X - - // tags describing the type of a literal in the constant pool - final val CONSTANT_UTF8 = 1 - final val CONSTANT_UNICODE = 2 - final val CONSTANT_INTEGER = 3 - final val CONSTANT_FLOAT = 4 - final val CONSTANT_LONG = 5 - final val CONSTANT_DOUBLE = 6 - final val CONSTANT_CLASS = 7 - final val CONSTANT_STRING = 8 - final val CONSTANT_FIELDREF = 9 - final val CONSTANT_METHODREF = 10 - final val CONSTANT_INTFMETHODREF = 11 - final val CONSTANT_NAMEANDTYPE = 12 - - // tags describing the type of a literal in attribute values - final val BYTE_TAG = 'B' - final val CHAR_TAG = 'C' - final val DOUBLE_TAG = 'D' - final val FLOAT_TAG = 'F' - final val INT_TAG = 'I' - final val LONG_TAG = 'J' - final val SHORT_TAG = 'S' - final val BOOL_TAG = 'Z' - final val STRING_TAG = 's' - final val ENUM_TAG = 'e' - final val CLASS_TAG = 'c' - final val ARRAY_TAG = '[' - final val VOID_TAG = 'V' - final val TVAR_TAG = 'T' - final val OBJECT_TAG = 'L' - final val ANNOTATION_TAG = '@' - final val SCALA_NOTHING = "scala.runtime.Nothing$" - final val SCALA_NULL = "scala.runtime.Null$" - - - // tags describing the type of newarray - final val T_BOOLEAN = 4 - final val T_CHAR = 5 - final val T_FLOAT = 6 - final val T_DOUBLE = 7 - final val T_BYTE = 8 - final val T_SHORT = 9 - final val T_INT = 10 - final val T_LONG = 11 - - // JVM mnemonics - final val nop = 0x00 - final val aconst_null = 0x01 - final val iconst_m1 = 0x02 - - final val iconst_0 = 0x03 - final val iconst_1 = 0x04 - final val iconst_2 = 0x05 - final val iconst_3 = 0x06 - final val iconst_4 = 0x07 - final val iconst_5 = 0x08 - - final val lconst_0 = 0x09 - final val lconst_1 = 0x0a - final val fconst_0 = 0x0b - final val fconst_1 = 0x0c - final val fconst_2 = 0x0d - final val dconst_0 = 0x0e - final val dconst_1 = 0x0f - - final val bipush = 0x10 - final val sipush = 0x11 - final val ldc = 0x12 - final val ldc_w = 0x13 - final val ldc2_w = 0x14 - - final val iload = 0x15 - final val lload = 0x16 - final val fload = 0x17 - final val dload = 0x18 - final val aload = 0x19 - - final val iload_0 = 0x1a - final val iload_1 = 0x1b - final val iload_2 = 0x1c - final val iload_3 = 0x1d - final val lload_0 = 0x1e - final val lload_1 = 0x1f - final val lload_2 = 0x20 - final val lload_3 = 0x21 - final val fload_0 = 0x22 - final val fload_1 = 0x23 - final val fload_2 = 0x24 - final val fload_3 = 0x25 - final val dload_0 = 0x26 - final val dload_1 = 0x27 - final val dload_2 = 0x28 - final val dload_3 = 0x29 - final val aload_0 = 0x2a - final val aload_1 = 0x2b - final val aload_2 = 0x2c - final val aload_3 = 0x2d - final val iaload = 0x2e - final val laload = 0x2f - final val faload = 0x30 - final val daload = 0x31 - final val aaload = 0x32 - final val baload = 0x33 - final val caload = 0x34 - final val saload = 0x35 - - final val istore = 0x36 - final val lstore = 0x37 - final val fstore = 0x38 - final val dstore = 0x39 - final val astore = 0x3a - final val istore_0 = 0x3b - final val istore_1 = 0x3c - final val istore_2 = 0x3d - final val istore_3 = 0x3e - final val lstore_0 = 0x3f - final val lstore_1 = 0x40 - final val lstore_2 = 0x41 - final val lstore_3 = 0x42 - final val fstore_0 = 0x43 - final val fstore_1 = 0x44 - final val fstore_2 = 0x45 - final val fstore_3 = 0x46 - final val dstore_0 = 0x47 - final val dstore_1 = 0x48 - final val dstore_2 = 0x49 - final val dstore_3 = 0x4a - final val astore_0 = 0x4b - final val astore_1 = 0x4c - final val astore_2 = 0x4d - final val astore_3 = 0x4e - final val iastore = 0x4f - final val lastore = 0x50 - final val fastore = 0x51 - final val dastore = 0x52 - final val aastore = 0x53 - final val bastore = 0x54 - final val castore = 0x55 - final val sastore = 0x56 - - final val pop = 0x57 - final val pop2 = 0x58 - final val dup = 0x59 - final val dup_x1 = 0x5a - final val dup_x2 = 0x5b - final val dup2 = 0x5c - final val dup2_x1 = 0x5d - final val dup2_x2 = 0x5e - final val swap = 0x5f - - final val iadd = 0x60 - final val ladd = 0x61 - final val fadd = 0x62 - final val dadd = 0x63 - final val isub = 0x64 - final val lsub = 0x65 - final val fsub = 0x66 - final val dsub = 0x67 - final val imul = 0x68 - final val lmul = 0x69 - final val fmul = 0x6a - final val dmul = 0x6b - final val idiv = 0x6c - final val ldiv = 0x6d - final val fdiv = 0x6e - final val ddiv = 0x6f - final val irem = 0x70 - final val lrem = 0x71 - final val frem = 0x72 - final val drem = 0x73 - - final val ineg = 0x74 - final val lneg = 0x75 - final val fneg = 0x76 - final val dneg = 0x77 - - final val ishl = 0x78 - final val lshl = 0x79 - final val ishr = 0x7a - final val lshr = 0x7b - final val iushr = 0x7c - final val lushr = 0x7d - final val iand = 0x7e - final val land = 0x7f - final val ior = 0x80 - final val lor = 0x81 - final val ixor = 0x82 - final val lxor = 0x83 - final val iinc = 0x84 - - final val i2l = 0x85 - final val i2f = 0x86 - final val i2d = 0x87 - final val l2i = 0x88 - final val l2f = 0x89 - final val l2d = 0x8a - final val f2i = 0x8b - final val f2l = 0x8c - final val f2d = 0x8d - final val d2i = 0x8e - final val d2l = 0x8f - final val d2f = 0x90 - final val i2b = 0x91 - final val i2c = 0x92 - final val i2s = 0x93 - - final val lcmp = 0x94 - final val fcmpl = 0x95 - final val fcmpg = 0x96 - final val dcmpl = 0x97 - final val dcmpg = 0x98 - - final val ifeq = 0x99 - final val ifne = 0x9a - final val iflt = 0x9b - final val ifge = 0x9c - final val ifgt = 0x9d - final val ifle = 0x9e - final val if_icmpeq = 0x9f - final val if_icmpne = 0xa0 - final val if_icmplt = 0xa1 - final val if_icmpge = 0xa2 - final val if_icmpgt = 0xa3 - final val if_icmple = 0xa4 - final val if_acmpeq = 0xa5 - final val if_acmpne = 0xa6 - final val goto = 0xa7 - final val jsr = 0xa8 - final val ret = 0xa9 - final val tableswitch = 0xaa - final val lookupswitch = 0xab - final val ireturn = 0xac - final val lreturn = 0xad - final val freturn = 0xae - final val dreturn = 0xaf - final val areturn = 0xb0 - final val return_ = 0xb1 - - final val getstatic = 0xb2 - final val putstatic = 0xb3 - final val getfield = 0xb4 - final val putfield = 0xb5 - - final val invokevirtual = 0xb6 - final val invokespecial = 0xb7 - final val invokestatic = 0xb8 - final val invokeinterface = 0xb9 - final val xxxunusedxxxx = 0xba - - final val new_ = 0xbb - final val newarray = 0xbc - final val anewarray = 0xbd - final val arraylength = 0xbe - final val athrow = 0xbf - final val checkcast = 0xc0 - final val instanceof = 0xc1 - final val monitorenter = 0xc2 - final val monitorexit = 0xc3 - final val wide = 0xc4 - final val multianewarray = 0xc5 - final val ifnull = 0xc6 - final val ifnonnull = 0xc7 - final val goto_w = 0xc8 - final val jsr_w = 0xc9 - - // reserved opcodes - final val breakpoint = 0xca - final val impdep1 = 0xfe - final val impdep2 = 0xff - - abstract class FlagTranslation { - import Flags._ - - private var isAnnotation = false - private var isClass = false - private def initFields(flags: Int) = { - isAnnotation = (flags & JAVA_ACC_ANNOTATION) != 0 - isClass = false - } - private def translateFlag(jflag: Int): Long = (jflag: @switch) match { - case JAVA_ACC_PRIVATE => PRIVATE - case JAVA_ACC_PROTECTED => PROTECTED - case JAVA_ACC_FINAL => FINAL - case JAVA_ACC_SYNTHETIC => SYNTHETIC - case JAVA_ACC_STATIC => STATIC - case JAVA_ACC_ABSTRACT => if (isAnnotation) 0L else if (isClass) ABSTRACT else DEFERRED - case JAVA_ACC_INTERFACE => if (isAnnotation) 0L else TRAIT | INTERFACE | ABSTRACT - case _ => 0L - } - private def translateFlags(jflags: Int, baseFlags: Long): Long = { - var res: Long = JAVA | baseFlags - /** fast, elegant, maintainable, pick any two... */ - res |= translateFlag(jflags & JAVA_ACC_PRIVATE) - res |= translateFlag(jflags & JAVA_ACC_PROTECTED) - res |= translateFlag(jflags & JAVA_ACC_FINAL) - res |= translateFlag(jflags & JAVA_ACC_SYNTHETIC) - res |= translateFlag(jflags & JAVA_ACC_STATIC) - res |= translateFlag(jflags & JAVA_ACC_ABSTRACT) - res |= translateFlag(jflags & JAVA_ACC_INTERFACE) - res - } - - def classFlags(jflags: Int): Long = { - initFields(jflags) - isClass = true - translateFlags(jflags, 0) - } - def fieldFlags(jflags: Int): Long = { - initFields(jflags) - translateFlags(jflags, if ((jflags & JAVA_ACC_FINAL) == 0) MUTABLE else 0) - } - def methodFlags(jflags: Int): Long = { - initFields(jflags) - translateFlags(jflags, if ((jflags & JAVA_ACC_BRIDGE) != 0) BRIDGE else 0) - } - } - object FlagTranslation extends FlagTranslation { } - - def toScalaMethodFlags(flags: Int): Long = FlagTranslation methodFlags flags - def toScalaClassFlags(flags: Int): Long = FlagTranslation classFlags flags - def toScalaFieldFlags(flags: Int): Long = FlagTranslation fieldFlags flags - - @deprecated("Use another method in this object", "2.10.0") - def toScalaFlags(flags: Int, isClass: Boolean = false, isField: Boolean = false): Long = ( - if (isClass) toScalaClassFlags(flags) - else if (isField) toScalaFieldFlags(flags) - else toScalaMethodFlags(flags) - ) -} diff --git a/src/compiler/scala/reflect/internal/Constants.scala b/src/compiler/scala/reflect/internal/Constants.scala deleted file mode 100644 index 820dfe0868..0000000000 --- a/src/compiler/scala/reflect/internal/Constants.scala +++ /dev/null @@ -1,240 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import java.lang.Integer.toOctalString -import annotation.switch - -trait Constants extends api.Constants { - self: SymbolTable => - - import definitions._ - - final val NoTag = 0 - final val UnitTag = 1 - final val BooleanTag = 2 - final val ByteTag = 3 - final val ShortTag = 4 - final val CharTag = 5 - final val IntTag = 6 - final val LongTag = 7 - final val FloatTag = 8 - final val DoubleTag = 9 - final val StringTag = 10 - final val NullTag = 11 - final val ClazzTag = 12 - // For supporting java enumerations inside java annotations (see ClassfileParser) - final val EnumTag = 13 - - case class Constant(value: Any) extends ConstantApi { - val tag: Int = value match { - case null => NullTag - case x: Unit => UnitTag - case x: Boolean => BooleanTag - case x: Byte => ByteTag - case x: Short => ShortTag - case x: Int => IntTag - case x: Long => LongTag - case x: Float => FloatTag - case x: Double => DoubleTag - case x: String => StringTag - case x: Char => CharTag - case x: Type => ClazzTag - case x: Symbol => EnumTag - case _ => throw new Error("bad constant value: " + value + " of class " + value.getClass) - } - - def isByteRange: Boolean = isIntRange && Byte.MinValue <= intValue && intValue <= Byte.MaxValue - def isShortRange: Boolean = isIntRange && Short.MinValue <= intValue && intValue <= Short.MaxValue - def isCharRange: Boolean = isIntRange && Char.MinValue <= intValue && intValue <= Char.MaxValue - def isIntRange: Boolean = ByteTag <= tag && tag <= IntTag - def isLongRange: Boolean = ByteTag <= tag && tag <= LongTag - def isFloatRange: Boolean = ByteTag <= tag && tag <= FloatTag - def isNumeric: Boolean = ByteTag <= tag && tag <= DoubleTag - def isNonUnitAnyVal = BooleanTag <= tag && tag <= DoubleTag - def isAnyVal = UnitTag <= tag && tag <= DoubleTag - - def tpe: Type = tag match { - case UnitTag => UnitClass.tpe - case BooleanTag => BooleanClass.tpe - case ByteTag => ByteClass.tpe - case ShortTag => ShortClass.tpe - case CharTag => CharClass.tpe - case IntTag => IntClass.tpe - case LongTag => LongClass.tpe - case FloatTag => FloatClass.tpe - case DoubleTag => DoubleClass.tpe - case StringTag => StringClass.tpe - case NullTag => NullClass.tpe - case ClazzTag => ClassType(value.asInstanceOf[Type]) - case EnumTag => - // given (in java): "class A { enum E { VAL1 } }" - // - symbolValue: the symbol of the actual enumeration value (VAL1) - // - .owner: the ModuleClasSymbol of the enumeration (object E) - // - .linkedClassOfClass: the ClassSymbol of the enumeration (class E) - symbolValue.owner.linkedClassOfClass.tpe - } - - /** We need the equals method to take account of tags as well as values. - */ - override def equals(other: Any): Boolean = other match { - case that: Constant => - this.tag == that.tag && - (this.value == that.value || this.isNaN && that.isNaN) - case _ => false - } - - def isNaN = value match { - case f: Float => f.isNaN - case d: Double => d.isNaN - case _ => false - } - - def booleanValue: Boolean = - if (tag == BooleanTag) value.asInstanceOf[Boolean] - else throw new Error("value " + value + " is not a boolean"); - - def byteValue: Byte = tag match { - case ByteTag => value.asInstanceOf[Byte] - case ShortTag => value.asInstanceOf[Short].toByte - case CharTag => value.asInstanceOf[Char].toByte - case IntTag => value.asInstanceOf[Int].toByte - case LongTag => value.asInstanceOf[Long].toByte - case FloatTag => value.asInstanceOf[Float].toByte - case DoubleTag => value.asInstanceOf[Double].toByte - case _ => throw new Error("value " + value + " is not a Byte") - } - - def shortValue: Short = tag match { - case ByteTag => value.asInstanceOf[Byte].toShort - case ShortTag => value.asInstanceOf[Short] - case CharTag => value.asInstanceOf[Char].toShort - case IntTag => value.asInstanceOf[Int].toShort - case LongTag => value.asInstanceOf[Long].toShort - case FloatTag => value.asInstanceOf[Float].toShort - case DoubleTag => value.asInstanceOf[Double].toShort - case _ => throw new Error("value " + value + " is not a Short") - } - - def charValue: Char = tag match { - case ByteTag => value.asInstanceOf[Byte].toChar - case ShortTag => value.asInstanceOf[Short].toChar - case CharTag => value.asInstanceOf[Char] - case IntTag => value.asInstanceOf[Int].toChar - case LongTag => value.asInstanceOf[Long].toChar - case FloatTag => value.asInstanceOf[Float].toChar - case DoubleTag => value.asInstanceOf[Double].toChar - case _ => throw new Error("value " + value + " is not a Char") - } - - def intValue: Int = tag match { - case ByteTag => value.asInstanceOf[Byte].toInt - case ShortTag => value.asInstanceOf[Short].toInt - case CharTag => value.asInstanceOf[Char].toInt - case IntTag => value.asInstanceOf[Int] - case LongTag => value.asInstanceOf[Long].toInt - case FloatTag => value.asInstanceOf[Float].toInt - case DoubleTag => value.asInstanceOf[Double].toInt - case _ => throw new Error("value " + value + " is not an Int") - } - - def longValue: Long = tag match { - case ByteTag => value.asInstanceOf[Byte].toLong - case ShortTag => value.asInstanceOf[Short].toLong - case CharTag => value.asInstanceOf[Char].toLong - case IntTag => value.asInstanceOf[Int].toLong - case LongTag => value.asInstanceOf[Long] - case FloatTag => value.asInstanceOf[Float].toLong - case DoubleTag => value.asInstanceOf[Double].toLong - case _ => throw new Error("value " + value + " is not a Long") - } - - def floatValue: Float = tag match { - case ByteTag => value.asInstanceOf[Byte].toFloat - case ShortTag => value.asInstanceOf[Short].toFloat - case CharTag => value.asInstanceOf[Char].toFloat - case IntTag => value.asInstanceOf[Int].toFloat - case LongTag => value.asInstanceOf[Long].toFloat - case FloatTag => value.asInstanceOf[Float] - case DoubleTag => value.asInstanceOf[Double].toFloat - case _ => throw new Error("value " + value + " is not a Float") - } - - def doubleValue: Double = tag match { - case ByteTag => value.asInstanceOf[Byte].toDouble - case ShortTag => value.asInstanceOf[Short].toDouble - case CharTag => value.asInstanceOf[Char].toDouble - case IntTag => value.asInstanceOf[Int].toDouble - case LongTag => value.asInstanceOf[Long].toDouble - case FloatTag => value.asInstanceOf[Float].toDouble - case DoubleTag => value.asInstanceOf[Double] - case _ => throw new Error("value " + value + " is not a Double") - } - - /** Convert constant value to conform to given type. - */ - def convertTo(pt: Type): Constant = { - val target = pt.typeSymbol - if (target == tpe.typeSymbol) - this - else if (target == ByteClass && isByteRange) - Constant(byteValue) - else if (target == ShortClass && isShortRange) - Constant(shortValue) - else if (target == CharClass && isCharRange) - Constant(charValue) - else if (target == IntClass && isIntRange) - Constant(intValue) - else if (target == LongClass && isLongRange) - Constant(longValue) - else if (target == FloatClass && isFloatRange) - Constant(floatValue) - else if (target == DoubleClass && isNumeric) - Constant(doubleValue) - else - null - } - - def stringValue: String = - if (value == null) "null" - else if (tag == ClazzTag) signature(typeValue) - else value.toString() - - @switch def escapedChar(ch: Char): String = ch match { - case '\b' => "\\b" - case '\t' => "\\t" - case '\n' => "\\n" - case '\f' => "\\f" - case '\r' => "\\r" - case '"' => "\\\"" - case '\'' => "\\\'" - case '\\' => "\\\\" - case _ => if (ch.isControl) "\\0" + toOctalString(ch) else String.valueOf(ch) - } - - def escapedStringValue: String = { - def escape(text: String): String = text flatMap escapedChar - tag match { - case NullTag => "null" - case StringTag => "\"" + escape(stringValue) + "\"" - case ClazzTag => "classOf[" + signature(typeValue) + "]" - case CharTag => "'" + escapedChar(charValue) + "'" - case LongTag => longValue.toString() + "L" - case EnumTag => symbolValue.name.toString() - case _ => String.valueOf(value) - } - } - def typeValue: Type = value.asInstanceOf[Type] - def symbolValue: Symbol = value.asInstanceOf[Symbol] - - override def hashCode: Int = value.## * 41 + 17 - } - - object Constant extends ConstantExtractor - - implicit val ConstantTag = ClassTag[Constant](classOf[Constant]) -} diff --git a/src/compiler/scala/reflect/internal/Definitions.scala b/src/compiler/scala/reflect/internal/Definitions.scala deleted file mode 100644 index d55b38224d..0000000000 --- a/src/compiler/scala/reflect/internal/Definitions.scala +++ /dev/null @@ -1,1241 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import annotation.{ switch, meta } -import scala.collection.{ mutable, immutable } -import Flags._ -import PartialFunction._ -import scala.reflect.base.{Universe => BaseUniverse} - -trait Definitions extends api.StandardDefinitions { - self: SymbolTable => - - import rootMirror.{getModule, getClassByName, getRequiredClass, getRequiredModule, getRequiredPackage, getClassIfDefined, getModuleIfDefined, getPackageObject, getPackageObjectIfDefined, requiredClass, requiredModule} - - object definitions extends DefinitionsClass - - // [Eugene] find a way to make these non-lazy - lazy val ByteTpe = definitions.ByteClass.asType - lazy val ShortTpe = definitions.ShortClass.asType - lazy val CharTpe = definitions.CharClass.asType - lazy val IntTpe = definitions.IntClass.asType - lazy val LongTpe = definitions.LongClass.asType - lazy val FloatTpe = definitions.FloatClass.asType - lazy val DoubleTpe = definitions.DoubleClass.asType - lazy val BooleanTpe = definitions.BooleanClass.asType - lazy val UnitTpe = definitions.UnitClass.asType - lazy val AnyTpe = definitions.AnyClass.asType - lazy val ObjectTpe = definitions.ObjectClass.asType - lazy val AnyValTpe = definitions.AnyValClass.asType - lazy val AnyRefTpe = definitions.AnyRefClass.asType - lazy val NothingTpe = definitions.NothingClass.asType - lazy val NullTpe = definitions.NullClass.asType - lazy val StringTpe = definitions.StringClass.asType - - /** Since both the value parameter types and the result type may - * require access to the type parameter symbols, we model polymorphic - * creation as a function from those symbols to (formal types, result type). - * The Option is to distinguish between nullary methods and empty-param-list - * methods. - */ - private type PolyMethodCreator = List[Symbol] => (Option[List[Type]], Type) - - private def enterNewClass(owner: Symbol, name: TypeName, parents: List[Type], flags: Long = 0L): ClassSymbol = { - val clazz = owner.newClassSymbol(name, NoPosition, flags) - clazz setInfoAndEnter ClassInfoType(parents, newScope, clazz) - } - private def newMethod(owner: Symbol, name: TermName, formals: List[Type], restpe: Type, flags: Long = 0L): MethodSymbol = { - val msym = owner.newMethod(name.encode, NoPosition, flags) - val params = msym.newSyntheticValueParams(formals) - msym setInfo MethodType(params, restpe) - } - private def enterNewMethod(owner: Symbol, name: TermName, formals: List[Type], restpe: Type, flags: Long = 0L): MethodSymbol = - owner.info.decls enter newMethod(owner, name, formals, restpe, flags) - - // the scala value classes - trait ValueClassDefinitions { - self: DefinitionsClass => - - import ClassfileConstants._ - - private val nameToWeight = Map[Name, Int]( - tpnme.Byte -> 2, - tpnme.Char -> 3, - tpnme.Short -> 4, - tpnme.Int -> 12, - tpnme.Long -> 24, - tpnme.Float -> 48, - tpnme.Double -> 96 - ) - - private val nameToTag = Map[Name, Char]( - tpnme.Byte -> BYTE_TAG, - tpnme.Char -> CHAR_TAG, - tpnme.Short -> SHORT_TAG, - tpnme.Int -> INT_TAG, - tpnme.Long -> LONG_TAG, - tpnme.Float -> FLOAT_TAG, - tpnme.Double -> DOUBLE_TAG, - tpnme.Boolean -> BOOL_TAG, - tpnme.Unit -> VOID_TAG - ) - - private def catastrophicFailure() = - abort("Could not find value classes! This is a catastrophic failure. scala " + - scala.util.Properties.versionString) - - private def valueClassSymbol(name: TypeName): ClassSymbol = { - getMember(ScalaPackageClass, name) match { - case x: ClassSymbol => x - case _ => catastrophicFailure() - } - } - private def valueClassCompanion(name: TermName): ModuleSymbol = { - getMember(ScalaPackageClass, name) match { - case x: ModuleSymbol => x - case _ => catastrophicFailure() - } - } - private def valueCompanionMember(className: Name, methodName: TermName): TermSymbol = - getMemberMethod(valueClassCompanion(className.toTermName).moduleClass, methodName) - - private def classesMap[T](f: Name => T) = symbolsMap(ScalaValueClassesNoUnit, f) - private def symbolsMap[T](syms: List[Symbol], f: Name => T): Map[Symbol, T] = mapFrom(syms)(x => f(x.name)) - private def symbolsMapFilt[T](syms: List[Symbol], p: Name => Boolean, f: Name => T) = symbolsMap(syms filter (x => p(x.name)), f) - - private def boxedName(name: Name) = sn.Boxed(name.toTypeName) - - lazy val abbrvTag = symbolsMap(ScalaValueClasses, nameToTag) withDefaultValue OBJECT_TAG - lazy val numericWeight = symbolsMapFilt(ScalaValueClasses, nameToWeight.keySet, nameToWeight) - lazy val boxedModule = classesMap(x => getModule(boxedName(x))) - lazy val boxedClass = classesMap(x => getClassByName(boxedName(x))) - lazy val refClass = classesMap(x => getRequiredClass("scala.runtime." + x + "Ref")) - lazy val volatileRefClass = classesMap(x => getRequiredClass("scala.runtime.Volatile" + x + "Ref")) - lazy val boxMethod = classesMap(x => valueCompanionMember(x, nme.box)) - lazy val unboxMethod = classesMap(x => valueCompanionMember(x, nme.unbox)) - - def isNumericSubClass(sub: Symbol, sup: Symbol) = ( - (numericWeight contains sub) - && (numericWeight contains sup) - && (numericWeight(sup) % numericWeight(sub) == 0) - ) - - /** Is symbol a numeric value class? */ - def isNumericValueClass(sym: Symbol) = ScalaNumericValueClasses contains sym - - def isGetClass(sym: Symbol) = - (sym.name == nme.getClass_) && flattensToEmpty(sym.paramss) - - lazy val UnitClass = valueClassSymbol(tpnme.Unit) - lazy val ByteClass = valueClassSymbol(tpnme.Byte) - lazy val ShortClass = valueClassSymbol(tpnme.Short) - lazy val CharClass = valueClassSymbol(tpnme.Char) - lazy val IntClass = valueClassSymbol(tpnme.Int) - lazy val LongClass = valueClassSymbol(tpnme.Long) - lazy val FloatClass = valueClassSymbol(tpnme.Float) - lazy val DoubleClass = valueClassSymbol(tpnme.Double) - lazy val BooleanClass = valueClassSymbol(tpnme.Boolean) - lazy val Boolean_and = getMemberMethod(BooleanClass, nme.ZAND) - lazy val Boolean_or = getMemberMethod(BooleanClass, nme.ZOR) - lazy val Boolean_not = getMemberMethod(BooleanClass, nme.UNARY_!) - - lazy val ScalaNumericValueClasses = ScalaValueClasses filterNot Set[Symbol](UnitClass, BooleanClass) - - def ScalaValueClassesNoUnit = ScalaValueClasses filterNot (_ eq UnitClass) - def ScalaValueClasses: List[ClassSymbol] = List( - UnitClass, - BooleanClass, - ByteClass, - ShortClass, - CharClass, - IntClass, - LongClass, - FloatClass, - DoubleClass - ) - def ScalaValueClassCompanions: List[Symbol] = ScalaValueClasses map (_.companionSymbol) - def ScalaPrimitiveValueClasses: List[ClassSymbol] = ScalaValueClasses - } - - abstract class DefinitionsClass extends DefinitionsApi with ValueClassDefinitions { - private var isInitialized = false - def isDefinitionsInitialized = isInitialized - - // symbols related to packages - var emptypackagescope: Scope = null //debug - - // It becomes tricky to create dedicated objects for other symbols because - // of initialization order issues. - lazy val JavaLangPackage = getRequiredPackage(sn.JavaLang) - lazy val JavaLangPackageClass = JavaLangPackage.moduleClass.asClassSymbol - lazy val ScalaPackage = getRequiredPackage(nme.scala_) - lazy val ScalaPackageClass = ScalaPackage.moduleClass.asClassSymbol - lazy val RuntimePackage = getRequiredPackage("scala.runtime") - lazy val RuntimePackageClass = RuntimePackage.moduleClass.asClassSymbol - - lazy val JavaLangEnumClass = requiredClass[java.lang.Enum[_]] - - // convenient one-argument parameter lists - lazy val anyparam = List(AnyClass.tpe) - lazy val anyvalparam = List(AnyValClass.typeConstructor) - lazy val anyrefparam = List(AnyRefClass.typeConstructor) - - // private parameter conveniences - private def booltype = BooleanClass.tpe - private def inttype = IntClass.tpe - private def stringtype = StringClass.tpe - - def javaTypeToValueClass(jtype: Class[_]): Symbol = jtype match { - case java.lang.Void.TYPE => UnitClass - case java.lang.Byte.TYPE => ByteClass - case java.lang.Character.TYPE => CharClass - case java.lang.Short.TYPE => ShortClass - case java.lang.Integer.TYPE => IntClass - case java.lang.Long.TYPE => LongClass - case java.lang.Float.TYPE => FloatClass - case java.lang.Double.TYPE => DoubleClass - case java.lang.Boolean.TYPE => BooleanClass - case _ => NoSymbol - } - def valueClassToJavaType(sym: Symbol): Class[_] = sym match { - case UnitClass => java.lang.Void.TYPE - case ByteClass => java.lang.Byte.TYPE - case CharClass => java.lang.Character.TYPE - case ShortClass => java.lang.Short.TYPE - case IntClass => java.lang.Integer.TYPE - case LongClass => java.lang.Long.TYPE - case FloatClass => java.lang.Float.TYPE - case DoubleClass => java.lang.Double.TYPE - case BooleanClass => java.lang.Boolean.TYPE - case _ => null - } - - private def fixupAsAnyTrait(tpe: Type): Type = tpe match { - case ClassInfoType(parents, decls, clazz) => - if (parents.head.typeSymbol == AnyClass) tpe - else { - assert(parents.head.typeSymbol == ObjectClass, parents) - ClassInfoType(AnyClass.tpe :: parents.tail, decls, clazz) - } - case PolyType(tparams, restpe) => - PolyType(tparams, fixupAsAnyTrait(restpe)) -// case _ => tpe - } - - // top types - lazy val AnyClass = enterNewClass(ScalaPackageClass, tpnme.Any, Nil, ABSTRACT) - lazy val AnyRefClass = newAlias(ScalaPackageClass, tpnme.AnyRef, ObjectClass.tpe) - lazy val ObjectClass = getRequiredClass(sn.Object.toString) - - // Note: this is not the type alias AnyRef, it's a companion-like - // object used by the @specialize annotation. - lazy val AnyRefModule = getMemberModule(ScalaPackageClass, nme.AnyRef) - @deprecated("Use AnyRefModule", "2.10.0") - def Predef_AnyRef = AnyRefModule - - lazy val AnyValClass: ClassSymbol = (ScalaPackageClass.info member tpnme.AnyVal orElse { - val anyval = enterNewClass(ScalaPackageClass, tpnme.AnyVal, List(AnyClass.tpe, NotNullClass.tpe), ABSTRACT) - val av_constr = anyval.newClassConstructor(NoPosition) - anyval.info.decls enter av_constr - anyval - }).asInstanceOf[ClassSymbol] - - // bottom types - lazy val RuntimeNothingClass = getClassByName(fulltpnme.RuntimeNothing) - lazy val RuntimeNullClass = getClassByName(fulltpnme.RuntimeNull) - - sealed abstract class BottomClassSymbol(name: TypeName, parent: Symbol) extends ClassSymbol(ScalaPackageClass, NoPosition, name) { - locally { - this initFlags ABSTRACT | FINAL - this setInfoAndEnter ClassInfoType(List(parent.tpe), newScope, this) - } - final override def isBottomClass = true - } - final object NothingClass extends BottomClassSymbol(tpnme.Nothing, AnyClass) { - override def isSubClass(that: Symbol) = true - } - final object NullClass extends BottomClassSymbol(tpnme.Null, AnyRefClass) { - override def isSubClass(that: Symbol) = ( - (that eq AnyClass) - || (that ne NothingClass) && (that isSubClass ObjectClass) - ) - } - - // exceptions and other throwables - lazy val ClassCastExceptionClass = requiredClass[ClassCastException] - lazy val IndexOutOfBoundsExceptionClass = getClassByName(sn.IOOBException) - lazy val InvocationTargetExceptionClass = getClassByName(sn.InvTargetException) - lazy val MatchErrorClass = requiredClass[MatchError] - lazy val NonLocalReturnControlClass = requiredClass[scala.runtime.NonLocalReturnControl[_]] - lazy val NullPointerExceptionClass = getClassByName(sn.NPException) - lazy val ThrowableClass = getClassByName(sn.Throwable) - lazy val UninitializedErrorClass = requiredClass[UninitializedFieldError] - - // fundamental reference classes - lazy val PartialFunctionClass = requiredClass[PartialFunction[_,_]] - lazy val AbstractPartialFunctionClass = requiredClass[scala.runtime.AbstractPartialFunction[_,_]] - lazy val SymbolClass = requiredClass[scala.Symbol] - lazy val StringClass = requiredClass[java.lang.String] - lazy val StringModule = StringClass.linkedClassOfClass - lazy val ClassClass = requiredClass[java.lang.Class[_]] - def Class_getMethod = getMemberMethod(ClassClass, nme.getMethod_) - lazy val DynamicClass = requiredClass[Dynamic] - - // fundamental modules - lazy val SysPackage = getPackageObject("scala.sys") - def Sys_error = getMemberMethod(SysPackage, nme.error) - - // Modules whose members are in the default namespace - // [Eugene++] ScalaPackage and JavaLangPackage are never ever shared between mirrors - // as a result, `Int` becomes `scala.Int` and `String` becomes `java.lang.String` - // I could just change `isOmittablePrefix`, but there's more to it, so I'm leaving this as a todo for now - lazy val UnqualifiedModules = List(PredefModule, ScalaPackage, JavaLangPackage) - // Those modules and their module classes - lazy val UnqualifiedOwners = UnqualifiedModules.toSet ++ UnqualifiedModules.map(_.moduleClass) - - lazy val PredefModule = requiredModule[scala.Predef.type] - lazy val PredefModuleClass = PredefModule.moduleClass - - def Predef_classOf = getMemberMethod(PredefModule, nme.classOf) - def Predef_identity = getMemberMethod(PredefModule, nme.identity) - def Predef_conforms = getMemberMethod(PredefModule, nme.conforms) - def Predef_wrapRefArray = getMemberMethod(PredefModule, nme.wrapRefArray) - def Predef_??? = getMemberMethod(PredefModule, nme.???) - def Predef_implicitly = getMemberMethod(PredefModule, nme.implicitly) - - /** Is `sym` a member of Predef with the given name? - * Note: DON't replace this by sym == Predef_conforms/etc, as Predef_conforms is a `def` - * which does a member lookup (it can't be a lazy val because we might reload Predef - * during resident compilations). - */ - def isPredefMemberNamed(sym: Symbol, name: Name) = ( - (sym.name == name) && (sym.owner == PredefModule.moduleClass) - ) - - /** Specialization. - */ - lazy val SpecializableModule = requiredModule[Specializable] - lazy val GroupOfSpecializable = getMemberClass(SpecializableModule, tpnme.Group) - - lazy val ConsoleModule = requiredModule[scala.Console.type] - lazy val ScalaRunTimeModule = requiredModule[scala.runtime.ScalaRunTime.type] - lazy val SymbolModule = requiredModule[scala.Symbol.type] - lazy val Symbol_apply = getMemberMethod(SymbolModule, nme.apply) - - def SeqFactory = getMember(ScalaRunTimeModule, nme.Seq) // [Eugene++] obsolete? - def arrayApplyMethod = getMemberMethod(ScalaRunTimeModule, nme.array_apply) - def arrayUpdateMethod = getMemberMethod(ScalaRunTimeModule, nme.array_update) - def arrayLengthMethod = getMemberMethod(ScalaRunTimeModule, nme.array_length) - def arrayCloneMethod = getMemberMethod(ScalaRunTimeModule, nme.array_clone) - def ensureAccessibleMethod = getMemberMethod(ScalaRunTimeModule, nme.ensureAccessible) - def scalaRuntimeSameElements = getMemberMethod(ScalaRunTimeModule, nme.sameElements) - def arrayClassMethod = getMemberMethod(ScalaRunTimeModule, nme.arrayClass) - def arrayElementClassMethod = getMemberMethod(ScalaRunTimeModule, nme.arrayElementClass) - - // classes with special meanings - lazy val StringAddClass = requiredClass[scala.runtime.StringAdd] - lazy val ArrowAssocClass = getRequiredClass("scala.Predef.ArrowAssoc") // SI-5731 - lazy val StringAdd_+ = getMemberMethod(StringAddClass, nme.PLUS) - lazy val NotNullClass = getRequiredClass("scala.NotNull") - lazy val ScalaNumberClass = requiredClass[scala.math.ScalaNumber] - lazy val TraitSetterAnnotationClass = requiredClass[scala.runtime.TraitSetter] - lazy val DelayedInitClass = requiredClass[scala.DelayedInit] - def delayedInitMethod = getMemberMethod(DelayedInitClass, nme.delayedInit) - // a dummy value that communicates that a delayedInit call is compiler-generated - // from phase UnCurry to phase Constructors - // !!! This is not used anywhere (it was checked in that way.) - // def delayedInitArgVal = EmptyPackageClass.newValue(NoPosition, nme.delayedInitArg) - // .setInfo(UnitClass.tpe) - - lazy val TypeConstraintClass = requiredClass[scala.annotation.TypeConstraint] - lazy val SingletonClass = enterNewClass(ScalaPackageClass, tpnme.Singleton, anyparam, ABSTRACT | TRAIT | FINAL) - lazy val SerializableClass = requiredClass[scala.Serializable] - lazy val JavaSerializableClass = requiredClass[java.io.Serializable] modifyInfo fixupAsAnyTrait - lazy val ComparableClass = requiredClass[java.lang.Comparable[_]] modifyInfo fixupAsAnyTrait - lazy val JavaCloneableClass = requiredClass[java.lang.Cloneable] - lazy val JavaNumberClass = requiredClass[java.lang.Number] - lazy val RemoteInterfaceClass = requiredClass[java.rmi.Remote] - lazy val RemoteExceptionClass = requiredClass[java.rmi.RemoteException] - - lazy val ByNameParamClass = specialPolyClass(tpnme.BYNAME_PARAM_CLASS_NAME, COVARIANT)(_ => AnyClass.tpe) - lazy val EqualsPatternClass = specialPolyClass(tpnme.EQUALS_PATTERN_NAME, 0L)(_ => AnyClass.tpe) - lazy val JavaRepeatedParamClass = specialPolyClass(tpnme.JAVA_REPEATED_PARAM_CLASS_NAME, COVARIANT)(tparam => arrayType(tparam.tpe)) - lazy val RepeatedParamClass = specialPolyClass(tpnme.REPEATED_PARAM_CLASS_NAME, COVARIANT)(tparam => seqType(tparam.tpe)) - - def isByNameParamType(tp: Type) = tp.typeSymbol == ByNameParamClass - def isScalaRepeatedParamType(tp: Type) = tp.typeSymbol == RepeatedParamClass - def isJavaRepeatedParamType(tp: Type) = tp.typeSymbol == JavaRepeatedParamClass - def isRepeatedParamType(tp: Type) = isScalaRepeatedParamType(tp) || isJavaRepeatedParamType(tp) - def isCastSymbol(sym: Symbol) = sym == Any_asInstanceOf || sym == Object_asInstanceOf - - def isJavaVarArgsMethod(m: Symbol) = m.isMethod && isJavaVarArgs(m.info.params) - def isJavaVarArgs(params: Seq[Symbol]) = params.nonEmpty && isJavaRepeatedParamType(params.last.tpe) - def isScalaVarArgs(params: Seq[Symbol]) = params.nonEmpty && isScalaRepeatedParamType(params.last.tpe) - def isVarArgsList(params: Seq[Symbol]) = params.nonEmpty && isRepeatedParamType(params.last.tpe) - def isVarArgTypes(formals: Seq[Type]) = formals.nonEmpty && isRepeatedParamType(formals.last) - - def hasRepeatedParam(tp: Type): Boolean = tp match { - case MethodType(formals, restpe) => isScalaVarArgs(formals) || hasRepeatedParam(restpe) - case PolyType(_, restpe) => hasRepeatedParam(restpe) - case _ => false - } - - def isPrimitiveArray(tp: Type) = tp match { - case TypeRef(_, ArrayClass, arg :: Nil) => isPrimitiveValueClass(arg.typeSymbol) - case _ => false - } - def isReferenceArray(tp: Type) = tp match { - case TypeRef(_, ArrayClass, arg :: Nil) => arg <:< AnyRefClass.tpe - case _ => false - } - def isArrayOfSymbol(tp: Type, elem: Symbol) = tp match { - case TypeRef(_, ArrayClass, arg :: Nil) => arg.typeSymbol == elem - case _ => false - } - - lazy val MatchingStrategyClass = getRequiredClass("scala.MatchingStrategy") - - // collections classes - lazy val ConsClass = requiredClass[scala.collection.immutable.::[_]] - lazy val IterableClass = requiredClass[scala.collection.Iterable[_]] - lazy val IteratorClass = requiredClass[scala.collection.Iterator[_]] - lazy val ListClass = requiredClass[scala.collection.immutable.List[_]] - lazy val SeqClass = requiredClass[scala.collection.Seq[_]] - lazy val StringBuilderClass = requiredClass[scala.collection.mutable.StringBuilder] - lazy val TraversableClass = requiredClass[scala.collection.Traversable[_]] - - lazy val ListModule = requiredModule[scala.collection.immutable.List.type] - lazy val List_apply = getMemberMethod(ListModule, nme.apply) - lazy val NilModule = requiredModule[scala.collection.immutable.Nil.type] - lazy val SeqModule = requiredModule[scala.collection.Seq.type] - lazy val IteratorModule = requiredModule[scala.collection.Iterator.type] - lazy val Iterator_apply = getMemberMethod(IteratorModule, nme.apply) - - // arrays and their members - lazy val ArrayModule = requiredModule[scala.Array.type] - lazy val ArrayModule_overloadedApply = getMemberMethod(ArrayModule, nme.apply) - lazy val ArrayClass = getRequiredClass("scala.Array") // requiredClass[scala.Array[_]] - lazy val Array_apply = getMemberMethod(ArrayClass, nme.apply) - lazy val Array_update = getMemberMethod(ArrayClass, nme.update) - lazy val Array_length = getMemberMethod(ArrayClass, nme.length) - lazy val Array_clone = getMemberMethod(ArrayClass, nme.clone_) - - // reflection / structural types - lazy val SoftReferenceClass = requiredClass[java.lang.ref.SoftReference[_]] - lazy val WeakReferenceClass = requiredClass[java.lang.ref.WeakReference[_]] - lazy val MethodClass = getClassByName(sn.MethodAsObject) - def methodClass_setAccessible = getMemberMethod(MethodClass, nme.setAccessible) - lazy val EmptyMethodCacheClass = requiredClass[scala.runtime.EmptyMethodCache] - lazy val MethodCacheClass = requiredClass[scala.runtime.MethodCache] - def methodCache_find = getMemberMethod(MethodCacheClass, nme.find_) - def methodCache_add = getMemberMethod(MethodCacheClass, nme.add_) - - // scala.reflect - lazy val ReflectPackage = requiredModule[scala.reflect.`package`.type] - def ReflectBasis = getMemberValue(ReflectPackage, nme.basis) - lazy val ReflectRuntimePackage = getPackageObjectIfDefined("scala.reflect.runtime") // defined in scala-reflect.jar, so we need to be careful - def ReflectRuntimeUniverse = if (ReflectRuntimePackage != NoSymbol) getMemberValue(ReflectRuntimePackage, nme.universe) else NoSymbol - def ReflectRuntimeCurrentMirror = if (ReflectRuntimePackage != NoSymbol) getMemberMethod(ReflectRuntimePackage, nme.currentMirror) else NoSymbol - - lazy val PartialManifestClass = requiredClass[scala.reflect.ClassManifest[_]] - lazy val PartialManifestModule = requiredModule[scala.reflect.ClassManifest.type] - lazy val FullManifestClass = requiredClass[scala.reflect.Manifest[_]] - lazy val FullManifestModule = requiredModule[scala.reflect.Manifest.type] - lazy val OptManifestClass = requiredClass[scala.reflect.OptManifest[_]] - lazy val NoManifest = requiredModule[scala.reflect.NoManifest.type] - - lazy val ExprsClass = getClassIfDefined("scala.reflect.api.Exprs") // defined in scala-reflect.jar, so we need to be careful - lazy val ExprClass = if (ExprsClass != NoSymbol) getMemberClass(ExprsClass, tpnme.Expr) else NoSymbol - def ExprSplice = if (ExprsClass != NoSymbol) getMemberMethod(ExprClass, nme.splice) else NoSymbol - def ExprValue = if (ExprsClass != NoSymbol) getMemberMethod(ExprClass, nme.value) else NoSymbol - lazy val ExprModule = if (ExprsClass != NoSymbol) getMemberModule(ExprsClass, nme.Expr) else NoSymbol - - lazy val ArrayTagClass = requiredClass[scala.reflect.ArrayTag[_]] - lazy val ClassTagModule = requiredModule[scala.reflect.ClassTag[_]] - lazy val ClassTagClass = requiredClass[scala.reflect.ClassTag[_]] - lazy val TypeTagsClass = requiredClass[scala.reflect.base.TypeTags] - lazy val TypeTagClass = getMemberClass(TypeTagsClass, tpnme.TypeTag) - lazy val TypeTagModule = getMemberModule(TypeTagsClass, nme.TypeTag) - lazy val ConcreteTypeTagClass = getMemberClass(TypeTagsClass, tpnme.ConcreteTypeTag) - lazy val ConcreteTypeTagModule = getMemberModule(TypeTagsClass, nme.ConcreteTypeTag) - - lazy val BaseUniverseClass = requiredClass[scala.reflect.base.Universe] - lazy val ApiUniverseClass = getClassIfDefined("scala.reflect.api.Universe") // defined in scala-reflect.jar, so we need to be careful - def ApiUniverseReify = if (ApiUniverseClass != NoSymbol) getMemberMethod(ApiUniverseClass, nme.reify) else NoSymbol - lazy val JavaUniverseClass = getClassIfDefined("scala.reflect.api.JavaUniverse") // defined in scala-reflect.jar, so we need to be careful - - lazy val MirrorOfClass = requiredClass[scala.reflect.base.MirrorOf[_]] - - lazy val TypeCreatorClass = requiredClass[scala.reflect.base.TypeCreator] - lazy val TreeCreatorClass = requiredClass[scala.reflect.base.TreeCreator] - - lazy val MacroContextClass = getClassIfDefined("scala.reflect.makro.Context") // defined in scala-reflect.jar, so we need to be careful - def MacroContextPrefix = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.prefix) else NoSymbol - def MacroContextPrefixType = if (MacroContextClass != NoSymbol) getMemberType(MacroContextClass, tpnme.PrefixType) else NoSymbol - def MacroContextUniverse = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.universe) else NoSymbol - def MacroContextMirror = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.mirror) else NoSymbol - def MacroContextReify = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.reify) else NoSymbol - lazy val MacroImplAnnotation = requiredClass[scala.reflect.makro.internal.macroImpl] - lazy val MacroInternalPackage = getPackageObject("scala.reflect.makro.internal") - def MacroInternal_materializeArrayTag = getMemberMethod(MacroInternalPackage, nme.materializeArrayTag) - def MacroInternal_materializeClassTag = getMemberMethod(MacroInternalPackage, nme.materializeClassTag) - def MacroInternal_materializeTypeTag = getMemberMethod(MacroInternalPackage, nme.materializeTypeTag) - def MacroInternal_materializeConcreteTypeTag = getMemberMethod(MacroInternalPackage, nme.materializeConcreteTypeTag) - - lazy val ScalaSignatureAnnotation = requiredClass[scala.reflect.ScalaSignature] - lazy val ScalaLongSignatureAnnotation = requiredClass[scala.reflect.ScalaLongSignature] - - // Option classes - lazy val OptionClass: ClassSymbol = requiredClass[Option[_]] - lazy val SomeClass: ClassSymbol = requiredClass[Some[_]] - lazy val NoneModule: ModuleSymbol = requiredModule[scala.None.type] - lazy val SomeModule: ModuleSymbol = requiredModule[scala.Some.type] - - def compilerTypeFromTag(tt: BaseUniverse # TypeTag[_]): Type = tt.in(rootMirror).tpe - def compilerSymbolFromTag(tt: BaseUniverse # TypeTag[_]): Symbol = tt.in(rootMirror).tpe.typeSymbol - - // The given symbol represents either String.+ or StringAdd.+ - def isStringAddition(sym: Symbol) = sym == String_+ || sym == StringAdd_+ - def isArrowAssoc(sym: Symbol) = ArrowAssocClass.tpe.decls.toList contains sym - - // The given symbol is a method with the right name and signature to be a runnable java program. - def isJavaMainMethod(sym: Symbol) = (sym.name == nme.main) && (sym.info match { - case MethodType(p :: Nil, restpe) => isArrayOfSymbol(p.tpe, StringClass) && restpe.typeSymbol == UnitClass - case _ => false - }) - // The given class has a main method. - def hasJavaMainMethod(sym: Symbol): Boolean = - (sym.tpe member nme.main).alternatives exists isJavaMainMethod - def hasJavaMainMethod(path: String): Boolean = - hasJavaMainMethod(getModuleIfDefined(path)) - - def isOptionType(tp: Type) = tp.typeSymbol isSubClass OptionClass - def isSomeType(tp: Type) = tp.typeSymbol eq SomeClass - def isNoneType(tp: Type) = tp.typeSymbol eq NoneModule - - // Product, Tuple, Function, AbstractFunction - private def mkArityArray(name: String, arity: Int, countFrom: Int): Array[ClassSymbol] = { - val list = countFrom to arity map (i => getRequiredClass("scala." + name + i)) - list.toArray - } - def prepend[S >: ClassSymbol : ClassTag](elem0: S, elems: Array[ClassSymbol]): Array[S] = elem0 +: elems - - private def aritySpecificType[S <: Symbol](symbolArray: Array[S], args: List[Type], others: Type*): Type = { - val arity = args.length - if (arity >= symbolArray.length) NoType - else appliedType(symbolArray(arity), args ++ others: _*) - } - - val MaxTupleArity, MaxProductArity, MaxFunctionArity = 22 - lazy val ProductClass: Array[ClassSymbol] = prepend(UnitClass, mkArityArray("Product", MaxProductArity, 1)) - lazy val TupleClass: Array[Symbol] = prepend(NoSymbol, mkArityArray("Tuple", MaxTupleArity, 1)) - lazy val FunctionClass = mkArityArray("Function", MaxFunctionArity, 0) - lazy val AbstractFunctionClass = mkArityArray("runtime.AbstractFunction", MaxFunctionArity, 0) - - /** Creators for TupleN, ProductN, FunctionN. */ - def tupleType(elems: List[Type]) = aritySpecificType(TupleClass, elems) - def productType(elems: List[Type]) = aritySpecificType(ProductClass, elems) - def functionType(formals: List[Type], restpe: Type) = aritySpecificType(FunctionClass, formals, restpe) - def abstractFunctionType(formals: List[Type], restpe: Type) = aritySpecificType(AbstractFunctionClass, formals, restpe) - - def wrapArrayMethodName(elemtp: Type): TermName = elemtp.typeSymbol match { - case ByteClass => nme.wrapByteArray - case ShortClass => nme.wrapShortArray - case CharClass => nme.wrapCharArray - case IntClass => nme.wrapIntArray - case LongClass => nme.wrapLongArray - case FloatClass => nme.wrapFloatArray - case DoubleClass => nme.wrapDoubleArray - case BooleanClass => nme.wrapBooleanArray - case UnitClass => nme.wrapUnitArray - case _ => - if ((elemtp <:< AnyRefClass.tpe) && !isPhantomClass(elemtp.typeSymbol)) nme.wrapRefArray - else nme.genericWrapArray - } - - @deprecated("Use isTupleType", "2.10.0") - def isTupleTypeOrSubtype(tp: Type) = isTupleType(tp) - - def tupleField(n: Int, j: Int) = getMemberValue(TupleClass(n), nme.productAccessorName(j)) - // NOTE: returns true for NoSymbol since it's included in the TupleClass array -- is this intensional? - def isTupleSymbol(sym: Symbol) = TupleClass contains unspecializedSymbol(sym) - def isProductNClass(sym: Symbol) = ProductClass contains sym - - def unspecializedSymbol(sym: Symbol): Symbol = { - if (sym hasFlag SPECIALIZED) { - // add initialization from its generic class constructor - val genericName = nme.unspecializedName(sym.name) - val member = sym.owner.info.decl(genericName.toTypeName) - member - } - else sym - } - - // Checks whether the given type is true for the given condition, - // or if it is a specialized subtype of a type for which it is true. - // - // Origins notes: - // An issue was introduced with specialization in that the implementation - // of "isTupleType" in Definitions relied upon sym == TupleClass(elems.length). - // This test is untrue for specialized tuples, causing mysterious behavior - // because only some tuples are specialized. - def isPossiblySpecializedType(tp: Type)(cond: Type => Boolean) = { - cond(tp) || (tp match { - case TypeRef(pre, sym, args) if sym hasFlag SPECIALIZED => - cond(tp baseType unspecializedSymbol(sym)) - case _ => - false - }) - } - // No normalization. - def isTupleTypeDirect(tp: Type) = isPossiblySpecializedType(tp) { - case TypeRef(_, sym, args) if args.nonEmpty => - val len = args.length - len <= MaxTupleArity && sym == TupleClass(len) - case _ => false - } - def isTupleType(tp: Type) = isTupleTypeDirect(tp.normalize) - - lazy val ProductRootClass: ClassSymbol = requiredClass[scala.Product] - def Product_productArity = getMemberMethod(ProductRootClass, nme.productArity) - def Product_productElement = getMemberMethod(ProductRootClass, nme.productElement) - def Product_iterator = getMemberMethod(ProductRootClass, nme.productIterator) - def Product_productPrefix = getMemberMethod(ProductRootClass, nme.productPrefix) - def Product_canEqual = getMemberMethod(ProductRootClass, nme.canEqual_) - // def Product_productElementName = getMemberMethod(ProductRootClass, nme.productElementName) - - def productProj(z:Symbol, j: Int): TermSymbol = getMemberValue(z, nme.productAccessorName(j)) - def productProj(n: Int, j: Int): TermSymbol = productProj(ProductClass(n), j) - - /** returns true if this type is exactly ProductN[T1,...,Tn], not some subclass */ - def isExactProductType(tp: Type): Boolean = isProductNClass(tp.typeSymbol) - - /** if tpe <: ProductN[T1,...,TN], returns List(T1,...,TN) else Nil */ - def getProductArgs(tpe: Type): List[Type] = tpe.baseClasses find isProductNClass match { - case Some(x) => tpe.baseType(x).typeArgs - case _ => Nil - } - - def unapplyUnwrap(tpe:Type) = tpe.finalResultType.normalize match { - case RefinedType(p :: _, _) => p.normalize - case tp => tp - } - - def functionApply(n: Int) = getMemberMethod(FunctionClass(n), nme.apply) - - def abstractFunctionForFunctionType(tp: Type) = - if (isFunctionType(tp)) abstractFunctionType(tp.typeArgs.init, tp.typeArgs.last) - else NoType - - def isFunctionType(tp: Type): Boolean = tp.normalize match { - case TypeRef(_, sym, args) if args.nonEmpty => - val arity = args.length - 1 // -1 is the return type - arity <= MaxFunctionArity && sym == FunctionClass(arity) - case _ => - false - } - - def isPartialFunctionType(tp: Type): Boolean = { - val sym = tp.typeSymbol - (sym eq PartialFunctionClass) || (sym eq AbstractPartialFunctionClass) - } - - def isSeqType(tp: Type) = elementType(SeqClass, tp.normalize) != NoType - - def elementType(container: Symbol, tp: Type): Type = tp match { - case TypeRef(_, `container`, arg :: Nil) => arg - case _ => NoType - } - - def arrayType(arg: Type) = appliedType(ArrayClass, arg) - def byNameType(arg: Type) = appliedType(ByNameParamClass, arg) - def iteratorOfType(tp: Type) = appliedType(IteratorClass, tp) - def javaRepeatedType(arg: Type) = appliedType(JavaRepeatedParamClass, arg) - def optionType(tp: Type) = appliedType(OptionClass, tp) - def scalaRepeatedType(arg: Type) = appliedType(RepeatedParamClass, arg) - def seqType(arg: Type) = appliedType(SeqClass, arg) - def someType(tp: Type) = appliedType(SomeClass, tp) - - def StringArray = arrayType(StringClass.tpe) - lazy val ObjectArray = arrayType(ObjectClass.tpe) - - def ClassType(arg: Type) = - if (phase.erasedTypes || forMSIL) ClassClass.tpe - else appliedType(ClassClass, arg) - - def vmClassType(arg: Type): Type = ClassType(arg) - def vmSignature(sym: Symbol, info: Type): String = signature(info) // !!! - - /** Given a class symbol C with type parameters T1, T2, ... Tn - * which have upper/lower bounds LB1/UB1, LB1/UB2, ..., LBn/UBn, - * returns an existential type of the form - * - * C[E1, ..., En] forSome { E1 >: LB1 <: UB1 ... en >: LBn <: UBn }. - */ - def classExistentialType(clazz: Symbol): Type = - newExistentialType(clazz.typeParams, clazz.tpe) - - /** Given type U, creates a Type representing Class[_ <: U]. - */ - def boundedClassType(upperBound: Type) = - appliedTypeAsUpperBounds(ClassClass.typeConstructor, List(upperBound)) - - /** To avoid unchecked warnings on polymorphic classes, translate - * a Foo[T] into a Foo[_] for use in the pattern matcher. - */ - @deprecated("Use classExistentialType", "2.10.0") - def typeCaseType(clazz: Symbol): Type = classExistentialType(clazz) - - // - // .NET backend - // - - lazy val ComparatorClass = getRequiredClass("scala.runtime.Comparator") - // System.ValueType - lazy val ValueTypeClass: ClassSymbol = getClassByName(sn.ValueType) - // System.MulticastDelegate - lazy val DelegateClass: ClassSymbol = getClassByName(sn.Delegate) - var Delegate_scalaCallers: List[Symbol] = List() // Syncnote: No protection necessary yet as only for .NET where reflection is not supported. - // Symbol -> (Symbol, Type): scalaCaller -> (scalaMethodSym, DelegateType) - // var Delegate_scalaCallerInfos: HashMap[Symbol, (Symbol, Type)] = _ - lazy val Delegate_scalaCallerTargets: mutable.HashMap[Symbol, Symbol] = mutable.HashMap() - - def isCorrespondingDelegate(delegateType: Type, functionType: Type): Boolean = { - isSubType(delegateType, DelegateClass.tpe) && - (delegateType.member(nme.apply).tpe match { - case MethodType(delegateParams, delegateReturn) => - isFunctionType(functionType) && - (functionType.normalize match { - case TypeRef(_, _, args) => - (delegateParams.map(pt => { - if (pt.tpe == AnyClass.tpe) definitions.ObjectClass.tpe else pt}) - ::: List(delegateReturn)) == args - case _ => false - }) - case _ => false - }) - } - - // members of class scala.Any - lazy val Any_== = enterNewMethod(AnyClass, nme.EQ, anyparam, booltype, FINAL) - lazy val Any_!= = enterNewMethod(AnyClass, nme.NE, anyparam, booltype, FINAL) - lazy val Any_equals = enterNewMethod(AnyClass, nme.equals_, anyparam, booltype) - lazy val Any_hashCode = enterNewMethod(AnyClass, nme.hashCode_, Nil, inttype) - lazy val Any_toString = enterNewMethod(AnyClass, nme.toString_, Nil, stringtype) - lazy val Any_## = enterNewMethod(AnyClass, nme.HASHHASH, Nil, inttype, FINAL) - - // Any_getClass requires special handling. The return type is determined on - // a per-call-site basis as if the function being called were actually: - // - // // Assuming `target.getClass()` - // def getClass[T](target: T): Class[_ <: T] - // - // Since getClass is not actually a polymorphic method, this requires compiler - // participation. At the "Any" level, the return type is Class[_] as it is in - // java.lang.Object. Java also special cases the return type. - lazy val Any_getClass = enterNewMethod(AnyClass, nme.getClass_, Nil, getMemberMethod(ObjectClass, nme.getClass_).tpe.resultType, DEFERRED) - lazy val Any_isInstanceOf = newT1NullaryMethod(AnyClass, nme.isInstanceOf_, FINAL)(_ => booltype) - lazy val Any_asInstanceOf = newT1NullaryMethod(AnyClass, nme.asInstanceOf_, FINAL)(_.typeConstructor) - - // A type function from T => Class[U], used to determine the return - // type of getClass calls. The returned type is: - // - // 1. If T is a value type, Class[T]. - // 2. If T is a phantom type (Any or AnyVal), Class[_]. - // 3. If T is a local class, Class[_ <: |T|]. - // 4. Otherwise, Class[_ <: T]. - // - // Note: AnyVal cannot be Class[_ <: AnyVal] because if the static type of the - // receiver is AnyVal, it implies the receiver is boxed, so the correct - // class object is that of java.lang.Integer, not Int. - // - // TODO: If T is final, return type could be Class[T]. Should it? - def getClassReturnType(tp: Type): Type = { - val sym = tp.typeSymbol - - if (phase.erasedTypes) ClassClass.tpe - else if (isPrimitiveValueClass(sym)) ClassType(tp.widen) - else { - val eparams = typeParamsToExistentials(ClassClass, ClassClass.typeParams) - val upperBound = ( - if (isPhantomClass(sym)) AnyClass.tpe - else if (sym.isLocalClass) erasure.intersectionDominator(tp.parents) - else tp.widen - ) - - existentialAbstraction( - eparams, - ClassType((eparams.head setInfo TypeBounds.upper(upperBound)).tpe) - ) - } - } - - /** Remove references to class Object (other than the head) in a list of parents */ - def removeLaterObjects(tps: List[Type]): List[Type] = tps match { - case Nil => Nil - case x :: xs => x :: xs.filterNot(_.typeSymbol == ObjectClass) - } - /** Remove all but one reference to class Object from a list of parents. */ - def removeRedundantObjects(tps: List[Type]): List[Type] = tps match { - case Nil => Nil - case x :: xs => - if (x.typeSymbol == ObjectClass) - x :: xs.filterNot(_.typeSymbol == ObjectClass) - else - x :: removeRedundantObjects(xs) - } - /** Order a list of types with non-trait classes before others. */ - def classesFirst(tps: List[Type]): List[Type] = { - val (classes, others) = tps partition (t => t.typeSymbol.isClass && !t.typeSymbol.isTrait) - if (classes.isEmpty || others.isEmpty || (tps startsWith classes)) tps - else classes ::: others - } - /** The following transformations applied to a list of parents. - * If any parent is a class/trait, all parents which normalize to - * Object are discarded. Otherwise, all parents which normalize - * to Object except the first one found are discarded. - */ - def normalizedParents(parents: List[Type]): List[Type] = { - if (parents exists (t => (t.typeSymbol ne ObjectClass) && t.typeSymbol.isClass)) - parents filterNot (_.typeSymbol eq ObjectClass) - else - removeRedundantObjects(parents) - } - - def typeStringNoPackage(tp: Type) = - "" + tp stripPrefix tp.typeSymbol.enclosingPackage.fullName + "." - - def briefParentsString(parents: List[Type]) = - normalizedParents(parents) map typeStringNoPackage mkString " with " - - def parentsString(parents: List[Type]) = - normalizedParents(parents) mkString " with " - - def typeParamsString(tp: Type) = tp match { - case PolyType(tparams, _) => tparams map (_.defString) mkString ("[", ",", "]") - case _ => "" - } - def valueParamsString(tp: Type) = tp match { - case MethodType(params, _) => params map (_.defString) mkString ("(", ",", ")") - case _ => "" - } - - // members of class java.lang.{ Object, String } - lazy val Object_## = enterNewMethod(ObjectClass, nme.HASHHASH, Nil, inttype, FINAL) - lazy val Object_== = enterNewMethod(ObjectClass, nme.EQ, anyrefparam, booltype, FINAL) - lazy val Object_!= = enterNewMethod(ObjectClass, nme.NE, anyrefparam, booltype, FINAL) - lazy val Object_eq = enterNewMethod(ObjectClass, nme.eq, anyrefparam, booltype, FINAL) - lazy val Object_ne = enterNewMethod(ObjectClass, nme.ne, anyrefparam, booltype, FINAL) - lazy val Object_isInstanceOf = newT1NoParamsMethod(ObjectClass, nme.isInstanceOf_Ob, FINAL | SYNTHETIC)(_ => booltype) - lazy val Object_asInstanceOf = newT1NoParamsMethod(ObjectClass, nme.asInstanceOf_Ob, FINAL | SYNTHETIC)(_.typeConstructor) - lazy val Object_synchronized = newPolyMethod(1, ObjectClass, nme.synchronized_, FINAL)(tps => - (Some(List(tps.head.typeConstructor)), tps.head.typeConstructor) - ) - lazy val String_+ = enterNewMethod(StringClass, nme.raw.PLUS, anyparam, stringtype, FINAL) - - def Object_getClass = getMemberMethod(ObjectClass, nme.getClass_) - def Object_clone = getMemberMethod(ObjectClass, nme.clone_) - def Object_finalize = getMemberMethod(ObjectClass, nme.finalize_) - def Object_notify = getMemberMethod(ObjectClass, nme.notify_) - def Object_notifyAll = getMemberMethod(ObjectClass, nme.notifyAll_) - def Object_equals = getMemberMethod(ObjectClass, nme.equals_) - def Object_hashCode = getMemberMethod(ObjectClass, nme.hashCode_) - def Object_toString = getMemberMethod(ObjectClass, nme.toString_) - - // boxed classes - lazy val ObjectRefClass = requiredClass[scala.runtime.ObjectRef[_]] - lazy val VolatileObjectRefClass = requiredClass[scala.runtime.VolatileObjectRef[_]] - lazy val RuntimeStaticsModule = getRequiredModule("scala.runtime.Statics") - lazy val BoxesRunTimeModule = getRequiredModule("scala.runtime.BoxesRunTime") - lazy val BoxesRunTimeClass = BoxesRunTimeModule.moduleClass - lazy val BoxedNumberClass = getClassByName(sn.BoxedNumber) - lazy val BoxedCharacterClass = getClassByName(sn.BoxedCharacter) - lazy val BoxedBooleanClass = getClassByName(sn.BoxedBoolean) - lazy val BoxedByteClass = requiredClass[java.lang.Byte] - lazy val BoxedShortClass = requiredClass[java.lang.Short] - lazy val BoxedIntClass = requiredClass[java.lang.Integer] - lazy val BoxedLongClass = requiredClass[java.lang.Long] - lazy val BoxedFloatClass = requiredClass[java.lang.Float] - lazy val BoxedDoubleClass = requiredClass[java.lang.Double] - - lazy val Boxes_isNumberOrBool = getDecl(BoxesRunTimeClass, nme.isBoxedNumberOrBoolean) - lazy val Boxes_isNumber = getDecl(BoxesRunTimeClass, nme.isBoxedNumber) - - lazy val BoxedUnitClass = requiredClass[scala.runtime.BoxedUnit] - lazy val BoxedUnitModule = getRequiredModule("scala.runtime.BoxedUnit") - def BoxedUnit_UNIT = getMemberValue(BoxedUnitModule, nme.UNIT) - def BoxedUnit_TYPE = getMemberValue(BoxedUnitModule, nme.TYPE_) - - // Annotation base classes - lazy val AnnotationClass = requiredClass[scala.annotation.Annotation] - lazy val ClassfileAnnotationClass = requiredClass[scala.annotation.ClassfileAnnotation] - lazy val StaticAnnotationClass = requiredClass[scala.annotation.StaticAnnotation] - - // Annotations - lazy val BridgeClass = requiredClass[scala.annotation.bridge] - lazy val ElidableMethodClass = requiredClass[scala.annotation.elidable] - lazy val ImplicitNotFoundClass = requiredClass[scala.annotation.implicitNotFound] - lazy val MigrationAnnotationClass = requiredClass[scala.annotation.migration] - lazy val ScalaStrictFPAttr = requiredClass[scala.annotation.strictfp] - lazy val SerializableAttr = requiredClass[scala.annotation.serializable] // @serializable is deprecated - lazy val SwitchClass = requiredClass[scala.annotation.switch] - lazy val TailrecClass = requiredClass[scala.annotation.tailrec] - lazy val VarargsClass = requiredClass[scala.annotation.varargs] - lazy val uncheckedStableClass = requiredClass[scala.annotation.unchecked.uncheckedStable] - lazy val uncheckedVarianceClass = requiredClass[scala.annotation.unchecked.uncheckedVariance] - - lazy val BeanPropertyAttr = requiredClass[scala.beans.BeanProperty] - lazy val BooleanBeanPropertyAttr = requiredClass[scala.beans.BooleanBeanProperty] - lazy val CloneableAttr = requiredClass[scala.cloneable] - lazy val DeprecatedAttr = requiredClass[scala.deprecated] - lazy val DeprecatedNameAttr = requiredClass[scala.deprecatedName] - lazy val NativeAttr = requiredClass[scala.native] - lazy val RemoteAttr = requiredClass[scala.remote] - lazy val ScalaInlineClass = requiredClass[scala.inline] - lazy val ScalaNoInlineClass = requiredClass[scala.noinline] - lazy val SerialVersionUIDAttr = requiredClass[scala.SerialVersionUID] - lazy val SpecializedClass = requiredClass[scala.specialized] - lazy val ThrowsClass = requiredClass[scala.throws] - lazy val TransientAttr = requiredClass[scala.transient] - lazy val UncheckedClass = requiredClass[scala.unchecked] - lazy val UnspecializedClass = requiredClass[scala.annotation.unspecialized] - lazy val VolatileAttr = requiredClass[scala.volatile] - - // Meta-annotations - lazy val BeanGetterTargetClass = requiredClass[meta.beanGetter] - lazy val BeanSetterTargetClass = requiredClass[meta.beanSetter] - lazy val FieldTargetClass = requiredClass[meta.field] - lazy val GetterTargetClass = requiredClass[meta.getter] - lazy val ParamTargetClass = requiredClass[meta.param] - lazy val SetterTargetClass = requiredClass[meta.setter] - lazy val ClassTargetClass = requiredClass[meta.companionClass] - lazy val ObjectTargetClass = requiredClass[meta.companionObject] - lazy val MethodTargetClass = requiredClass[meta.companionMethod] // TODO: module, moduleClass? package, packageObject? - lazy val LanguageFeatureAnnot = requiredClass[meta.languageFeature] - - // Language features - lazy val languageFeatureModule = getRequiredModule("scala.languageFeature") - lazy val experimentalModule = getMemberModule(languageFeatureModule, nme.experimental) - lazy val MacrosFeature = getLanguageFeature("macros", experimentalModule) - lazy val DynamicsFeature = getLanguageFeature("dynamics") - lazy val PostfixOpsFeature = getLanguageFeature("postfixOps") - lazy val ReflectiveCallsFeature = getLanguageFeature("reflectiveCalls") - lazy val ImplicitConversionsFeature = getLanguageFeature("implicitConversions") - lazy val HigherKindsFeature = getLanguageFeature("higherKinds") - lazy val ExistentialsFeature = getLanguageFeature("existentials") - - def isMetaAnnotation(sym: Symbol): Boolean = metaAnnotations(sym) || ( - // Trying to allow for deprecated locations - sym.isAliasType && isMetaAnnotation(sym.info.typeSymbol) - ) - lazy val metaAnnotations = Set[Symbol]( - FieldTargetClass, ParamTargetClass, - GetterTargetClass, SetterTargetClass, - BeanGetterTargetClass, BeanSetterTargetClass - ) - - lazy val AnnotationDefaultAttr: ClassSymbol = { - val attr = enterNewClass(RuntimePackageClass, tpnme.AnnotationDefaultATTR, List(AnnotationClass.tpe)) - // This attribute needs a constructor so that modifiers in parsed Java code make sense - attr.info.decls enter attr.newClassConstructor(NoPosition) - attr - } - - private def fatalMissingSymbol(owner: Symbol, name: Name, what: String = "member") = { - throw new FatalError(owner + " does not have a " + what + " " + name) - } - - def getLanguageFeature(name: String, owner: Symbol = languageFeatureModule): Symbol = - // [Eugene++] `getMemberClass` leads to crashes in mixin: - // "object languageFeature does not have a member class implicitConversions" - // that's because by that time `implicitConversions` becomes a module - // getMemberClass(owner, newTypeName(name)) - getMember(owner, newTypeName(name)) - - def termMember(owner: Symbol, name: String): Symbol = owner.info.member(newTermName(name)) - def typeMember(owner: Symbol, name: String): Symbol = owner.info.member(newTypeName(name)) - - def findNamedMember(fullName: Name, root: Symbol): Symbol = { - val segs = nme.segments(fullName.toString, fullName.isTermName) - if (segs.isEmpty || segs.head != root.simpleName) NoSymbol - else findNamedMember(segs.tail, root) - } - def findNamedMember(segs: List[Name], root: Symbol): Symbol = - if (segs.isEmpty) root - else findNamedMember(segs.tail, root.info member segs.head) - - def getMember(owner: Symbol, name: Name): Symbol = { - getMemberIfDefined(owner, name) orElse { - if (phase.flatClasses && name.isTypeName && !owner.isPackageObjectOrClass) { - val pkg = owner.owner - val flatname = nme.flattenedName(owner.name, name) - getMember(pkg, flatname) - } - else fatalMissingSymbol(owner, name) - } - } - def getMemberValue(owner: Symbol, name: Name): TermSymbol = { - // [Eugene++] should be a ClassCastException instead? - getMember(owner, name.toTermName) match { - case x: TermSymbol => x - case _ => fatalMissingSymbol(owner, name, "member value") - } - } - def getMemberModule(owner: Symbol, name: Name): ModuleSymbol = { - // [Eugene++] should be a ClassCastException instead? - getMember(owner, name.toTermName) match { - case x: ModuleSymbol => x - case _ => fatalMissingSymbol(owner, name, "member object") - } - } - def getMemberType(owner: Symbol, name: Name): TypeSymbol = { - // [Eugene++] should be a ClassCastException instead? - getMember(owner, name.toTypeName) match { - case x: TypeSymbol => x - case _ => fatalMissingSymbol(owner, name, "member type") - } - } - def getMemberClass(owner: Symbol, name: Name): ClassSymbol = { - // [Eugene++] should be a ClassCastException instead? - val y = getMember(owner, name.toTypeName) - getMember(owner, name.toTypeName) match { - case x: ClassSymbol => x - case _ => fatalMissingSymbol(owner, name, "member class") - } - } - def getMemberMethod(owner: Symbol, name: Name): TermSymbol = { - // [Eugene++] is this a bug? - // - // System.err.println(result.getClass) - // System.err.println(result.flags) - // System.err.println("isMethod = " + result.isMethod) - // System.err.println("isTerm = " + result.isTerm) - // System.err.println("isValue = " + result.isValue) - // result.asMethodSymbol - // - // prints this: - // - // quick.lib: - // [javac] Compiling 1 source file to C:\Projects\KeplerUnderRefactoring\build\quick\classes\library - // [scalacfork] Compiling 769 files to C:\Projects\KeplerUnderRefactoring\build\quick\classes\library - // [scalacfork] class scala.reflect.internal.Symbols$TermSymbol - // [scalacfork] 8589934592 - // [scalacfork] isMethod = false - // [scalacfork] isTerm = true - // [scalacfork] isValue = true - // [scalacfork] - // [scalacfork] while compiling: C:\Projects\KeplerUnderRefactoring\src\library\scala\LowPriorityImplicits.scala - // [scalacfork] current phase: cleanup - // [scalacfork] library version: version 2.10.0-20120507-185519-665d1d9127 - // [scalacfork] compiler version: version 2.10.0-20120507-185519-665d1d9127 - // [scalacfork] reconstructed args: -Xmacros -classpath C:\\Projects\\KeplerUnderRefactoring\\build\\quick\\classes\\library;C:\\Projects\\KeplerUnderRefactoring\\lib\\forkjoin.jar -d C:\\Projects\\KeplerUnderRefactoring\\build\\quick\\classes\\library -sourcepath C:\\Projects\\KeplerUnderRefactoring\\src\\library - // [scalacfork] - // [scalacfork] unhandled exception while transforming LowPriorityImplicits.scala - // [scalacfork] error: - // [scalacfork] while compiling: C:\Projects\KeplerUnderRefactoring\src\library\scala\LowPriorityImplicits.scala - // [scalacfork] current phase: cleanup - // [scalacfork] library version: version 2.10.0-20120507-185519-665d1d9127 - // [scalacfork] compiler version: version 2.10.0-20120507-185519-665d1d9127 - // [scalacfork] reconstructed args: -Xmacros -classpath C:\\Projects\\KeplerUnderRefactoring\\build\\quick\\classes\\library;C:\\Projects\\KeplerUnderRefactoring\\lib\\forkjoin.jar -d C:\\Projects\\KeplerUnderRefactoring\\build\\quick\\classes\\library -sourcepath C:\\Projects\\KeplerUnderRefactoring\\src\\library - // [scalacfork] - // [scalacfork] uncaught exception during compilation: java.lang.ClassCastException - // [scalacfork] error: java.lang.ClassCastException: value apply - // [scalacfork] at scala.reflect.base.Symbols$SymbolBase$class.asMethodSymbol(Symbols.scala:118) - // [scalacfork] at scala.reflect.internal.Symbols$SymbolContextApiImpl.asMethodSymbol(Symbols.scala:63) - // [scalacfork] at scala.reflect.internal.Definitions$DefinitionsClass.Symbol_apply(Definitions.scala:381) - - // [Eugene++] should be a ClassCastException instead? - getMember(owner, name.toTermName) match { - // case x: MethodSymbol => x - case x: TermSymbol => x - case _ => fatalMissingSymbol(owner, name, "method") - } - } - - def getMemberIfDefined(owner: Symbol, name: Name): Symbol = - owner.info.nonPrivateMember(name) - - /** Using getDecl rather than getMember may avoid issues with - * OverloadedTypes turning up when you don't want them, if you - * know the method in question is uniquely declared in the given owner. - */ - def getDecl(owner: Symbol, name: Name): Symbol = { - getDeclIfDefined(owner, name) orElse fatalMissingSymbol(owner, name, "decl") - } - def getDeclIfDefined(owner: Symbol, name: Name): Symbol = - owner.info.nonPrivateDecl(name) - - def packageExists(packageName: String): Boolean = - getModuleIfDefined(packageName).isPackage - - private def newAlias(owner: Symbol, name: TypeName, alias: Type): AliasTypeSymbol = - owner.newAliasType(name) setInfoAndEnter alias - - private def specialPolyClass(name: TypeName, flags: Long)(parentFn: Symbol => Type): ClassSymbol = { - val clazz = enterNewClass(ScalaPackageClass, name, Nil) - val tparam = clazz.newSyntheticTypeParam("T0", flags) - val parents = List(AnyRefClass.tpe, parentFn(tparam)) - - clazz setInfo GenPolyType(List(tparam), ClassInfoType(parents, newScope, clazz)) - } - - def newPolyMethod(typeParamCount: Int, owner: Symbol, name: TermName, flags: Long)(createFn: PolyMethodCreator): MethodSymbol = { - val msym = owner.newMethod(name.encode, NoPosition, flags) - val tparams = msym.newSyntheticTypeParams(typeParamCount) - val mtpe = createFn(tparams) match { - case (Some(formals), restpe) => MethodType(msym.newSyntheticValueParams(formals), restpe) - case (_, restpe) => NullaryMethodType(restpe) - } - - msym setInfoAndEnter genPolyType(tparams, mtpe) - } - - /** T1 means one type parameter. - */ - def newT1NullaryMethod(owner: Symbol, name: TermName, flags: Long)(createFn: Symbol => Type): MethodSymbol = { - newPolyMethod(1, owner, name, flags)(tparams => (None, createFn(tparams.head))) - } - def newT1NoParamsMethod(owner: Symbol, name: TermName, flags: Long)(createFn: Symbol => Type): MethodSymbol = { - newPolyMethod(1, owner, name, flags)(tparams => (Some(Nil), createFn(tparams.head))) - } - - lazy val boxedClassValues = boxedClass.values.toSet[Symbol] - lazy val isUnbox = unboxMethod.values.toSet[Symbol] - lazy val isBox = boxMethod.values.toSet[Symbol] - - /** Is symbol a phantom class for which no runtime representation exists? */ - lazy val isPhantomClass = Set[Symbol](AnyClass, AnyValClass, NullClass, NothingClass) - - /** Is the symbol that of a parent which is added during parsing? */ - lazy val isPossibleSyntheticParent = ProductClass.toSet[Symbol] + ProductRootClass + SerializableClass - - private lazy val boxedValueClassesSet = boxedClass.values.toSet[Symbol] + BoxedUnitClass - - /** Is symbol a value class? */ - def isPrimitiveValueClass(sym: Symbol) = ScalaValueClasses contains sym - def isNonUnitValueClass(sym: Symbol) = isPrimitiveValueClass(sym) && (sym != UnitClass) - def isSpecializableClass(sym: Symbol) = isPrimitiveValueClass(sym) || (sym == AnyRefClass) - def isPrimitiveValueType(tp: Type) = isPrimitiveValueClass(tp.typeSymbol) - - /** Is symbol a boxed value class, e.g. java.lang.Integer? */ - def isBoxedValueClass(sym: Symbol) = boxedValueClassesSet(sym) - - /** If symbol is a value class (boxed or not), return the unboxed - * value class. Otherwise, NoSymbol. - */ - def unboxedValueClass(sym: Symbol): Symbol = - if (isPrimitiveValueClass(sym)) sym - else if (sym == BoxedUnitClass) UnitClass - else boxedClass.map(kvp => (kvp._2: Symbol, kvp._1)).getOrElse(sym, NoSymbol) - - /** Is type's symbol a numeric value class? */ - def isNumericValueType(tp: Type): Boolean = tp match { - case TypeRef(_, sym, _) => isNumericValueClass(sym) - case _ => false - } - - // todo: reconcile with javaSignature!!! - def signature(tp: Type): String = { - def erasure(tp: Type): Type = tp match { - case st: SubType => erasure(st.supertype) - case RefinedType(parents, _) => erasure(parents.head) - case _ => tp - } - def flatNameString(sym: Symbol, separator: Char): String = - if (sym == NoSymbol) "" // be more resistant to error conditions, e.g. neg/t3222.scala - else if (sym.owner.isPackageClass) sym.javaClassName - else flatNameString(sym.owner, separator) + nme.NAME_JOIN_STRING + sym.simpleName - def signature1(etp: Type): String = { - if (etp.typeSymbol == ArrayClass) "[" + signature1(erasure(etp.normalize.typeArgs.head)) - else if (isPrimitiveValueClass(etp.typeSymbol)) abbrvTag(etp.typeSymbol).toString() - else "L" + flatNameString(etp.typeSymbol, '/') + ";" - } - val etp = erasure(tp) - if (etp.typeSymbol == ArrayClass) signature1(etp) - else flatNameString(etp.typeSymbol, '.') - } - - /** Surgery on the value classes. Without this, AnyVals defined in source - * files end up with an AnyRef parent. It is likely there is a better way - * to evade that AnyRef. - */ - private def setParents(sym: Symbol, parents: List[Type]): Symbol = sym.rawInfo match { - case ClassInfoType(_, scope, clazz) => - sym setInfo ClassInfoType(parents, scope, clazz) - case _ => - sym - } - - def init() { - if (isInitialized) return - - val forced = List( // force initialization of every symbol that is entered as a side effect - AnnotationDefaultAttr, // #2264 - RepeatedParamClass, - JavaRepeatedParamClass, - ByNameParamClass, - AnyClass, - AnyRefClass, - AnyValClass, - NullClass, - NothingClass, - SingletonClass, - EqualsPatternClass, - Any_==, - Any_!=, - Any_equals, - Any_hashCode, - Any_toString, - Any_getClass, - Any_isInstanceOf, - Any_asInstanceOf, - Any_##, - Object_eq, - Object_ne, - Object_==, - Object_!=, - Object_##, - Object_synchronized, - Object_isInstanceOf, - Object_asInstanceOf, - String_+, - ComparableClass, - JavaSerializableClass - ) - - isInitialized = true - } //init - - var nbScalaCallers: Int = 0 - def newScalaCaller(delegateType: Type): MethodSymbol = { - assert(forMSIL, "scalaCallers can only be created if target is .NET") - // object: reference to object on which to call (scala-)method - val paramTypes: List[Type] = List(ObjectClass.tpe) - val name = newTermName("$scalaCaller$$" + nbScalaCallers) - // tparam => resultType, which is the resultType of PolyType, i.e. the result type after applying the - // type parameter =-> a MethodType in this case - // TODO: set type bounds manually (-> MulticastDelegate), see newTypeParam - val newCaller = enterNewMethod(DelegateClass, name, paramTypes, delegateType, FINAL | STATIC) - // val newCaller = newPolyMethod(DelegateClass, name, - // tparam => MethodType(paramTypes, tparam.typeConstructor)) setFlag (FINAL | STATIC) - Delegate_scalaCallers = Delegate_scalaCallers ::: List(newCaller) - nbScalaCallers += 1 - newCaller - } - - // def addScalaCallerInfo(scalaCaller: Symbol, methSym: Symbol, delType: Type) { - // assert(Delegate_scalaCallers contains scalaCaller) - // Delegate_scalaCallerInfos += (scalaCaller -> (methSym, delType)) - // } - - def addScalaCallerInfo(scalaCaller: Symbol, methSym: Symbol) { - assert(Delegate_scalaCallers contains scalaCaller) - Delegate_scalaCallerTargets += (scalaCaller -> methSym) - } - } -} diff --git a/src/compiler/scala/reflect/internal/ExistentialsAndSkolems.scala b/src/compiler/scala/reflect/internal/ExistentialsAndSkolems.scala deleted file mode 100644 index f1fe4fc118..0000000000 --- a/src/compiler/scala/reflect/internal/ExistentialsAndSkolems.scala +++ /dev/null @@ -1,50 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import scala.collection.{ mutable, immutable } -import util._ - -/** The name of this trait defines the eventual intent better than - * it does the initial contents. - */ -trait ExistentialsAndSkolems { - self: SymbolTable => - - /** Map a list of type parameter symbols to skolemized symbols, which - * can be deskolemized to the original type parameter. (A skolem is a - * representation of a bound variable when viewed inside its scope.) - * !!!Adriaan: this does not work for hk types. - */ - def deriveFreshSkolems(tparams: List[Symbol]): List[Symbol] = { - class Deskolemizer extends LazyType { - override val typeParams = tparams - val typeSkolems = typeParams map (_.newTypeSkolem setInfo this) - override def complete(sym: Symbol) { - // The info of a skolem is the skolemized info of the - // actual type parameter of the skolem - sym setInfo sym.deSkolemize.info.substSym(typeParams, typeSkolems) - } - } - (new Deskolemizer).typeSkolems - } - - /** Convert to corresponding type parameters all skolems of method - * parameters which appear in `tparams`. - */ - def deskolemizeTypeParams(tparams: List[Symbol])(tp: Type): Type = { - class DeSkolemizeMap extends TypeMap { - def apply(tp: Type): Type = tp match { - case TypeRef(pre, sym, args) if sym.isTypeSkolem && (tparams contains sym.deSkolemize) => - mapOver(typeRef(NoPrefix, sym.deSkolemize, args)) - case _ => - mapOver(tp) - } - } - new DeSkolemizeMap mapOver tp - } -} diff --git a/src/compiler/scala/reflect/internal/FatalError.scala b/src/compiler/scala/reflect/internal/FatalError.scala deleted file mode 100644 index c843308480..0000000000 --- a/src/compiler/scala/reflect/internal/FatalError.scala +++ /dev/null @@ -1,6 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ -package scala.reflect.internal -case class FatalError(msg: String) extends Exception(msg) diff --git a/src/compiler/scala/reflect/internal/FlagSets.scala b/src/compiler/scala/reflect/internal/FlagSets.scala deleted file mode 100644 index 0354d2513c..0000000000 --- a/src/compiler/scala/reflect/internal/FlagSets.scala +++ /dev/null @@ -1,66 +0,0 @@ -package scala.reflect -package internal - -import language.implicitConversions - -trait FlagSets extends api.FlagSets { self: SymbolTable => - - type FlagSet = Long - implicit val FlagSetTag = ClassTag[FlagSet](classOf[FlagSet]) - - implicit def addFlagOps(left: FlagSet): FlagOps = - new FlagOpsImpl(left) - - private class FlagOpsImpl(left: Long) extends FlagOps { - def | (right: Long): Long = left | right - def & (right: Long): Long = left & right - def containsAll (right: Long): Boolean = (right & ~left) == 0 - } - - val NoFlags: FlagSet = 0L - - trait FlagValues extends FlagValuesApi - - object Flag extends FlagValues { - val TRAIT : FlagSet = Flags.TRAIT - val MODULE : FlagSet = Flags.MODULE - val MUTABLE : FlagSet = Flags.MUTABLE - val PACKAGE : FlagSet = Flags.PACKAGE - val METHOD : FlagSet = Flags.METHOD - val MACRO : FlagSet = Flags.MACRO - val DEFERRED : FlagSet = Flags.DEFERRED - val ABSTRACT : FlagSet = Flags.ABSTRACT - val FINAL : FlagSet = Flags.FINAL - val SEALED : FlagSet = Flags.SEALED - val IMPLICIT : FlagSet = Flags.IMPLICIT - val LAZY : FlagSet = Flags.LAZY - val OVERRIDE : FlagSet = Flags.OVERRIDE - val PRIVATE : FlagSet = Flags.PRIVATE - val PROTECTED : FlagSet = Flags.PROTECTED - val CASE : FlagSet = Flags.CASE - val ABSOVERRIDE : FlagSet = Flags.ABSOVERRIDE - val BYNAMEPARAM : FlagSet = Flags.BYNAMEPARAM - val PARAM : FlagSet = Flags.PARAM - val PARAMACCESSOR : FlagSet = Flags.PARAMACCESSOR - val CASEACCESSOR : FlagSet = Flags.CASEACCESSOR - val COVARIANT : FlagSet = Flags.COVARIANT - val CONTRAVARIANT : FlagSet = Flags.CONTRAVARIANT - val DEFAULTPARAM : FlagSet = Flags.DEFAULTPARAM - val INTERFACE : FlagSet = Flags.INTERFACE - - def union(flags: FlagSet*): FlagSet = { - var acc = 0L - for (flag <- flags) acc |= flag - acc - } - - def intersection(flags: FlagSet*): FlagSet = { - var acc = -1L - for (flag <- flags) acc &= flag - acc - } - - def containsAll(superset: FlagSet, subset: FlagSet): Boolean = - (subset & ~superset) == 0 - } -} diff --git a/src/compiler/scala/reflect/internal/Flags.scala b/src/compiler/scala/reflect/internal/Flags.scala deleted file mode 100644 index 37e5a23819..0000000000 --- a/src/compiler/scala/reflect/internal/Flags.scala +++ /dev/null @@ -1,483 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import scala.collection.{ mutable, immutable } - -// Flags at each index of a flags Long. Those marked with /M are used in -// Parsers/JavaParsers and therefore definitely appear on Modifiers; but the -// absence of /M on the other flags does not imply they aren't. -// -// Generated by mkFlagsTable() at Thu Feb 02 20:31:52 PST 2012 -// -// 0: PROTECTED/M -// 1: OVERRIDE/M -// 2: PRIVATE/M -// 3: ABSTRACT/M -// 4: DEFERRED/M -// 5: FINAL/M -// 6: METHOD -// 7: INTERFACE/M -// 8: MODULE -// 9: IMPLICIT/M -// 10: SEALED/M -// 11: CASE/M -// 12: MUTABLE/M -// 13: PARAM/M -// 14: PACKAGE -// 15: MACRO/M -// 16: BYNAMEPARAM/M CAPTURED COVARIANT/M -// 17: CONTRAVARIANT/M INCONSTRUCTOR LABEL -// 18: ABSOVERRIDE/M -// 19: LOCAL/M -// 20: JAVA/M -// 21: SYNTHETIC -// 22: STABLE -// 23: STATIC/M -// 24: CASEACCESSOR/M -// 25: DEFAULTPARAM/M TRAIT/M -// 26: BRIDGE -// 27: ACCESSOR -// 28: SUPERACCESSOR -// 29: PARAMACCESSOR/M -// 30: MODULEVAR -// 31: LAZY/M -// 32: IS_ERROR -// 33: OVERLOADED -// 34: LIFTED -// 35: EXISTENTIAL MIXEDIN -// 36: EXPANDEDNAME -// 37: IMPLCLASS PRESUPER/M -// 38: TRANS_FLAG -// 39: LOCKED -// 40: SPECIALIZED -// 41: DEFAULTINIT/M -// 42: VBRIDGE -// 43: VARARGS -// 44: TRIEDCOOKING -// 45: -// 46: -// 47: -// 48: -// 49: -// 50: -// 51: lateDEFERRED -// 52: lateFINAL -// 53: lateMETHOD -// 54: lateINTERFACE -// 55: lateMODULE -// 56: notPROTECTED -// 57: notOVERRIDE -// 58: notPRIVATE -// 59: -// 60: -// 61: -// 62: -// 63: - -/** Flags set on Modifiers instances in the parsing stage. - */ -class ModifierFlags { - final val IMPLICIT = 1 << 9 - final val FINAL = 1 << 5 // May not be overridden. Note that java final implies much more than scala final. - final val PRIVATE = 1 << 2 - final val PROTECTED = 1 << 0 - - final val SEALED = 1 << 10 - final val OVERRIDE = 1 << 1 - final val CASE = 1 << 11 - final val ABSTRACT = 1 << 3 // abstract class, or used in conjunction with abstract override. - // Note difference to DEFERRED! - final val DEFERRED = 1 << 4 // was `abstract' for members | trait is virtual - final val INTERFACE = 1 << 7 // symbol is an interface (i.e. a trait which defines only abstract methods) - final val MUTABLE = 1 << 12 // symbol is a mutable variable. - final val PARAM = 1 << 13 // symbol is a (value or type) parameter to a method - final val MACRO = 1 << 15 // symbol is a macro definition - - final val COVARIANT = 1 << 16 // symbol is a covariant type variable - final val BYNAMEPARAM = 1 << 16 // parameter is by name - final val CONTRAVARIANT = 1 << 17 // symbol is a contravariant type variable - final val ABSOVERRIDE = 1 << 18 // combination of abstract & override - final val LOCAL = 1 << 19 // symbol is local to current class (i.e. private[this] or protected[this] - // pre: PRIVATE or PROTECTED are also set - final val JAVA = 1 << 20 // symbol was defined by a Java class - final val STATIC = 1 << 23 // static field, method or class - final val CASEACCESSOR = 1 << 24 // symbol is a case parameter (or its accessor, or a GADT skolem) - final val TRAIT = 1 << 25 // symbol is a trait - final val DEFAULTPARAM = 1 << 25 // the parameter has a default value - final val PARAMACCESSOR = 1 << 29 // for field definitions generated for primary constructor - // parameters (no matter if it's a 'val' parameter or not) - // for parameters of a primary constructor ('val' or not) - // for the accessor methods generated for 'val' or 'var' parameters - final val LAZY = 1L << 31 // symbol is a lazy val. can't have MUTABLE unless transformed by typer - final val PRESUPER = 1L << 37 // value is evaluated before super call - final val DEFAULTINIT = 1L << 41 // symbol is initialized to the default value: used by -Xcheckinit - - // Overridden. - def flagToString(flag: Long): String = "" - - final val PrivateLocal = PRIVATE | LOCAL - final val ProtectedLocal = PROTECTED | LOCAL - final val AccessFlags = PRIVATE | PROTECTED | LOCAL -} -object ModifierFlags extends ModifierFlags - -/** All flags and associated operatins */ -class Flags extends ModifierFlags { - final val METHOD = 1 << 6 // a method - final val MODULE = 1 << 8 // symbol is module or class implementing a module - final val PACKAGE = 1 << 14 // symbol is a java package - - final val CAPTURED = 1 << 16 // variable is accessed from nested function. Set by LambdaLift. - final val LABEL = 1 << 17 // method symbol is a label. Set by TailCall - final val INCONSTRUCTOR = 1 << 17 // class symbol is defined in this/superclass constructor. - final val SYNTHETIC = 1 << 21 // symbol is compiler-generated - final val STABLE = 1 << 22 // functions that are assumed to be stable - // (typically, access methods for valdefs) - // or classes that do not contain abstract types. - final val BRIDGE = 1 << 26 // function is a bridge method. Set by Erasure - final val ACCESSOR = 1 << 27 // a value or variable accessor (getter or setter) - - final val SUPERACCESSOR = 1 << 28 // a super accessor - final val MODULEVAR = 1 << 30 // for variables: is the variable caching a module value - - final val IS_ERROR = 1L << 32 // symbol is an error symbol - final val OVERLOADED = 1L << 33 // symbol is overloaded - final val LIFTED = 1L << 34 // class has been lifted out to package level - // local value has been lifted out to class level - // todo: make LIFTED = latePRIVATE? - final val MIXEDIN = 1L << 35 // term member has been mixed in - final val EXISTENTIAL = 1L << 35 // type is an existential parameter or skolem - final val EXPANDEDNAME = 1L << 36 // name has been expanded with class suffix - final val IMPLCLASS = 1L << 37 // symbol is an implementation class - final val TRANS_FLAG = 1L << 38 // transient flag guaranteed to be reset after each phase. - - final val LOCKED = 1L << 39 // temporary flag to catch cyclic dependencies - final val SPECIALIZED = 1L << 40 // symbol is a generated specialized member - final val VBRIDGE = 1L << 42 // symbol is a varargs bridge - - final val VARARGS = 1L << 43 // symbol is a Java-style varargs method - final val TRIEDCOOKING = 1L << 44 // ``Cooking'' has been tried on this symbol - // A Java method's type is ``cooked'' by transforming raw types to existentials - - final val SYNCHRONIZED = 1L << 45 // symbol is a method which should be marked ACC_SYNCHRONIZED - // ------- shift definitions ------------------------------------------------------- - - final val InitialFlags = 0x0001FFFFFFFFFFFFL // flags that are enabled from phase 1. - final val LateFlags = 0x00FE000000000000L // flags that override flags in 0x1FC. - final val AntiFlags = 0x7F00000000000000L // flags that cancel flags in 0x07F - final val LateShift = 47L - final val AntiShift = 56L - - // Flags which sketchily share the same slot - val OverloadedFlagsMask = 0L | BYNAMEPARAM | CONTRAVARIANT | DEFAULTPARAM | EXISTENTIAL | IMPLCLASS - - // ------- late flags (set by a transformer phase) --------------------------------- - // - // Summary of when these are claimed to be first used. - // You can get this output with scalac -Xshow-phases -Ydebug. - // - // refchecks 7 [START] - // specialize 13 [START] - // explicitouter 14 [START] - // erasure 15 [START] - // mixin 20 [START] - // - // lateMETHOD set in RefChecks#transformInfo. - // lateFINAL set in Symbols#makeNotPrivate. - // notPRIVATE set in Symbols#makeNotPrivate, IExplicitOuter#transform, Inliners. - // notPROTECTED set in ExplicitOuter#transform. - // lateDEFERRED set in AddInterfaces, Mixin, etc. - // lateINTERFACE set in AddInterfaces#transformMixinInfo. - // lateMODULE set in Mixin#transformInfo. - // notOVERRIDE set in Mixin#preTransform. - - final val lateDEFERRED = (DEFERRED: Long) << LateShift - final val lateFINAL = (FINAL: Long) << LateShift - final val lateINTERFACE = (INTERFACE: Long) << LateShift - final val lateMETHOD = (METHOD: Long) << LateShift - final val lateMODULE = (MODULE: Long) << LateShift - - final val notOVERRIDE = (OVERRIDE: Long) << AntiShift - final val notPRIVATE = (PRIVATE: Long) << AntiShift - final val notPROTECTED = (PROTECTED: Long) << AntiShift - - // ------- masks ----------------------------------------------------------------------- - - /** To be a little clearer to people who aren't habitual bit twiddlers. - */ - final val AllFlags = -1L - - /** These flags can be set when class or module symbol is first created. - * They are the only flags to survive a call to resetFlags(). - */ - final val TopLevelCreationFlags = - MODULE | PACKAGE | FINAL | JAVA - - // TODO - there's no call to slap four flags onto every package. - final val PackageFlags = TopLevelCreationFlags - - // FINAL not included here due to possibility of object overriding. - // In fact, FINAL should not be attached regardless. We should be able - // to reconstruct whether an object was marked final in source. - final val ModuleFlags = MODULE - - /** These modifiers can be set explicitly in source programs. This is - * used only as the basis for the default flag mask (which ones to display - * when printing a normal message.) - */ - final val ExplicitFlags = - PRIVATE | PROTECTED | ABSTRACT | FINAL | SEALED | - OVERRIDE | CASE | IMPLICIT | ABSOVERRIDE | LAZY - - /** The two bridge flags */ - final val BridgeFlags = BRIDGE | VBRIDGE - final val BridgeAndPrivateFlags = BridgeFlags | PRIVATE - - /** These modifiers appear in TreePrinter output. */ - final val PrintableFlags = - ExplicitFlags | BridgeFlags | LOCAL | SYNTHETIC | STABLE | CASEACCESSOR | MACRO | - ACCESSOR | SUPERACCESSOR | PARAMACCESSOR | STATIC | SPECIALIZED | SYNCHRONIZED - - /** When a symbol for a field is created, only these flags survive - * from Modifiers. Others which may be applied at creation time are: - * PRIVATE, LOCAL. - */ - final val FieldFlags = - MUTABLE | CASEACCESSOR | PARAMACCESSOR | STATIC | FINAL | PRESUPER | LAZY - - /** Masks for getters and setters, where the flags are derived from those - * on the field's modifiers. Both getters and setters get the ACCESSOR flag. - * Getters of immutable values also get STABLE. - */ - final val GetterFlags = ~(PRESUPER | MUTABLE) - final val SetterFlags = ~(PRESUPER | MUTABLE | STABLE | CASEACCESSOR) - - /** When a symbol for a default getter is created, it inherits these - * flags from the method with the default. Other flags applied at creation - * time are SYNTHETIC, DEFAULTPARAM, and possibly OVERRIDE, and maybe PRESUPER. - */ - final val DefaultGetterFlags = PRIVATE | PROTECTED | FINAL - - /** When a symbol for a method parameter is created, only these flags survive - * from Modifiers. Others which may be applied at creation time are: - * SYNTHETIC. - */ - final val ValueParameterFlags = BYNAMEPARAM | IMPLICIT | DEFAULTPARAM - final val BeanPropertyFlags = DEFERRED | OVERRIDE | STATIC - final val VarianceFlags = COVARIANT | CONTRAVARIANT - - /** These appear to be flags which should be transferred from owner symbol - * to a newly created constructor symbol. - */ - final val ConstrFlags = JAVA - - /** Module flags inherited by their module-class */ - final val ModuleToClassFlags = AccessFlags | TopLevelCreationFlags | CASE | SYNTHETIC - - def getterFlags(fieldFlags: Long): Long = ACCESSOR + ( - if ((fieldFlags & MUTABLE) != 0) fieldFlags & ~MUTABLE & ~PRESUPER - else fieldFlags & ~PRESUPER | STABLE - ) - - def setterFlags(fieldFlags: Long): Long = - getterFlags(fieldFlags) & ~STABLE & ~CASEACCESSOR - - // ------- pickling and unpickling of flags ----------------------------------------------- - - // The flags from 0x001 to 0x800 are different in the raw flags - // and in the pickled format. - - private final val IMPLICIT_PKL = (1 << 0) - private final val FINAL_PKL = (1 << 1) - private final val PRIVATE_PKL = (1 << 2) - private final val PROTECTED_PKL = (1 << 3) - private final val SEALED_PKL = (1 << 4) - private final val OVERRIDE_PKL = (1 << 5) - private final val CASE_PKL = (1 << 6) - private final val ABSTRACT_PKL = (1 << 7) - private final val DEFERRED_PKL = (1 << 8) - private final val METHOD_PKL = (1 << 9) - private final val MODULE_PKL = (1 << 10) - private final val INTERFACE_PKL = (1 << 11) - - private final val PKL_MASK = 0x00000FFF - - final val PickledFlags = 0xFFFFFFFFL - - private def rawPickledCorrespondence = Array( - (IMPLICIT, IMPLICIT_PKL), - (FINAL, FINAL_PKL), - (PRIVATE, PRIVATE_PKL), - (PROTECTED, PROTECTED_PKL), - (SEALED, SEALED_PKL), - (OVERRIDE, OVERRIDE_PKL), - (CASE, CASE_PKL), - (ABSTRACT, ABSTRACT_PKL), - (DEFERRED, DEFERRED_PKL), - (METHOD, METHOD_PKL), - (MODULE, MODULE_PKL), - (INTERFACE, INTERFACE_PKL) - ) - private val rawFlags: Array[Int] = rawPickledCorrespondence map (_._1) - private val pickledFlags: Array[Int] = rawPickledCorrespondence map (_._2) - - private def r2p(flags: Int): Int = { - var result = 0 - var i = 0 - while (i < rawFlags.length) { - if ((flags & rawFlags(i)) != 0) - result |= pickledFlags(i) - - i += 1 - } - result - } - private def p2r(flags: Int): Int = { - var result = 0 - var i = 0 - while (i < rawFlags.length) { - if ((flags & pickledFlags(i)) != 0) - result |= rawFlags(i) - - i += 1 - } - result - } - - // ------ displaying flags -------------------------------------------------------- - - // Generated by mkFlagToStringMethod() at Thu Feb 02 20:31:52 PST 2012 - @annotation.switch override def flagToString(flag: Long): String = flag match { - case PROTECTED => "protected" // (1L << 0) - case OVERRIDE => "override" // (1L << 1) - case PRIVATE => "private" // (1L << 2) - case ABSTRACT => "abstract" // (1L << 3) - case DEFERRED => "" // (1L << 4) - case FINAL => "final" // (1L << 5) - case METHOD => "" // (1L << 6) - case INTERFACE => "" // (1L << 7) - case MODULE => "" // (1L << 8) - case IMPLICIT => "implicit" // (1L << 9) - case SEALED => "sealed" // (1L << 10) - case CASE => "case" // (1L << 11) - case MUTABLE => "" // (1L << 12) - case PARAM => "" // (1L << 13) - case PACKAGE => "" // (1L << 14) - case MACRO => "" // (1L << 15) - case BYNAMEPARAM => "" // (1L << 16) - case CONTRAVARIANT => "" // (1L << 17) - case ABSOVERRIDE => "absoverride" // (1L << 18) - case LOCAL => "" // (1L << 19) - case JAVA => "" // (1L << 20) - case SYNTHETIC => "" // (1L << 21) - case STABLE => "" // (1L << 22) - case STATIC => "" // (1L << 23) - case CASEACCESSOR => "" // (1L << 24) - case DEFAULTPARAM => "" // (1L << 25) - case BRIDGE => "" // (1L << 26) - case ACCESSOR => "" // (1L << 27) - case SUPERACCESSOR => "" // (1L << 28) - case PARAMACCESSOR => "" // (1L << 29) - case MODULEVAR => "" // (1L << 30) - case LAZY => "lazy" // (1L << 31) - case IS_ERROR => "" // (1L << 32) - case OVERLOADED => "" // (1L << 33) - case LIFTED => "" // (1L << 34) - case EXISTENTIAL => "" // (1L << 35) - case EXPANDEDNAME => "" // (1L << 36) - case IMPLCLASS => "" // (1L << 37) - case TRANS_FLAG => "" // (1L << 38) - case LOCKED => "" // (1L << 39) - case SPECIALIZED => "" // (1L << 40) - case DEFAULTINIT => "" // (1L << 41) - case VBRIDGE => "" // (1L << 42) - case VARARGS => "" // (1L << 43) - case TRIEDCOOKING => "" // (1L << 44) - case SYNCHRONIZED => "" // (1L << 45) - case 0x400000000000L => "" // (1L << 46) - case 0x800000000000L => "" // (1L << 47) - case 0x1000000000000L => "" // (1L << 48) - case 0x2000000000000L => "" // (1L << 49) - case 0x4000000000000L => "" // (1L << 50) - case `lateDEFERRED` => "" // (1L << 51) - case `lateFINAL` => "" // (1L << 52) - case `lateMETHOD` => "" // (1L << 53) - case `lateINTERFACE` => "" // (1L << 54) - case `lateMODULE` => "" // (1L << 55) - case `notPROTECTED` => "" // (1L << 56) - case `notOVERRIDE` => "" // (1L << 57) - case `notPRIVATE` => "" // (1L << 58) - case 0x800000000000000L => "" // (1L << 59) - case 0x1000000000000000L => "" // (1L << 60) - case 0x2000000000000000L => "" // (1L << 61) - case 0x4000000000000000L => "" // (1L << 62) - case 0x8000000000000000L => "" // (1L << 63) - case _ => "" - } - - private def accessString(flags: Long, privateWithin: String)= ( - if (privateWithin == "") { - if ((flags & PrivateLocal) == PrivateLocal) "private[this]" - else if ((flags & ProtectedLocal) == ProtectedLocal) "protected[this]" - else if ((flags & PRIVATE) != 0) "private" - else if ((flags & PROTECTED) != 0) "protected" - else "" - } - else if ((flags & PROTECTED) != 0) "protected[" + privateWithin + "]" - else "private[" + privateWithin + "]" - ) - - @deprecated("Use flagString on the flag-carrying member", "2.10.0") - def flagsToString(flags: Long, privateWithin: String): String = { - val access = accessString(flags, privateWithin) - val nonAccess = flagsToString(flags & ~AccessFlags) - - List(nonAccess, access) filterNot (_ == "") mkString " " - } - - @deprecated("Use flagString on the flag-carrying member", "2.10.0") - def flagsToString(flags: Long): String = { - // Fast path for common case - if (flags == 0L) "" else { - var sb: StringBuilder = null - var i = 0 - while (i <= MaxBitPosition) { - val mask = rawFlagPickledOrder(i) - if ((flags & mask) != 0L) { - val s = flagToString(mask) - if (s.length > 0) { - if (sb eq null) sb = new StringBuilder append s - else if (sb.length == 0) sb append s - else sb append " " append s - } - } - i += 1 - } - if (sb eq null) "" else sb.toString - } - } - - def rawFlagsToPickled(flags: Long): Long = - (flags & ~PKL_MASK) | r2p(flags.toInt & PKL_MASK) - - def pickledToRawFlags(pflags: Long): Long = - (pflags & ~PKL_MASK) | p2r(pflags.toInt & PKL_MASK) - - // List of the raw flags, in pickled order - final val MaxBitPosition = 62 - - final val pickledListOrder: List[Long] = { - val all = 0 to MaxBitPosition map (1L << _) - val front = rawFlags map (_.toLong) - - front.toList ++ (all filterNot (front contains _)) - } - final val rawFlagPickledOrder: Array[Long] = pickledListOrder.toArray -} - -object Flags extends Flags { } diff --git a/src/compiler/scala/reflect/internal/HasFlags.scala b/src/compiler/scala/reflect/internal/HasFlags.scala deleted file mode 100644 index c7c0882209..0000000000 --- a/src/compiler/scala/reflect/internal/HasFlags.scala +++ /dev/null @@ -1,169 +0,0 @@ -package scala.reflect -package internal - -import Flags._ - -/** Common code utilized by Modifiers (which carry the flags associated - * with Trees) and Symbol. - */ -trait HasFlags { - type AccessBoundaryType - type AnnotationType - - /** Though both Symbol and Modifiers widen this method to public, it's - * defined protected here to give us the option in the future to route - * flag methods through accessors and disallow raw flag manipulation. - * And after that, perhaps, on some magical day: a typesafe enumeration. - */ - protected def flags: Long - - /** Access level encoding: there are three scala flags (PRIVATE, PROTECTED, - * and LOCAL) which combine with value privateWithin (the "foo" in private[foo]) - * to define from where an entity can be accessed. The meanings are as follows: - * - * PRIVATE access restricted to class only. - * PROTECTED access restricted to class and subclasses only. - * LOCAL can only be set in conjunction with PRIVATE or PROTECTED. - * Further restricts access to the same object instance. - * - * In addition, privateWithin can be used to set a visibility barrier. - * When set, everything contained in the named enclosing package or class - * has access. It is incompatible with PRIVATE or LOCAL, but is additive - * with PROTECTED (i.e. if either the flags or privateWithin allow access, - * then it is allowed.) - * - * The java access levels translate as follows: - * - * java private: hasFlag(PRIVATE) && !hasAccessBoundary - * java package: !hasFlag(PRIVATE | PROTECTED) && (privateWithin == enclosing package) - * java protected: hasFlag(PROTECTED) && (privateWithin == enclosing package) - * java public: !hasFlag(PRIVATE | PROTECTED) && !hasAccessBoundary - */ - def privateWithin: AccessBoundaryType - - /** A list of annotations attached to this entity. - */ - def annotations: List[AnnotationType] - - /** Whether this entity has a "privateWithin" visibility barrier attached. - */ - def hasAccessBoundary: Boolean - - /** Whether this entity has ANY of the flags in the given mask. - */ - def hasFlag(flag: Long): Boolean - - /** Whether this entity has ALL of the flags in the given mask. - */ - def hasAllFlags(mask: Long): Boolean - - /** Whether this entity has NONE of the flags in the given mask. - */ - def hasNoFlags(mask: Long): Boolean = !hasFlag(mask) - - /** The printable representation of this entity's flags and access boundary, - * restricted to flags in the given mask. - */ - def flagString: String = flagString(flagMask) - def flagString(mask: Long): String = calculateFlagString(flags & mask) - - /** The default mask determining which flags to display. - */ - def flagMask: Long = AllFlags - - /** The string representation of a single bit, seen from this - * flag carrying entity. - */ - def resolveOverloadedFlag(flag: Long): String = Flags.flagToString(flag) - - // Tests which come through cleanly: both Symbol and Modifiers use these - // identically, testing for a single flag. - def hasAbstractFlag = hasFlag(ABSTRACT) - def hasAccessorFlag = hasFlag(ACCESSOR) - def hasDefault = hasAllFlags(DEFAULTPARAM | PARAM) - def hasLocalFlag = hasFlag(LOCAL) - def hasModuleFlag = hasFlag(MODULE) - def hasPackageFlag = hasFlag(PACKAGE) - def hasStableFlag = hasFlag(STABLE) - def hasStaticFlag = hasFlag(STATIC) - def isAbstractOverride = hasFlag(ABSOVERRIDE) - def isAnyOverride = hasFlag(OVERRIDE | ABSOVERRIDE) - def isCase = hasFlag(CASE) - def isCaseAccessor = hasFlag(CASEACCESSOR) - def isDeferred = hasFlag(DEFERRED) - def isFinal = hasFlag(FINAL) - def isImplicit = hasFlag(IMPLICIT) - def isInterface = hasFlag(INTERFACE) - def isJavaDefined = hasFlag(JAVA) - def isLabel = hasAllFlags(LABEL | METHOD) && !hasAccessorFlag - def isLazy = hasFlag(LAZY) - def isLifted = hasFlag(LIFTED) - def isMutable = hasFlag(MUTABLE) - def isOverride = hasFlag(OVERRIDE) - def isParamAccessor = hasFlag(PARAMACCESSOR) - def isPrivate = hasFlag(PRIVATE) - def isPackage = hasFlag(PACKAGE) - def isPrivateLocal = hasAllFlags(PrivateLocal) - def isProtected = hasFlag(PROTECTED) - def isProtectedLocal = hasAllFlags(ProtectedLocal) - def isPublic = hasNoFlags(PRIVATE | PROTECTED) && !hasAccessBoundary - def isSealed = hasFlag(SEALED) - def isSuperAccessor = hasFlag(SUPERACCESSOR) - def isSynthetic = hasFlag(SYNTHETIC) - def isTrait = hasFlag(TRAIT) && !hasFlag(PARAM) - - def flagBitsToString(bits: Long): String = { - // Fast path for common case - if (bits == 0L) "" else { - var sb: StringBuilder = null - var i = 0 - while (i <= MaxBitPosition) { - val flag = Flags.rawFlagPickledOrder(i) - if ((bits & flag) != 0L) { - val s = resolveOverloadedFlag(flag) - if (s.length > 0) { - if (sb eq null) sb = new StringBuilder append s - else if (sb.length == 0) sb append s - else sb append " " append s - } - } - i += 1 - } - if (sb eq null) "" else sb.toString - } - } - - def accessString: String = { - val pw = if (hasAccessBoundary) privateWithin.toString else "" - - if (pw == "") { - if (hasAllFlags(PrivateLocal)) "private[this]" - else if (hasAllFlags(ProtectedLocal)) "protected[this]" - else if (hasFlag(PRIVATE)) "private" - else if (hasFlag(PROTECTED)) "protected" - else "" - } - else if (hasFlag(PROTECTED)) "protected[" + pw + "]" - else "private[" + pw + "]" - } - protected def calculateFlagString(basis: Long): String = { - val access = accessString - val nonAccess = flagBitsToString(basis & ~AccessFlags) - - if (access == "") nonAccess - else if (nonAccess == "") access - else nonAccess + " " + access - } - - // Backward compat section - @deprecated( "Use isTrait", "2.10.0") - def hasTraitFlag = hasFlag(TRAIT) - @deprecated("Use hasDefault", "2.10.0") - def hasDefaultFlag = hasFlag(DEFAULTPARAM) - @deprecated("Use isValueParameter or isTypeParameter", "2.10.0") - def isParameter = hasFlag(PARAM) - @deprecated("Use flagString", "2.10.0") - def defaultFlagString = flagString - @deprecated("Use flagString(mask)", "2.10.0") - def hasFlagsToString(mask: Long): String = flagString(mask) -} diff --git a/src/compiler/scala/reflect/internal/Importers.scala b/src/compiler/scala/reflect/internal/Importers.scala deleted file mode 100644 index 431d9819a5..0000000000 --- a/src/compiler/scala/reflect/internal/Importers.scala +++ /dev/null @@ -1,451 +0,0 @@ -package scala.reflect -package internal -import scala.collection.mutable.WeakHashMap - -// todo: move importers to a mirror -trait Importers { self: SymbolTable => - - // [Eugene] possible to make this less cast-heavy? - def mkImporter(from0: api.Universe): Importer { val from: from0.type } = ( - if (self eq from0) { - new Importer { - val from = from0 - val reverse = this.asInstanceOf[from.Importer{ val from: self.type }] - def importSymbol(sym: from.Symbol) = sym.asInstanceOf[self.Symbol] - def importType(tpe: from.Type) = tpe.asInstanceOf[self.Type] - def importTree(tree: from.Tree) = tree.asInstanceOf[self.Tree] - } - } else { - // todo. fix this loophole - assert(from0.isInstanceOf[SymbolTable], "`from` should be an instance of scala.reflect.internal.SymbolTable") - new StandardImporter { val from = from0.asInstanceOf[SymbolTable] } - } - ).asInstanceOf[Importer { val from: from0.type }] - - abstract class StandardImporter extends Importer { - - val from: SymbolTable - - lazy val symMap: WeakHashMap[from.Symbol, Symbol] = new WeakHashMap - lazy val tpeMap: WeakHashMap[from.Type, Type] = new WeakHashMap - - // fixups and maps prevent stackoverflows in importer - var pendingSyms = 0 - var pendingTpes = 0 - lazy val fixups = collection.mutable.MutableList[Function0[Unit]]() - def addFixup(fixup: => Unit): Unit = fixups += (() => fixup) - def tryFixup(): Unit = { - if (pendingSyms == 0 && pendingTpes == 0) { - val fixups = this.fixups.toList - this.fixups.clear() - fixups foreach { _() } - } - } - - object reverse extends from.StandardImporter { - val from: self.type = self - for ((fromsym, mysym) <- StandardImporter.this.symMap) symMap += ((mysym, fromsym)) - for ((fromtpe, mytpe) <- StandardImporter.this.tpeMap) tpeMap += ((mytpe, fromtpe)) - } - - // todo. careful import of positions - def importPosition(pos: from.Position): Position = - pos.asInstanceOf[Position] - - def importSymbol(sym0: from.Symbol): Symbol = { - def doImport(sym: from.Symbol): Symbol = { - if (symMap.contains(sym)) - return symMap(sym) - - val myowner = importSymbol(sym.owner) - val mypos = importPosition(sym.pos) - val myname = importName(sym.name).toTermName - val myflags = sym.flags - def linkReferenced(mysym: TermSymbol, x: from.TermSymbol, op: from.Symbol => Symbol): Symbol = { - symMap(x) = mysym - mysym.referenced = op(x.referenced) - mysym - } - val mysym = sym match { - case x: from.MethodSymbol => - linkReferenced(myowner.newMethod(myname, mypos, myflags), x, importSymbol) - case x: from.ModuleSymbol => - linkReferenced(myowner.newModuleSymbol(myname, mypos, myflags), x, importSymbol) - case x: from.FreeTermSymbol => - newFreeTermSymbol(importName(x.name).toTermName, importType(x.info), x.value, x.flags, x.origin) - case x: from.FreeTypeSymbol => - newFreeTypeSymbol(importName(x.name).toTypeName, importType(x.info), x.value, x.flags, x.origin) - case x: from.TermSymbol => - linkReferenced(myowner.newValue(myname, mypos, myflags), x, importSymbol) - case x: from.TypeSkolem => - val origin = x.unpackLocation match { - case null => null - case y: from.Tree => importTree(y) - case y: from.Symbol => importSymbol(y) - } - myowner.newTypeSkolemSymbol(myname.toTypeName, origin, mypos, myflags) - case x: from.ModuleClassSymbol => - val mysym = myowner.newModuleClass(myname.toTypeName, mypos, myflags) - symMap(x) = mysym - mysym.sourceModule = importSymbol(x.sourceModule) - mysym - case x: from.ClassSymbol => - val mysym = myowner.newClassSymbol(myname.toTypeName, mypos, myflags) - symMap(x) = mysym - if (sym.thisSym != sym) { - mysym.typeOfThis = importType(sym.typeOfThis) - mysym.thisSym setName importName(sym.thisSym.name) - } - mysym - case x: from.TypeSymbol => - myowner.newTypeSymbol(myname.toTypeName, mypos, myflags) - } - symMap(sym) = mysym - mysym setFlag Flags.LOCKED - mysym setInfo { - val mytypeParams = sym.typeParams map importSymbol - new LazyPolyType(mytypeParams) { - override def complete(s: Symbol) { - val result = sym.info match { - case from.PolyType(_, res) => res - case result => result - } - s setInfo GenPolyType(mytypeParams, importType(result)) - s setAnnotations (sym.annotations map importAnnotationInfo) - } - } - } - mysym resetFlag Flags.LOCKED - } // end doImport - - def importOrRelink: Symbol = { - val sym = sym0 // makes sym visible in the debugger - if (sym == null) - null - else if (sym == from.NoSymbol) - NoSymbol - else if (sym.isRoot) - rootMirror.RootClass // !!! replace with actual mirror when we move importers to the mirror - else { - val name = sym.name - val owner = sym.owner - var scope = if (owner.isClass && !owner.isRefinementClass) owner.info else from.NoType - var existing = scope.decl(name) - if (sym.isModuleClass) - existing = existing.moduleClass - - if (!existing.exists) scope = from.NoType - - val myname = importName(name) - val myowner = importSymbol(owner) - val myscope = if (scope != from.NoType && !(myowner hasFlag Flags.LOCKED)) myowner.info else NoType - var myexisting = if (myscope != NoType) myowner.info.decl(myname) else NoSymbol // cannot load myexisting in general case, because it creates cycles for methods - if (sym.isModuleClass) - myexisting = importSymbol(sym.sourceModule).moduleClass - - if (!sym.isOverloaded && myexisting.isOverloaded) { - myexisting = - if (sym.isMethod) { - val localCopy = doImport(sym) - myexisting filter (_.tpe matches localCopy.tpe) - } else { - myexisting filter (!_.isMethod) - } - assert(!myexisting.isOverloaded, - "import failure: cannot determine unique overloaded method alternative from\n "+ - (myexisting.alternatives map (_.defString) mkString "\n")+"\n that matches "+sym+":"+sym.tpe) - } - - val mysym = { - if (sym.isOverloaded) { - myowner.newOverloaded(myowner.thisType, sym.alternatives map importSymbol) - } else if (sym.isTypeParameter && sym.paramPos >= 0 && !(myowner hasFlag Flags.LOCKED)) { - assert(myowner.typeParams.length > sym.paramPos, - "import failure: cannot determine parameter "+sym+" (#"+sym.paramPos+") in "+ - myowner+typeParamsString(myowner.rawInfo)+"\n original symbol was: "+ - sym.owner+from.typeParamsString(sym.owner.info)) - myowner.typeParams(sym.paramPos) - } else { - if (myexisting != NoSymbol) { - myexisting - } else { - val mysym = doImport(sym) - - if (myscope != NoType) { - assert(myowner.info.decls.lookup(myname) == NoSymbol, myname+" "+myowner.info.decl(myname)+" "+myexisting) - myowner.info.decls enter mysym - } - - mysym - } - } - } - - mysym - } - } // end importOrRelink - - val sym = sym0 - if (symMap contains sym) { - symMap(sym) - } else { - pendingSyms += 1 - - try { - symMap getOrElseUpdate (sym, importOrRelink) - } finally { - pendingSyms -= 1 - tryFixup() - } - } - } - - def importType(tpe: from.Type): Type = { - def doImport(tpe: from.Type): Type = tpe match { - case from.TypeRef(pre, sym, args) => - TypeRef(importType(pre), importSymbol(sym), args map importType) - case from.ThisType(clazz) => - ThisType(importSymbol(clazz)) - case from.SingleType(pre, sym) => - SingleType(importType(pre), importSymbol(sym)) - case from.MethodType(params, restpe) => - MethodType(params map importSymbol, importType(restpe)) - case from.PolyType(tparams, restpe) => - PolyType(tparams map importSymbol, importType(restpe)) - case from.NullaryMethodType(restpe) => - NullaryMethodType(importType(restpe)) - case from.ConstantType(constant @ from.Constant(_)) => - ConstantType(importConstant(constant)) - case from.SuperType(thistpe, supertpe) => - SuperType(importType(thistpe), importType(supertpe)) - case from.TypeBounds(lo, hi) => - TypeBounds(importType(lo), importType(hi)) - case from.BoundedWildcardType(bounds) => - BoundedWildcardType(importTypeBounds(bounds)) - case from.ClassInfoType(parents, decls, clazz) => - val myclazz = importSymbol(clazz) - val myscope = if (myclazz.isPackageClass) newPackageScope(myclazz) else newScope - val myclazzTpe = ClassInfoType(parents map importType, myscope, myclazz) - myclazz setInfo GenPolyType(myclazz.typeParams, myclazzTpe) // needed so that newly created symbols find their scope - decls foreach importSymbol // will enter itself into myclazz - myclazzTpe - case from.RefinedType(parents, decls) => - RefinedType(parents map importType, importScope(decls), importSymbol(tpe.typeSymbol)) - case from.ExistentialType(tparams, restpe) => - newExistentialType(tparams map importSymbol, importType(restpe)) - case from.OverloadedType(pre, alts) => - OverloadedType(importType(pre), alts map importSymbol) - case from.AntiPolyType(pre, targs) => - AntiPolyType(importType(pre), targs map importType) - case x: from.TypeVar => - TypeVar(importType(x.origin), importTypeConstraint(x.constr0), x.typeArgs map importType, x.params map importSymbol) - case from.NotNullType(tpe) => - NotNullType(importType(tpe)) - case from.AnnotatedType(annots, tpe, selfsym) => - AnnotatedType(annots map importAnnotationInfo, importType(tpe), importSymbol(selfsym)) - case from.ErrorType => - ErrorType - case from.WildcardType => - WildcardType - case from.NoType => - NoType - case from.NoPrefix => - NoPrefix - case null => - null - } // end doImport - - def importOrRelink: Type = - doImport(tpe) - - if (tpeMap contains tpe) { - tpeMap(tpe) - } else { - pendingTpes += 1 - - try { - tpeMap getOrElseUpdate (tpe, importOrRelink) - } finally { - pendingTpes -= 1 - tryFixup() - } - } - } - - def importTypeBounds(bounds: from.TypeBounds) = importType(bounds).asInstanceOf[TypeBounds] - - def importAnnotationInfo(ann: from.AnnotationInfo): AnnotationInfo = { - val atp1 = importType(ann.atp) - val args1 = ann.args map importTree - val assocs1 = ann.assocs map { case (name, arg) => (importName(name), importAnnotArg(arg)) } - val original1 = importTree(ann.original) - AnnotationInfo(atp1, args1, assocs1) setOriginal original1 - } - - def importAnnotArg(arg: from.ClassfileAnnotArg): ClassfileAnnotArg = arg match { - case from.LiteralAnnotArg(constant @ from.Constant(_)) => - LiteralAnnotArg(importConstant(constant)) - case from.ArrayAnnotArg(args) => - ArrayAnnotArg(args map importAnnotArg) - case from.ScalaSigBytes(bytes) => - ScalaSigBytes(bytes) - case from.NestedAnnotArg(annInfo) => - NestedAnnotArg(importAnnotationInfo(annInfo)) - } - - def importTypeConstraint(constr: from.TypeConstraint): TypeConstraint = { - val result = new TypeConstraint(constr.loBounds map importType, constr.hiBounds map importType) - result.inst = importType(constr.inst) - result - } - - // !!! todo: override to cater for PackageScopes - def importScope(decls: from.Scope): Scope = - newScopeWith(decls.toList map importSymbol: _*) - - def importName(name: from.Name): Name = - if (name.isTypeName) newTypeName(name.toString) else newTermName(name.toString) - def importTypeName(name: from.TypeName): TypeName = importName(name).toTypeName - def importTermName(name: from.TermName): TermName = importName(name).toTermName - - def importModifiers(mods: from.Modifiers): Modifiers = - new Modifiers(mods.flags, importName(mods.privateWithin), mods.annotations map importTree) - - def importImportSelector(sel: from.ImportSelector): ImportSelector = - new ImportSelector(importName(sel.name), sel.namePos, if (sel.rename != null) importName(sel.rename) else null, sel.renamePos) - - def importTree(tree: from.Tree): Tree = { - val mytree = tree match { - case from.ClassDef(mods, name, tparams, impl) => - new ClassDef(importModifiers(mods), importName(name).toTypeName, tparams map importTypeDef, importTemplate(impl)) - case from.PackageDef(pid, stats) => - new PackageDef(importRefTree(pid), stats map importTree) - case from.ModuleDef(mods, name, impl) => - new ModuleDef(importModifiers(mods), importName(name).toTermName, importTemplate(impl)) - case from.emptyValDef => - emptyValDef - case from.ValDef(mods, name, tpt, rhs) => - new ValDef(importModifiers(mods), importName(name).toTermName, importTree(tpt), importTree(rhs)) - case from.DefDef(mods, name, tparams, vparamss, tpt, rhs) => - new DefDef(importModifiers(mods), importName(name).toTermName, tparams map importTypeDef, mmap(vparamss)(importValDef), importTree(tpt), importTree(rhs)) - case from.TypeDef(mods, name, tparams, rhs) => - new TypeDef(importModifiers(mods), importName(name).toTypeName, tparams map importTypeDef, importTree(rhs)) - case from.LabelDef(name, params, rhs) => - new LabelDef(importName(name).toTermName, params map importIdent, importTree(rhs)) - case from.Import(expr, selectors) => - new Import(importTree(expr), selectors map importImportSelector) - case from.Template(parents, self, body) => - new Template(parents map importTree, importValDef(self), body map importTree) - case from.Block(stats, expr) => - new Block(stats map importTree, importTree(expr)) - case from.CaseDef(pat, guard, body) => - new CaseDef(importTree(pat), importTree(guard), importTree(body)) - case from.Alternative(trees) => - new Alternative(trees map importTree) - case from.Star(elem) => - new Star(importTree(elem)) - case from.Bind(name, body) => - new Bind(importName(name), importTree(body)) - case from.UnApply(fun, args) => - new UnApply(importTree(fun), args map importTree) - case from.ArrayValue(elemtpt ,elems) => - new ArrayValue(importTree(elemtpt), elems map importTree) - case from.Function(vparams, body) => - new Function(vparams map importValDef, importTree(body)) - case from.Assign(lhs, rhs) => - new Assign(importTree(lhs), importTree(rhs)) - case from.AssignOrNamedArg(lhs, rhs) => - new AssignOrNamedArg(importTree(lhs), importTree(rhs)) - case from.If(cond, thenp, elsep) => - new If(importTree(cond), importTree(thenp), importTree(elsep)) - case from.Match(selector, cases) => - new Match(importTree(selector), cases map importCaseDef) - case from.Return(expr) => - new Return(importTree(expr)) - case from.Try(block, catches, finalizer) => - new Try(importTree(block), catches map importCaseDef, importTree(finalizer)) - case from.Throw(expr) => - new Throw(importTree(expr)) - case from.New(tpt) => - new New(importTree(tpt)) - case from.Typed(expr, tpt) => - new Typed(importTree(expr), importTree(tpt)) - case from.TypeApply(fun, args) => - new TypeApply(importTree(fun), args map importTree) - case from.Apply(fun, args) => tree match { - case _: from.ApplyToImplicitArgs => - new ApplyToImplicitArgs(importTree(fun), args map importTree) - case _: from.ApplyImplicitView => - new ApplyImplicitView(importTree(fun), args map importTree) - case _ => - new Apply(importTree(fun), args map importTree) - } - case from.ApplyDynamic(qual, args) => - new ApplyDynamic(importTree(qual), args map importTree) - case from.Super(qual, mix) => - new Super(importTree(qual), importTypeName(mix)) - case from.This(qual) => - new This(importName(qual).toTypeName) - case from.Select(qual, name) => - new Select(importTree(qual), importName(name)) - case from.Ident(name) => - new Ident(importName(name)) - case from.ReferenceToBoxed(ident) => - new ReferenceToBoxed(importTree(ident) match { case ident: Ident => ident }) - case from.Literal(constant @ from.Constant(_)) => - new Literal(importConstant(constant)) - case from.TypeTree() => - new TypeTree() - case from.Annotated(annot, arg) => - new Annotated(importTree(annot), importTree(arg)) - case from.SingletonTypeTree(ref) => - new SingletonTypeTree(importTree(ref)) - case from.SelectFromTypeTree(qual, name) => - new SelectFromTypeTree(importTree(qual), importName(name).toTypeName) - case from.CompoundTypeTree(templ) => - new CompoundTypeTree(importTemplate(templ)) - case from.AppliedTypeTree(tpt, args) => - new AppliedTypeTree(importTree(tpt), args map importTree) - case from.TypeBoundsTree(lo, hi) => - new TypeBoundsTree(importTree(lo), importTree(hi)) - case from.ExistentialTypeTree(tpt, whereClauses) => - new ExistentialTypeTree(importTree(tpt), whereClauses map importTree) - case from.EmptyTree => - EmptyTree - case null => - null - } - addFixup({ - if (mytree != null) { - val mysym = if (tree.hasSymbol) importSymbol(tree.symbol) else NoSymbol - val mytpe = importType(tree.tpe) - - mytree match { - case mytt: TypeTree => - val tt = tree.asInstanceOf[from.TypeTree] - if (mytree.hasSymbol) mytt.symbol = mysym - if (tt.wasEmpty) mytt.defineType(mytpe) else mytt.setType(mytpe) - if (tt.original != null) mytt.setOriginal(importTree(tt.original)) - case _ => - if (mytree.hasSymbol) mytree.symbol = importSymbol(tree.symbol) - mytree.tpe = importType(tree.tpe) - } - } - }) - tryFixup() - mytree - } - - def importValDef(tree: from.ValDef): ValDef = importTree(tree).asInstanceOf[ValDef] - def importTypeDef(tree: from.TypeDef): TypeDef = importTree(tree).asInstanceOf[TypeDef] - def importTemplate(tree: from.Template): Template = importTree(tree).asInstanceOf[Template] - def importRefTree(tree: from.RefTree): RefTree = importTree(tree).asInstanceOf[RefTree] - def importIdent(tree: from.Ident): Ident = importTree(tree).asInstanceOf[Ident] - def importCaseDef(tree: from.CaseDef): CaseDef = importTree(tree).asInstanceOf[CaseDef] - def importConstant(constant: from.Constant): Constant = new Constant(constant.tag match { - case ClazzTag => importType(constant.value.asInstanceOf[from.Type]) - case EnumTag => importSymbol(constant.value.asInstanceOf[from.Symbol]) - case _ => constant.value - }) - } -} \ No newline at end of file diff --git a/src/compiler/scala/reflect/internal/InfoTransformers.scala b/src/compiler/scala/reflect/internal/InfoTransformers.scala deleted file mode 100644 index e53f714c0c..0000000000 --- a/src/compiler/scala/reflect/internal/InfoTransformers.scala +++ /dev/null @@ -1,51 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -trait InfoTransformers { - self: SymbolTable => - - /* Syncnote: This should not need to be protected, as reflection does not run in multiple phases. - */ - abstract class InfoTransformer { - var prev: InfoTransformer = this - var next: InfoTransformer = this - - val pid: Phase#Id - val changesBaseClasses: Boolean - def transform(sym: Symbol, tpe: Type): Type - - def insert(that: InfoTransformer) { - assert(this.pid != that.pid, this.pid) - - if (that.pid < this.pid) { - prev insert that - } else if (next.pid <= that.pid && next.pid != NoPhase.id) { - next insert that - } else { - log("Inserting info transformer %s following %s".format(phaseOf(that.pid), phaseOf(this.pid))) - that.next = next - that.prev = this - next.prev = that - this.next = that - } - } - - /** The InfoTransformer whose (pid == from). - * If no such exists, the InfoTransformer with the next - * higher pid. - */ - def nextFrom(from: Phase#Id): InfoTransformer = - if (from == this.pid) this - else if (from < this.pid) - if (prev.pid < from) this - else prev.nextFrom(from); - else if (next.pid == NoPhase.id) next - else next.nextFrom(from) - } -} - diff --git a/src/compiler/scala/reflect/internal/Kinds.scala b/src/compiler/scala/reflect/internal/Kinds.scala deleted file mode 100644 index b736a9192f..0000000000 --- a/src/compiler/scala/reflect/internal/Kinds.scala +++ /dev/null @@ -1,232 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import scala.collection.{ mutable, immutable } -import scala.reflect.internal.util.StringOps.{ countAsString, countElementsAsString } - -trait Kinds { - self: SymbolTable => - - import definitions._ - - private type SymPair = ((Symbol, Symbol)) // ((Argument, Parameter)) - - case class KindErrors( - arity: List[SymPair] = Nil, - variance: List[SymPair] = Nil, - strictness: List[SymPair] = Nil - ) { - def isEmpty = arity.isEmpty && variance.isEmpty && strictness.isEmpty - - def arityError(syms: SymPair) = copy(arity = arity :+ syms) - def varianceError(syms: SymPair) = copy(variance = variance :+ syms) - def strictnessError(syms: SymPair) = copy(strictness = strictness :+ syms) - - def ++(errs: KindErrors) = KindErrors( - arity ++ errs.arity, - variance ++ errs.variance, - strictness ++ errs.strictness - ) - // @M TODO this method is duplicated all over the place (varianceString) - private def varStr(s: Symbol): String = - if (s.isCovariant) "covariant" - else if (s.isContravariant) "contravariant" - else "invariant"; - - private def qualify(a0: Symbol, b0: Symbol): String = if (a0.toString != b0.toString) "" else { - if((a0 eq b0) || (a0.owner eq b0.owner)) "" - else { - var a = a0; var b = b0 - while (a.owner.name == b.owner.name) { a = a.owner; b = b.owner} - if (a.locationString ne "") " (" + a.locationString.trim + ")" else "" - } - } - private def kindMessage(a: Symbol, p: Symbol)(f: (String, String) => String): String = - f(a+qualify(a,p), p+qualify(p,a)) - - // Normally it's nicer to print nothing rather than '>: Nothing <: Any' all over - // the place, but here we need it for the message to make sense. - private def strictnessMessage(a: Symbol, p: Symbol) = - kindMessage(a, p)("%s's bounds%s are stricter than %s's declared bounds%s".format( - _, a.info, _, p.info match { - case tb @ TypeBounds(_, _) if tb.isEmptyBounds => " >: Nothing <: Any" - case tb => "" + tb - }) - ) - - private def varianceMessage(a: Symbol, p: Symbol) = - kindMessage(a, p)("%s is %s, but %s is declared %s".format(_, varStr(a), _, varStr(p))) - - private def arityMessage(a: Symbol, p: Symbol) = - kindMessage(a, p)("%s has %s, but %s has %s".format( - _, countElementsAsString(a.typeParams.length, "type parameter"), - _, countAsString(p.typeParams.length)) - ) - - private def buildMessage(xs: List[SymPair], f: (Symbol, Symbol) => String) = ( - if (xs.isEmpty) "" - else xs map f.tupled mkString ("\n", ", ", "") - ) - - def errorMessage(targ: Type, tparam: Symbol): String = ( - (targ+"'s type parameters do not match "+tparam+"'s expected parameters:") - + buildMessage(arity, arityMessage) - + buildMessage(variance, varianceMessage) - + buildMessage(strictness, strictnessMessage) - ) - } - val NoKindErrors = KindErrors(Nil, Nil, Nil) - - // TODO: this desperately needs to be cleaned up - // plan: split into kind inference and subkinding - // every Type has a (cached) Kind - def kindsConform(tparams: List[Symbol], targs: List[Type], pre: Type, owner: Symbol): Boolean = - checkKindBounds0(tparams, targs, pre, owner, false).isEmpty - - /** Check whether `sym1`'s variance conforms to `sym2`'s variance. - * - * If `sym2` is invariant, `sym1`'s variance is irrelevant. Otherwise they must be equal. - */ - private def variancesMatch(sym1: Symbol, sym2: Symbol) = ( - sym2.variance==0 - || sym1.variance==sym2.variance - ) - - /** Check well-kindedness of type application (assumes arities are already checked) -- @M - * - * This check is also performed when abstract type members become concrete (aka a "type alias") -- then tparams.length==1 - * (checked one type member at a time -- in that case, prefix is the name of the type alias) - * - * Type application is just like value application: it's "contravariant" in the sense that - * the type parameters of the supplied type arguments must conform to the type parameters of - * the required type parameters: - * - their bounds must be less strict - * - variances must match (here, variances are absolute, the variance of a type parameter does not influence the variance of its higher-order parameters) - * - @M TODO: are these conditions correct,sufficient&necessary? - * - * e.g. class Iterable[t, m[+x <: t]] --> the application Iterable[Int, List] is okay, since - * List's type parameter is also covariant and its bounds are weaker than <: Int - */ - def checkKindBounds0( - tparams: List[Symbol], - targs: List[Type], - pre: Type, - owner: Symbol, - explainErrors: Boolean - ): List[(Type, Symbol, KindErrors)] = { - - // instantiate type params that come from outside the abstract type we're currently checking - def transform(tp: Type, clazz: Symbol): Type = tp.asSeenFrom(pre, clazz) - - // check that the type parameters hkargs to a higher-kinded type conform to the - // expected params hkparams - def checkKindBoundsHK( - hkargs: List[Symbol], - arg: Symbol, - param: Symbol, - paramowner: Symbol, - underHKParams: List[Symbol], - withHKArgs: List[Symbol] - ): KindErrors = { - - var kindErrors: KindErrors = NoKindErrors - def bindHKParams(tp: Type) = tp.substSym(underHKParams, withHKArgs) - // @M sometimes hkargs != arg.typeParams, the symbol and the type may - // have very different type parameters - val hkparams = param.typeParams - - def kindCheck(cond: Boolean, f: KindErrors => KindErrors) { - if (!cond) - kindErrors = f(kindErrors) - } - - if (settings.debug.value) { - log("checkKindBoundsHK expected: "+ param +" with params "+ hkparams +" by definition in "+ paramowner) - log("checkKindBoundsHK supplied: "+ arg +" with params "+ hkargs +" from "+ owner) - log("checkKindBoundsHK under params: "+ underHKParams +" with args "+ withHKArgs) - } - - if (!sameLength(hkargs, hkparams)) { - // Any and Nothing are kind-overloaded - if (arg == AnyClass || arg == NothingClass) NoKindErrors - // shortcut: always set error, whether explainTypesOrNot - else return kindErrors.arityError(arg -> param) - } - else foreach2(hkargs, hkparams) { (hkarg, hkparam) => - if (hkparam.typeParams.isEmpty && hkarg.typeParams.isEmpty) { // base-case: kind * - kindCheck(variancesMatch(hkarg, hkparam), _ varianceError (hkarg -> hkparam)) - // instantiateTypeParams(tparams, targs) - // higher-order bounds, may contain references to type arguments - // substSym(hkparams, hkargs) - // these types are going to be compared as types of kind * - // - // Their arguments use different symbols, but are - // conceptually the same. Could also replace the types by - // polytypes, but can't just strip the symbols, as ordering - // is lost then. - val declaredBounds = transform(hkparam.info.instantiateTypeParams(tparams, targs).bounds, paramowner) - val declaredBoundsInst = transform(bindHKParams(declaredBounds), owner) - val argumentBounds = transform(hkarg.info.bounds, owner) - - kindCheck(declaredBoundsInst <:< argumentBounds, _ strictnessError (hkarg -> hkparam)) - - debuglog( - "checkKindBoundsHK base case: " + hkparam + - " declared bounds: " + declaredBounds + - " after instantiating earlier hkparams: " + declaredBoundsInst + "\n" + - "checkKindBoundsHK base case: "+ hkarg + - " has bounds: " + argumentBounds - ) - } - else { - debuglog("checkKindBoundsHK recursing to compare params of "+ hkparam +" with "+ hkarg) - kindErrors ++= checkKindBoundsHK( - hkarg.typeParams, - hkarg, - hkparam, - paramowner, - underHKParams ++ hkparam.typeParams, - withHKArgs ++ hkarg.typeParams - ) - } - if (!explainErrors && !kindErrors.isEmpty) - return kindErrors - } - if (explainErrors) kindErrors - else NoKindErrors - } - - if (settings.debug.value && (tparams.nonEmpty || targs.nonEmpty)) log( - "checkKindBounds0(" + tparams + ", " + targs + ", " + pre + ", " - + owner + ", " + explainErrors + ")" - ) - - flatMap2(tparams, targs) { (tparam, targ) => - // Prevent WildcardType from causing kind errors, as typevars may be higher-order - if (targ == WildcardType) Nil else { - // force symbol load for #4205 - targ.typeSymbolDirect.info - // @M must use the typeParams of the *type* targ, not of the *symbol* of targ!! - val tparamsHO = targ.typeParams - if (targ.isHigherKinded || tparam.typeParams.nonEmpty) { - // NOTE: *not* targ.typeSymbol, which normalizes - val kindErrors = checkKindBoundsHK( - tparamsHO, targ.typeSymbolDirect, tparam, - tparam.owner, tparam.typeParams, tparamsHO - ) - if (kindErrors.isEmpty) Nil else { - if (explainErrors) List((targ, tparam, kindErrors)) - // Return as soon as an error is seen if there's nothing to explain. - else return List((NoType, NoSymbol, NoKindErrors)) - } - } - else Nil - } - } - } -} \ No newline at end of file diff --git a/src/compiler/scala/reflect/internal/Mirrors.scala b/src/compiler/scala/reflect/internal/Mirrors.scala deleted file mode 100644 index e3680b14d5..0000000000 --- a/src/compiler/scala/reflect/internal/Mirrors.scala +++ /dev/null @@ -1,243 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import Flags._ - -trait Mirrors extends api.Mirrors { - self: SymbolTable => - - override type Mirror >: Null <: RootsBase - - abstract class RootsBase(rootOwner: Symbol) extends MirrorOf[Mirrors.this.type] { thisMirror => - - protected[scala] def rootLoader: LazyType - - val RootClass: ClassSymbol - val RootPackage: ModuleSymbol - val EmptyPackageClass: ClassSymbol - val EmptyPackage: ModuleSymbol - - def findMemberFromRoot(fullName: Name): Symbol = { - val segs = nme.segments(fullName.toString, fullName.isTermName) - if (segs.isEmpty) NoSymbol - else definitions.findNamedMember(segs.tail, RootClass.info member segs.head) - } - - /** Todo: organize similar to mkStatic in reflect.Base */ - private def getModuleOrClass(path: Name, len: Int): Symbol = { - val point = path lastPos('.', len - 1) - val owner = - if (point > 0) getModuleOrClass(path.toTermName, point) - else RootClass - val name = path subName (point + 1, len) - val sym = owner.info member name - val result = if (path.isTermName) sym.suchThat(_ hasFlag MODULE) else sym - if (result != NoSymbol) result - else { - if (settings.debug.value) { log(sym.info); log(sym.info.members) }//debug - mirrorMissingHook(owner, name) orElse symbolTableMissingHook(owner, name) orElse { - MissingRequirementError.notFound((if (path.isTermName) "object " else "class ")+path+" in "+thisMirror) - } - } - } - - protected def mirrorMissingHook(owner: Symbol, name: Name): Symbol = NoSymbol - - protected def symbolTableMissingHook(owner: Symbol, name: Name): Symbol = self.missingHook(owner, name) - - /** If you're looking for a class, pass a type name. - * If a module, a term name. - */ - private def getModuleOrClass(path: Name): Symbol = getModuleOrClass(path, path.length) - - override def staticClass(fullName: String): ClassSymbol = getRequiredClass(fullName) - - // todo: get rid of most creation methods and keep just staticClass/Module/Package - - def getClassByName(fullname: Name): ClassSymbol = { - var result = getModuleOrClass(fullname.toTypeName) - while (result.isAliasType) result = result.info.typeSymbol - result match { - case x: ClassSymbol => x - case _ => MissingRequirementError.notFound("class " + fullname) - } - } - - override def staticModule(fullName: String): ModuleSymbol = getRequiredModule(fullName) - - def getModule(fullname: Name): ModuleSymbol = - // [Eugene++] should be a ClassCastException instead? - getModuleOrClass(fullname.toTermName) match { - case x: ModuleSymbol => x - case _ => MissingRequirementError.notFound("object " + fullname) - } - - def getPackage(fullname: Name): ModuleSymbol = getModule(fullname) - - def getRequiredPackage(fullname: String): ModuleSymbol = - getPackage(newTermNameCached(fullname)) - - @deprecated("Use getClassByName", "2.10.0") - def getClass(fullname: Name): ClassSymbol = getClassByName(fullname) - - def getRequiredClass(fullname: String): ClassSymbol = - getClassByName(newTypeNameCached(fullname)) match { - case x: ClassSymbol => x - case _ => MissingRequirementError.notFound("class " + fullname) - } - - def getRequiredModule(fullname: String): ModuleSymbol = - getModule(newTermNameCached(fullname)) - - def erasureName[T: ClassTag] : String = { - /** We'd like the String representation to be a valid - * scala type, so we have to decode the jvm's secret language. - */ - def erasureString(clazz: Class[_]): String = { - if (clazz.isArray) "Array[" + erasureString(clazz.getComponentType) + "]" - else clazz.getName - } - erasureString(classTag[T].runtimeClass) - } - - def requiredClass[T: ClassTag] : ClassSymbol = - getRequiredClass(erasureName[T]) - - // TODO: What syntax do we think should work here? Say you have an object - // like scala.Predef. You can't say requiredModule[scala.Predef] since there's - // no accompanying Predef class, and if you say requiredModule[scala.Predef.type] - // the name found via the erasure is scala.Predef$. For now I am - // removing the trailing $, but I think that classTag should have - // a method which returns a usable name, one which doesn't expose this - // detail of the backend. - def requiredModule[T: ClassTag] : ModuleSymbol = - getRequiredModule(erasureName[T] stripSuffix "$") - - def getClassIfDefined(fullname: String): Symbol = - getClassIfDefined(newTypeName(fullname)) - - def getClassIfDefined(fullname: Name): Symbol = - wrapMissing(getClassByName(fullname.toTypeName)) - - def getModuleIfDefined(fullname: String): Symbol = - getModuleIfDefined(newTermName(fullname)) - - def getModuleIfDefined(fullname: Name): Symbol = - wrapMissing(getModule(fullname.toTermName)) - - def getPackageObject(fullname: String): ModuleSymbol = - (getModule(newTermName(fullname)).info member nme.PACKAGE) match { - case x: ModuleSymbol => x - case _ => MissingRequirementError.notFound("package object " + fullname) - } - - def getPackageObjectIfDefined(fullname: String): Symbol = { - val module = getModuleIfDefined(newTermName(fullname)) - if (module == NoSymbol) NoSymbol - else { - val packageObject = module.info member nme.PACKAGE - packageObject match { - case x: ModuleSymbol => x - case _ => NoSymbol - } - } - } - - @inline private def wrapMissing(body: => Symbol): Symbol = - try body - catch { case _: MissingRequirementError => NoSymbol } - - /** getModule2/getClass2 aren't needed at present but may be again, - * so for now they're mothballed. - */ - // def getModule2(name1: Name, name2: Name) = { - // try getModuleOrClass(name1.toTermName) - // catch { case ex1: FatalError => - // try getModuleOrClass(name2.toTermName) - // catch { case ex2: FatalError => throw ex1 } - // } - // } - // def getClass2(name1: Name, name2: Name) = { - // try { - // val result = getModuleOrClass(name1.toTypeName) - // if (result.isAliasType) getClass(name2) else result - // } - // catch { case ex1: FatalError => - // try getModuleOrClass(name2.toTypeName) - // catch { case ex2: FatalError => throw ex1 } - // } - // } - - def init() { - // Still fiddling with whether it's cleaner to do some of this setup here - // or from constructors. The latter approach tends to invite init order issues. - - EmptyPackageClass setInfo ClassInfoType(Nil, newPackageScope(EmptyPackageClass), EmptyPackageClass) - EmptyPackage setInfo EmptyPackageClass.tpe - - connectModuleToClass(EmptyPackage, EmptyPackageClass) - connectModuleToClass(RootPackage, RootClass) - - RootClass.info.decls enter EmptyPackage - RootClass.info.decls enter RootPackage - } - } - - abstract class Roots(rootOwner: Symbol) extends RootsBase(rootOwner) { thisMirror => - - // TODO - having these as objects means they elude the attempt to - // add synchronization in SynchronizedSymbols. But we should either - // flip on object overrides or find some other accomodation, because - // lazy vals are unnecessarily expensive relative to objects and it - // is very beneficial for a handful of bootstrap symbols to have - // first class identities - sealed trait WellKnownSymbol extends Symbol { - this initFlags TopLevelCreationFlags - } - // Features common to RootClass and RootPackage, the roots of all - // type and term symbols respectively. - sealed trait RootSymbol extends WellKnownSymbol { - final override def isRootSymbol = true - override def owner = rootOwner - override def typeOfThis = thisSym.tpe - } - - // This is the package _root_. The actual root cannot be referenced at - // the source level, but _root_ is essentially a function => . - final object RootPackage extends ModuleSymbol(rootOwner, NoPosition, nme.ROOTPKG) with RootSymbol { - this setInfo NullaryMethodType(RootClass.tpe) - RootClass.sourceModule = this - - override def isRootPackage = true - } - // This is , the actual root of everything except the package _root_. - // and _root_ (RootPackage and RootClass) should be the only "well known" - // symbols owned by NoSymbol. All owner chains should go through RootClass, - // although it is probable that some symbols are created as direct children - // of NoSymbol to ensure they will not be stumbled upon. (We should designate - // a better encapsulated place for that.) - final object RootClass extends PackageClassSymbol(rootOwner, NoPosition, tpnme.ROOT) with RootSymbol { - this setInfo rootLoader - - override def isRoot = true - override def isEffectiveRoot = true - override def isStatic = true - override def isNestedClass = false - override def ownerOfNewSymbols = EmptyPackageClass - } - // The empty package, which holds all top level types without given packages. - final object EmptyPackage extends ModuleSymbol(RootClass, NoPosition, nme.EMPTY_PACKAGE_NAME) with WellKnownSymbol { - override def isEmptyPackage = true - } - final object EmptyPackageClass extends PackageClassSymbol(RootClass, NoPosition, tpnme.EMPTY_PACKAGE_NAME) with WellKnownSymbol { - override def isEffectiveRoot = true - override def isEmptyPackageClass = true - } - } -} diff --git a/src/compiler/scala/reflect/internal/MissingRequirementError.scala b/src/compiler/scala/reflect/internal/MissingRequirementError.scala deleted file mode 100644 index fbbbcc1928..0000000000 --- a/src/compiler/scala/reflect/internal/MissingRequirementError.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -class MissingRequirementError private (msg: String) extends FatalError(msg) { - import MissingRequirementError.suffix - def req: String = if (msg endsWith suffix) msg dropRight suffix.length else msg -} - -object MissingRequirementError { - private val suffix = " not found." - def signal(msg: String): Nothing = throw new MissingRequirementError(msg) - def notFound(req: String): Nothing = signal(req + suffix) - def unapply(x: Throwable): Option[String] = x match { - case x: MissingRequirementError => Some(x.req) - case _ => None - } -} - - diff --git a/src/compiler/scala/reflect/internal/Names.scala b/src/compiler/scala/reflect/internal/Names.scala deleted file mode 100644 index 18671871ae..0000000000 --- a/src/compiler/scala/reflect/internal/Names.scala +++ /dev/null @@ -1,527 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import scala.io.Codec -import java.security.MessageDigest -import language.implicitConversions - -/** The class Names ... - * - * @author Martin Odersky - * @version 1.0, 05/02/2005 - */ -trait Names extends api.Names { - implicit def promoteTermNamesAsNecessary(name: Name): TermName = name.toTermName - -// Operations ------------------------------------------------------------- - - private final val HASH_SIZE = 0x8000 - private final val HASH_MASK = 0x7FFF - private final val NAME_SIZE = 0x20000 - - final val nameDebug = false - - /** Memory to store all names sequentially. */ - var chrs: Array[Char] = new Array[Char](NAME_SIZE) - private var nc = 0 - - /** Hashtable for finding term names quickly. */ - private val termHashtable = new Array[TermName](HASH_SIZE) - - /** Hashtable for finding type names quickly. */ - private val typeHashtable = new Array[TypeName](HASH_SIZE) - - /** The hashcode of a name. */ - private def hashValue(cs: Array[Char], offset: Int, len: Int): Int = - if (len > 0) - (len * (41 * 41 * 41) + - cs(offset) * (41 * 41) + - cs(offset + len - 1) * 41 + - cs(offset + (len >> 1))) - else 0; - - /** Is (the ASCII representation of) name at given index equal to - * cs[offset..offset+len-1]? - */ - private def equals(index: Int, cs: Array[Char], offset: Int, len: Int): Boolean = { - var i = 0 - while ((i < len) && (chrs(index + i) == cs(offset + i))) - i += 1; - i == len - } - - /** Enter characters into chrs array. */ - private def enterChars(cs: Array[Char], offset: Int, len: Int) { - var i = 0 - while (i < len) { - if (nc + i == chrs.length) { - val newchrs = new Array[Char](chrs.length * 2) - compat.Platform.arraycopy(chrs, 0, newchrs, 0, chrs.length) - chrs = newchrs - } - chrs(nc + i) = cs(offset + i) - i += 1 - } - if (len == 0) nc += 1 - else nc = nc + len - } - - /** Create a term name from the characters in cs[offset..offset+len-1]. */ - def newTermName(cs: Array[Char], offset: Int, len: Int): TermName = - newTermName(cs, offset, len, cachedString = null) - - def newTermName(cs: Array[Char]): TermName = newTermName(cs, 0, cs.length) - def newTypeName(cs: Array[Char]): TypeName = newTypeName(cs, 0, cs.length) - - /** Create a term name from the characters in cs[offset..offset+len-1]. - * TODO - have a mode where name validation is performed at creation time - * (e.g. if a name has the string "$class" in it, then fail if that - * string is not at the very end.) - */ - protected def newTermName(cs: Array[Char], offset: Int, len: Int, cachedString: String): TermName = { - val h = hashValue(cs, offset, len) & HASH_MASK - var n = termHashtable(h) - while ((n ne null) && (n.length != len || !equals(n.start, cs, offset, len))) - n = n.next - - if (n ne null) n - else { - // The logic order here is future-proofing against the possibility - // that name.toString will become an eager val, in which case the call - // to enterChars cannot follow the construction of the TermName. - val ncStart = nc - enterChars(cs, offset, len) - if (cachedString ne null) new TermName_S(ncStart, len, h, cachedString) - else new TermName_R(ncStart, len, h) - } - } - protected def newTypeName(cs: Array[Char], offset: Int, len: Int, cachedString: String): TypeName = - newTermName(cs, offset, len, cachedString).toTypeName - - /** Create a term name from string. */ - def newTermName(s: String): TermName = newTermName(s.toCharArray(), 0, s.length(), null) - - /** Create a type name from string. */ - def newTypeName(s: String): TypeName = newTermName(s).toTypeName - - /** Create a term name from the UTF8 encoded bytes in bs[offset..offset+len-1]. */ - def newTermName(bs: Array[Byte], offset: Int, len: Int): TermName = { - val chars = Codec.fromUTF8(bs, offset, len) - newTermName(chars, 0, chars.length) - } - - def newTermNameCached(s: String): TermName = - newTermName(s.toCharArray(), 0, s.length(), cachedString = s) - - def newTypeNameCached(s: String): TypeName = - newTypeName(s.toCharArray(), 0, s.length(), cachedString = s) - - /** Create a type name from the characters in cs[offset..offset+len-1]. */ - def newTypeName(cs: Array[Char], offset: Int, len: Int): TypeName = - newTermName(cs, offset, len, cachedString = null).toTypeName - - /** Create a type name from the UTF8 encoded bytes in bs[offset..offset+len-1]. */ - def newTypeName(bs: Array[Byte], offset: Int, len: Int): TypeName = - newTermName(bs, offset, len).toTypeName - - def nameChars: Array[Char] = chrs - @deprecated("", "2.9.0") def view(s: String): TermName = newTermName(s) - -// Classes ---------------------------------------------------------------------- - - /** The name class. - * TODO - resolve schizophrenia regarding whether to treat Names as Strings - * or Strings as Names. Give names the key functions the absence of which - * make people want Strings all the time. - */ - sealed abstract class Name(protected val index: Int, protected val len: Int) extends NameApi with Function1[Int, Char] { - type ThisNameType >: Null <: Name - protected[this] def thisName: ThisNameType - - /** Index into name table */ - def start: Int = index - - /** The next name in the same hash bucket. */ - def next: ThisNameType - - /** The length of this name. */ - final def length: Int = len - final def isEmpty = length == 0 - final def nonEmpty = !isEmpty - - def nameKind: String - def isTermName: Boolean - def isTypeName: Boolean - def toTermName: TermName - def toTypeName: TypeName - def companionName: Name - def bothNames: List[Name] = List(toTermName, toTypeName) - - /** Return the subname with characters from from to to-1. */ - def subName(from: Int, to: Int): ThisNameType - - /** Return a new name of the same variety. */ - def newName(str: String): ThisNameType - - /** Return a new name based on string transformation. */ - def mapName(f: String => String): ThisNameType = newName(f(toString)) - - /** Copy bytes of this name to buffer cs, starting at position `offset`. */ - final def copyChars(cs: Array[Char], offset: Int) = - compat.Platform.arraycopy(chrs, index, cs, offset, len) - - /** @return the ascii representation of this name */ - final def toChars: Array[Char] = { - val cs = new Array[Char](len) - copyChars(cs, 0) - cs - } - - /** Write to UTF8 representation of this name to given character array. - * Start copying to index `to`. Return index of next free byte in array. - * Array must have enough remaining space for all bytes - * (i.e. maximally 3*length bytes). - */ - final def copyUTF8(bs: Array[Byte], offset: Int): Int = { - val bytes = Codec.toUTF8(chrs, index, len) - compat.Platform.arraycopy(bytes, 0, bs, offset, bytes.length) - offset + bytes.length - } - - /** @return the hash value of this name */ - final override def hashCode(): Int = index - - // Presently disabled. - // override def equals(other: Any) = paranoidEquals(other) - private def paranoidEquals(other: Any): Boolean = { - val cmp = this eq other.asInstanceOf[AnyRef] - if (cmp || !nameDebug) - return cmp - - other match { - case x: String => - Console.println("Compared " + debugString + " and String '" + x + "'") - case x: Name => - if (this.isTermName != x.isTermName) { - val panic = this.toTermName == x.toTermName - Console.println("Compared '%s' and '%s', one term, one type.%s".format(this, x, - if (panic) " And they contain the same name string!" - else "" - )) - } - case _ => - } - false - } - - /** @return the i'th Char of this name */ - final def apply(i: Int): Char = chrs(index + i) - - /** @return the index of first occurrence of char c in this name, length if not found */ - final def pos(c: Char): Int = pos(c, 0) - - /** @return the index of first occurrence of char c in this name, length if not found */ - final def pos(s: String): Int = pos(s, 0) - - /** Returns the index of the first occurrence of character c in - * this name from start, length if not found. - * - * @param c the character - * @param start ... - * @return the index of the first occurrence of c - */ - final def pos(c: Char, start: Int): Int = { - var i = start - while (i < len && chrs(index + i) != c) i += 1 - i - } - - /** Returns the index of the first occurrence of nonempty string s - * in this name from start, length if not found. - * - * @param s the string - * @param start ... - * @return the index of the first occurrence of s - */ - final def pos(s: String, start: Int): Int = { - var i = pos(s.charAt(0), start) - while (i + s.length() <= len) { - var j = 1 - while (s.charAt(j) == chrs(index + i + j)) { - j += 1 - if (j == s.length()) return i - } - i = pos(s.charAt(0), i + 1) - } - len - } - - /** Returns the index of last occurrence of char c in this - * name, -1 if not found. - * - * @param c the character - * @return the index of the last occurrence of c - */ - final def lastPos(c: Char): Int = lastPos(c, len - 1) - - final def lastPos(s: String): Int = lastPos(s, len - s.length) - - /** Returns the index of the last occurrence of char c in this - * name from start, -1 if not found. - * - * @param c the character - * @param start ... - * @return the index of the last occurrence of c - */ - final def lastPos(c: Char, start: Int): Int = { - var i = start - while (i >= 0 && chrs(index + i) != c) i -= 1 - i - } - - /** Returns the index of the last occurrence of string s in this - * name from start, -1 if not found. - * - * @param s the string - * @param start ... - * @return the index of the last occurrence of s - */ - final def lastPos(s: String, start: Int): Int = { - var i = lastPos(s.charAt(0), start) - while (i >= 0) { - var j = 1; - while (s.charAt(j) == chrs(index + i + j)) { - j += 1 - if (j == s.length()) return i; - } - i = lastPos(s.charAt(0), i - 1) - } - -s.length() - } - - /** Does this name start with prefix? */ - final def startsWith(prefix: Name): Boolean = startsWith(prefix, 0) - - /** Does this name start with prefix at given start index? */ - final def startsWith(prefix: Name, start: Int): Boolean = { - var i = 0 - while (i < prefix.length && start + i < len && - chrs(index + start + i) == chrs(prefix.start + i)) - i += 1; - i == prefix.length - } - - /** Does this name end with suffix? */ - final def endsWith(suffix: Name): Boolean = endsWith(suffix, len) - - /** Does this name end with suffix just before given end index? */ - final def endsWith(suffix: Name, end: Int): Boolean = { - var i = 1 - while (i <= suffix.length && i <= end && - chrs(index + end - i) == chrs(suffix.start + suffix.length - i)) - i += 1; - i > suffix.length - } - - final def containsName(subname: String): Boolean = containsName(newTermName(subname)) - final def containsName(subname: Name): Boolean = { - var start = 0 - val last = len - subname.length - while (start <= last && !startsWith(subname, start)) start += 1 - start <= last - } - final def containsChar(ch: Char): Boolean = { - var i = index - val max = index + len - while (i < max) { - if (chrs(i) == ch) - return true - i += 1 - } - false - } - - /** Some thoroughly self-explanatory convenience functions. They - * assume that what they're being asked to do is known to be valid. - */ - final def startChar: Char = apply(0) - final def endChar: Char = apply(len - 1) - final def startsWith(char: Char): Boolean = len > 0 && startChar == char - final def startsWith(name: String): Boolean = startsWith(newTermName(name)) - final def endsWith(char: Char): Boolean = len > 0 && endChar == char - final def endsWith(name: String): Boolean = endsWith(newTermName(name)) - - def dropRight(n: Int): ThisNameType = subName(0, len - n) - def drop(n: Int): ThisNameType = subName(n, len) - def stripSuffix(suffix: Name): ThisNameType = - if (this endsWith suffix) dropRight(suffix.length) else thisName - - def indexOf(ch: Char) = { - val idx = pos(ch) - if (idx == length) -1 else idx - } - def indexOf(ch: Char, fromIndex: Int) = { - val idx = pos(ch, fromIndex) - if (idx == length) -1 else idx - } - def lastIndexOf(ch: Char) = lastPos(ch) - def lastIndexOf(ch: Char, fromIndex: Int) = lastPos(ch, fromIndex) - - /** Replace all occurrences of `from` by `to` in - * name; result is always a term name. - */ - def replace(from: Char, to: Char): Name = { - val cs = new Array[Char](len) - var i = 0 - while (i < len) { - val ch = this(i) - cs(i) = if (ch == from) to else ch - i += 1 - } - newTermName(cs, 0, len) - } - - /** TODO - reconcile/fix that encode returns a Name but - * decode returns a String. - */ - - /** !!! Duplicative but consistently named. - */ - def decoded: String = decode - def encoded: String = "" + encode - // def decodedName: ThisNameType = newName(decoded) - def encodedName: ThisNameType = encode - - /** Replace operator symbols by corresponding \$op_name. */ - def encode: ThisNameType = { - val str = toString - val res = NameTransformer.encode(str) - if (res == str) thisName else newName(res) - } - - /** Replace \$op_name by corresponding operator symbol. */ - def decode: String = { - if (this containsChar '$') { - val str = toString - val res = NameTransformer.decode(str) - if (res == str) str - else res - } - else toString - } - - /** TODO - find some efficiency. */ - def append(ch: Char) = newName("" + this + ch) - def append(suffix: String) = newName("" + this + suffix) - def append(suffix: Name) = newName("" + this + suffix) - def prepend(ch: Char) = newName("" + ch + this) - def prepend(prefix: String) = newName("" + prefix + this) - def prepend(prefix: Name) = newName("" + prefix + this) - - def decodedName: ThisNameType = newName(decode) - def isOperatorName: Boolean = decode != toString - def longString: String = nameKind + " " + decode - def debugString = { val s = decode ; if (isTypeName) s + "!" else s } - } - - implicit val NameTag = ClassTag[Name](classOf[Name]) - - /** A name that contains no operator chars nor dollar signs. - * TODO - see if it's any faster to do something along these lines. - * Cute: now that exhaustivity kind of works, the mere presence of - * this trait causes TermName and TypeName to stop being exhaustive. - * Commented out. - */ - // trait AlphaNumName extends Name { - // final override def encode = thisName - // final override def decodedName = thisName - // final override def decode = toString - // final override def isOperatorName = false - // } - - /** TermName_S and TypeName_S have fields containing the string version of the name. - * TermName_R and TypeName_R recreate it each time toString is called. - */ - private class TermName_S(index0: Int, len0: Int, hash: Int, override val toString: String) extends TermName(index0, len0, hash) { - protected def createCompanionName(h: Int): TypeName = new TypeName_S(index, len, h, toString) - override def newName(str: String): TermName = newTermNameCached(str) - } - private class TypeName_S(index0: Int, len0: Int, hash: Int, override val toString: String) extends TypeName(index0, len0, hash) { - protected def createCompanionName(h: Int): TermName = new TermName_S(index, len, h, toString) - override def newName(str: String): TypeName = newTypeNameCached(str) - } - - private class TermName_R(index0: Int, len0: Int, hash: Int) extends TermName(index0, len0, hash) { - protected def createCompanionName(h: Int): TypeName = new TypeName_R(index, len, h) - override def toString = new String(chrs, index, len) - } - - private class TypeName_R(index0: Int, len0: Int, hash: Int) extends TypeName(index0, len0, hash) { - protected def createCompanionName(h: Int): TermName = new TermName_R(index, len, h) - override def toString = new String(chrs, index, len) - } - - sealed abstract class TermName(index0: Int, len0: Int, hash: Int) extends Name(index0, len0) { - type ThisNameType = TermName - protected[this] def thisName: TermName = this - - var next: TermName = termHashtable(hash) - termHashtable(hash) = this - def isTermName: Boolean = true - def isTypeName: Boolean = false - def toTermName: TermName = this - def toTypeName: TypeName = { - val h = hashValue(chrs, index, len) & HASH_MASK - var n = typeHashtable(h) - while ((n ne null) && n.start != index) - n = n.next - - if (n ne null) n - else createCompanionName(h) - } - def newName(str: String): TermName = newTermName(str) - def companionName: TypeName = toTypeName - def subName(from: Int, to: Int): TermName = - newTermName(chrs, start + from, to - from) - - def nameKind = "term" - protected def createCompanionName(h: Int): TypeName - } - - implicit val TermNameTag = ClassTag[TermName](classOf[TermName]) - - sealed abstract class TypeName(index0: Int, len0: Int, hash: Int) extends Name(index0, len0) { - type ThisNameType = TypeName - protected[this] def thisName: TypeName = this - - var next: TypeName = typeHashtable(hash) - typeHashtable(hash) = this - def isTermName: Boolean = false - def isTypeName: Boolean = true - def toTermName: TermName = { - val h = hashValue(chrs, index, len) & HASH_MASK - var n = termHashtable(h) - while ((n ne null) && n.start != index) - n = n.next - - if (n ne null) n - else createCompanionName(h) - } - def toTypeName: TypeName = this - def newName(str: String): TypeName = newTypeName(str) - def companionName: TermName = toTermName - def subName(from: Int, to: Int): TypeName = - newTypeName(chrs, start + from, to - from) - - def nameKind = "type" - override def decode = if (nameDebug) super.decode + "!" else super.decode - protected def createCompanionName(h: Int): TermName - } - - implicit val TypeNameTag = ClassTag[TypeName](classOf[TypeName]) -} diff --git a/src/compiler/scala/reflect/internal/Phase.scala b/src/compiler/scala/reflect/internal/Phase.scala deleted file mode 100644 index 68dc5ce783..0000000000 --- a/src/compiler/scala/reflect/internal/Phase.scala +++ /dev/null @@ -1,66 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -abstract class Phase(val prev: Phase) { - if ((prev ne null) && (prev ne NoPhase)) - prev.nx = this - - type Id = Int - val id: Id = if (prev eq null) 0 else prev.id + 1 - - /** New flags visible after this phase has completed */ - def nextFlags: Long = 0l - - /** New flags visible once this phase has started */ - def newFlags: Long = 0l - - val fmask = ( - if (prev eq null) Flags.InitialFlags - else prev.flagMask | prev.nextFlags | newFlags - ) - def flagMask: Long = fmask - - private var nx: Phase = this - - def next: Phase = nx - def hasNext = next != this - def iterator = Iterator.iterate(this)(_.next) takeWhile (p => p.next != p) - - def name: String - def description: String = name - // Will running with -Ycheck:name work? - def checkable: Boolean = true - def specialized: Boolean = false - def erasedTypes: Boolean = false - def flatClasses: Boolean = false - def refChecked: Boolean = false - - /** This is used only in unsafeTypeParams, and at this writing is - * overridden to false in parser, namer, typer, and erasure. (And NoPhase.) - */ - def keepsTypeParams = true - def run(): Unit - - override def toString() = name - override def hashCode = id.## + name.## - override def equals(other: Any) = other match { - case x: Phase => id == x.id && name == x.name - case _ => false - } -} - -object NoPhase extends Phase(null) { - def name = "" - override def keepsTypeParams = false - def run() { throw new Error("NoPhase.run") } -} - -object SomePhase extends Phase(NoPhase) { - def name = "" - def run() { throw new Error("SomePhase.run") } -} diff --git a/src/compiler/scala/reflect/internal/Positions.scala b/src/compiler/scala/reflect/internal/Positions.scala deleted file mode 100644 index 6ae9b40fcb..0000000000 --- a/src/compiler/scala/reflect/internal/Positions.scala +++ /dev/null @@ -1,63 +0,0 @@ -package scala.reflect -package internal - -trait Positions extends api.Positions { self: SymbolTable => - - type Position = scala.reflect.internal.util.Position - val NoPosition = scala.reflect.internal.util.NoPosition - implicit val PositionTag = ClassTag[Position](classOf[Position]) - - /** A position that wraps a set of trees. - * The point of the wrapping position is the point of the default position. - * If some of the trees are ranges, returns a range position enclosing all ranges - * Otherwise returns default position. - */ - def wrappingPos(default: Position, trees: List[Tree]): Position = default - - /** A position that wraps the non-empty set of trees. - * The point of the wrapping position is the point of the first trees' position. - * If all some the trees are non-synthetic, returns a range position enclosing the non-synthetic trees - * Otherwise returns a synthetic offset position to point. - */ - def wrappingPos(trees: List[Tree]): Position = trees.head.pos - - /** Ensure that given tree has no positions that overlap with - * any of the positions of `others`. This is done by - * shortening the range or assigning TransparentPositions - * to some of the nodes in `tree`. - */ - def ensureNonOverlapping(tree: Tree, others: List[Tree]) {} - - trait PosAssigner extends Traverser { - var pos: Position - } - protected[this] lazy val posAssigner: PosAssigner = new DefaultPosAssigner - - protected class DefaultPosAssigner extends PosAssigner { - var pos: Position = _ - override def traverse(t: Tree) { - if (t eq EmptyTree) () - else if (t.pos == NoPosition) { - t.setPos(pos) - super.traverse(t) // TODO: bug? shouldn't the traverse be outside of the if? - // @PP: it's pruning whenever it encounters a node with a - // position, which I interpret to mean that (in the author's - // mind at least) either the children of a positioned node will - // already be positioned, or the children of a positioned node - // do not merit positioning. - // - // Whatever the author's rationale, it does seem like a bad idea - // to press on through a positioned node to find unpositioned - // children beneath it and then to assign whatever happens to - // be in `pos` to such nodes. There are supposed to be some - // position invariants which I can't imagine surviving that. - } - } - } - - def atPos[T <: Tree](pos: Position)(tree: T): T = { - posAssigner.pos = pos - posAssigner.traverse(tree) - tree - } -} \ No newline at end of file diff --git a/src/compiler/scala/reflect/internal/Required.scala b/src/compiler/scala/reflect/internal/Required.scala deleted file mode 100644 index abbe8fbfb7..0000000000 --- a/src/compiler/scala/reflect/internal/Required.scala +++ /dev/null @@ -1,17 +0,0 @@ -package scala.reflect -package internal - -import settings.MutableSettings - -trait Required { self: SymbolTable => - - type AbstractFileType >: Null <: AbstractFileApi - - def picklerPhase: Phase - - def settings: MutableSettings - - def forInteractive: Boolean - - def forScaladoc: Boolean -} diff --git a/src/compiler/scala/reflect/internal/Scopes.scala b/src/compiler/scala/reflect/internal/Scopes.scala deleted file mode 100644 index ceacd2afb0..0000000000 --- a/src/compiler/scala/reflect/internal/Scopes.scala +++ /dev/null @@ -1,359 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -trait Scopes extends api.Scopes { self: SymbolTable => - - class ScopeEntry(val sym: Symbol, val owner: Scope) { - /** the next entry in the hash bucket - */ - var tail: ScopeEntry = null - - /** the next entry in this scope - */ - var next: ScopeEntry = null - - override def hashCode(): Int = sym.name.start - override def toString(): String = sym.toString() - } - - /** - * @param sym ... - * @param owner ... - * @return ... - */ - private def newScopeEntry(sym: Symbol, owner: Scope): ScopeEntry = { - val e = new ScopeEntry(sym, owner) - e.next = owner.elems - owner.elems = e - e - } - - object Scope { - def unapplySeq(decls: Scope): Some[Seq[Symbol]] = Some(decls.toList) - } - - /** Note: constructor is protected to force everyone to use the factory methods newScope or newNestedScope instead. - * This is necessary because when run from reflection every scope needs to have a - * SynchronizedScope as mixin. - */ - class Scope protected[Scopes] (initElems: ScopeEntry = null) extends Iterable[Symbol] { - - protected[Scopes] def this(base: Scope) = { - this(base.elems) - nestinglevel = base.nestinglevel + 1 - } - - private[scala] var elems: ScopeEntry = initElems - - /** The number of times this scope is nested in another - */ - private var nestinglevel = 0 - - /** the hash table - */ - private var hashtable: Array[ScopeEntry] = null - - /** a cache for all elements, to be used by symbol iterator. - */ - private var elemsCache: List[Symbol] = null - - /** size and mask of hash tables - * todo: make hashtables grow? - */ - private val HASHSIZE = 0x80 - private val HASHMASK = 0x7f - - /** the threshold number of entries from which a hashtable is constructed. - */ - private val MIN_HASH = 8 - - if (size >= MIN_HASH) createHash() - - /** Returns a new scope with the same content as this one. */ - def cloneScope: Scope = newScopeWith(this.toList: _*) - - /** is the scope empty? */ - override def isEmpty: Boolean = elems eq null - - /** the number of entries in this scope */ - override def size: Int = { - var s = 0 - var e = elems - while (e ne null) { - s += 1 - e = e.next - } - s - } - - /** enter a scope entry - * - * @param e ... - */ - protected def enter(e: ScopeEntry) { - elemsCache = null - if (hashtable ne null) - enterInHash(e) - else if (size >= MIN_HASH) - createHash() - } - - private def enterInHash(e: ScopeEntry): Unit = { - val i = e.sym.name.start & HASHMASK - e.tail = hashtable(i) - hashtable(i) = e - } - - /** enter a symbol - * - * @param sym ... - */ - def enter[T <: Symbol](sym: T): T = { enter(newScopeEntry(sym, this)); sym } - - /** enter a symbol, asserting that no symbol with same name exists in scope - * - * @param sym ... - */ - def enterUnique(sym: Symbol) { - assert(lookup(sym.name) == NoSymbol, (sym.fullLocationString, lookup(sym.name).fullLocationString)) - enter(sym) - } - - private def createHash() { - hashtable = new Array[ScopeEntry](HASHSIZE) - enterAllInHash(elems) - } - - private def enterAllInHash(e: ScopeEntry, n: Int = 0) { - if (e ne null) { - if (n < maxRecursions) { - enterAllInHash(e.next, n + 1) - enterInHash(e) - } else { - var entries: List[ScopeEntry] = List() - var ee = e - while (ee ne null) { - entries = ee :: entries - ee = ee.next - } - entries foreach enterInHash - } - } - } - - def rehash(sym: Symbol, newname: Name) { - if (hashtable ne null) { - val index = sym.name.start & HASHMASK - var e1 = hashtable(index) - var e: ScopeEntry = null - if (e1 != null) { - if (e1.sym == sym) { - hashtable(index) = e1.tail - e = e1 - } else { - while (e1.tail != null && e1.tail.sym != sym) e1 = e1.tail - if (e1.tail != null) { - e = e1.tail - e1.tail = e.tail - } - } - } - if (e != null) { - val newindex = newname.start & HASHMASK - e.tail = hashtable(newindex) - hashtable(newindex) = e - } - } - } - - /** remove entry - * - * @param e ... - */ - def unlink(e: ScopeEntry) { - if (elems == e) { - elems = e.next - } else { - var e1 = elems - while (e1.next != e) e1 = e1.next - e1.next = e.next - } - if (hashtable ne null) { - val index = e.sym.name.start & HASHMASK - var e1 = hashtable(index) - if (e1 == e) { - hashtable(index) = e.tail - } else { - while (e1.tail != e) e1 = e1.tail; - e1.tail = e.tail - } - } - elemsCache = null - } - - /** remove symbol */ - def unlink(sym: Symbol) { - var e = lookupEntry(sym.name) - while (e ne null) { - if (e.sym == sym) unlink(e); - e = lookupNextEntry(e) - } - } - - /** lookup a symbol - * - * @param name ... - * @return ... - */ - def lookup(name: Name): Symbol = { - val e = lookupEntry(name) - if (e eq null) NoSymbol else e.sym - } - - /** Returns an iterator yielding every symbol with given name in this scope. - */ - def lookupAll(name: Name): Iterator[Symbol] = new Iterator[Symbol] { - var e = lookupEntry(name) - def hasNext: Boolean = e ne null - def next(): Symbol = { val r = e.sym; e = lookupNextEntry(e); r } - } - - /** lookup a symbol entry matching given name. - * @note from Martin: I believe this is a hotspot or will be one - * in future versions of the type system. I have reverted the previous - * change to use iterators as too costly. - */ - def lookupEntry(name: Name): ScopeEntry = { - var e: ScopeEntry = null - if (hashtable ne null) { - e = hashtable(name.start & HASHMASK) - while ((e ne null) && e.sym.name != name) { - e = e.tail - } - } else { - e = elems - while ((e ne null) && e.sym.name != name) { - e = e.next - } - } - e - } - - /** lookup next entry with same name as this one - * @note from Martin: I believe this is a hotspot or will be one - * in future versions of the type system. I have reverted the previous - * change to use iterators as too costly. - */ - def lookupNextEntry(entry: ScopeEntry): ScopeEntry = { - var e = entry - if (hashtable ne null) - do { e = e.tail } while ((e ne null) && e.sym.name != entry.sym.name) - else - do { e = e.next } while ((e ne null) && e.sym.name != entry.sym.name); - e - } - - /** Return all symbols as a list in the order they were entered in this scope. - */ - override def toList: List[Symbol] = { - if (elemsCache eq null) { - elemsCache = Nil - var e = elems - while ((e ne null) && e.owner == this) { - elemsCache = e.sym :: elemsCache - e = e.next - } - } - elemsCache - } - - /** Return the nesting level of this scope, i.e. the number of times this scope - * was nested in another */ - def nestingLevel = nestinglevel - - /** Return all symbols as an iterator in the order they were entered in this scope. - */ - def iterator: Iterator[Symbol] = toList.iterator - -/* - /** Does this scope contain an entry for `sym`? - */ - def contains(sym: Symbol): Boolean = lookupAll(sym.name) contains sym - - /** A scope that contains all symbols of this scope and that also contains `sym`. - */ - def +(sym: Symbol): Scope = - if (contains(sym)) this - else { - val result = cloneScope - result enter sym - result - } - - /** A scope that contains all symbols of this scope except `sym`. - */ - def -(sym: Symbol): Scope = - if (!contains(sym)) this - else { - val result = cloneScope - result unlink sym - result - } -*/ - override def foreach[U](p: Symbol => U): Unit = toList foreach p - - override def filter(p: Symbol => Boolean): Scope = - if (!(toList forall p)) newScopeWith(toList filter p: _*) else this - - override def mkString(start: String, sep: String, end: String) = - toList.map(_.defString).mkString(start, sep, end) - - override def toString(): String = mkString("Scope{\n ", ";\n ", "\n}") - - } - - implicit val ScopeTag = ClassTag[Scope](classOf[Scope]) - - /** Create a new scope */ - def newScope: Scope = new Scope() - - /** Create a new scope nested in another one with which it shares its elements */ - def newNestedScope(outer: Scope): Scope = new Scope(outer) - - /** Create a new scope with given initial elements */ - def newScopeWith(elems: Symbol*): Scope = { - val scope = newScope - elems foreach scope.enter - scope - } - - /** Create new scope for the members of package `pkg` */ - def newPackageScope(pkgClass: Symbol): Scope = newScope - - /** Transform scope of members of `owner` using operation `op` - * This is overridden by the reflective compiler to avoid creating new scopes for packages - */ - def scopeTransform(owner: Symbol)(op: => Scope): Scope = op - - - /** The empty scope (immutable). - */ - object EmptyScope extends Scope { - override def enter(e: ScopeEntry) { - abort("EmptyScope.enter") - } - } - - /** The error scope. - */ - class ErrorScope(owner: Symbol) extends Scope - - private final val maxRecursions = 1000 - -} - diff --git a/src/compiler/scala/reflect/internal/StdAttachments.scala b/src/compiler/scala/reflect/internal/StdAttachments.scala deleted file mode 100644 index 4ea9b27da9..0000000000 --- a/src/compiler/scala/reflect/internal/StdAttachments.scala +++ /dev/null @@ -1,12 +0,0 @@ -package scala.reflect -package internal - -trait StdAttachments { - self: SymbolTable => - - case object BackquotedIdentifierAttachment - - case class CompoundTypeTreeOriginalAttachment(parents: List[Tree], stats: List[Tree]) - - case class MacroExpansionAttachment(original: Tree) -} \ No newline at end of file diff --git a/src/compiler/scala/reflect/internal/StdCreators.scala b/src/compiler/scala/reflect/internal/StdCreators.scala deleted file mode 100644 index 3e6b7c1ab4..0000000000 --- a/src/compiler/scala/reflect/internal/StdCreators.scala +++ /dev/null @@ -1,21 +0,0 @@ -package scala.reflect -package internal - -import scala.reflect.base.{TreeCreator, TypeCreator} -import scala.reflect.base.{Universe => BaseUniverse} - -trait StdCreators { - self: SymbolTable => - - case class FixedMirrorTreeCreator(mirror: MirrorOf[StdCreators.this.type], tree: Tree) extends TreeCreator { - def apply[U <: BaseUniverse with Singleton](m: MirrorOf[U]): U # Tree = - if (m eq mirror) tree.asInstanceOf[U # Tree] - else throw new IllegalArgumentException(s"Expr defined in $mirror cannot be migrated to other mirrors.") - } - - case class FixedMirrorTypeCreator(mirror: MirrorOf[StdCreators.this.type], tpe: Type) extends TypeCreator { - def apply[U <: BaseUniverse with Singleton](m: MirrorOf[U]): U # Type = - if (m eq mirror) tpe.asInstanceOf[U # Type] - else throw new IllegalArgumentException(s"Type tag defined in $mirror cannot be migrated to other mirrors.") - } -} \ No newline at end of file diff --git a/src/compiler/scala/reflect/internal/StdNames.scala b/src/compiler/scala/reflect/internal/StdNames.scala deleted file mode 100644 index 6f68b8f63a..0000000000 --- a/src/compiler/scala/reflect/internal/StdNames.scala +++ /dev/null @@ -1,1218 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import java.security.MessageDigest -import Chars.isOperatorPart -import annotation.switch -import language.implicitConversions -import scala.collection.immutable -import scala.io.Codec - -trait StdNames { - self: SymbolTable => - - def encode(str: String): TermName = newTermNameCached(NameTransformer.encode(str)) - - implicit def lowerTermNames(n: TermName): String = n.toString - - /** Tensions: would like the keywords to be the very first names entered into the names - * storage so their ids count from 0, which simplifies the parser. Switched to abstract - * classes to avoid all the indirection which is generated with implementation-containing - * traits. Since all these classes use eager vals, that means the constructor with the - * keywords must run first. If it's the top in the superclass chain, then CommonNames - * must inherit from it, which means TypeNames would inherit keywords as well. - * - * Solution: Keywords extends CommonNames and uses early defs to beat the - * CommonNames constructor out of the starting gate. This is its builder. - */ - private class KeywordSetBuilder { - private var kws: Set[TermName] = Set() - def apply(s: String): TermName = { - val result = newTermNameCached(s) - kws = kws + result - result - } - def result: Set[TermName] = { - val result = kws - kws = null - result - } - } - - private final object compactify extends (String => String) { - val md5 = MessageDigest.getInstance("MD5") - - /** - * COMPACTIFY - * - * The hashed name has the form (prefix + marker + md5 + marker + suffix), where - * - prefix/suffix.length = MaxNameLength / 4 - * - md5.length = 32 - * - * We obtain the formula: - * - * FileNameLength = 2*(MaxNameLength / 4) + 2.marker.length + 32 + 6 - * - * (+6 for ".class"). MaxNameLength can therefore be computed as follows: - */ - val marker = "$$$$" - val MaxNameLength = math.min( - settings.maxClassfileName.value - 6, - 2 * (settings.maxClassfileName.value - 6 - 2*marker.length - 32) - ) - def toMD5(s: String, edge: Int): String = { - val prefix = s take edge - val suffix = s takeRight edge - - val cs = s.toArray - val bytes = Codec toUTF8 cs - md5 update bytes - val md5chars = (md5.digest() map (b => (b & 0xFF).toHexString)).mkString - - prefix + marker + md5chars + marker + suffix - } - def apply(s: String): String = ( - if (s.length <= MaxNameLength) s - else toMD5(s, MaxNameLength / 4) - ) - } - - abstract class CommonNames extends NamesApi { - type NameType >: Null <: Name - protected implicit def createNameType(name: String): NameType - - def flattenedName(segments: Name*): NameType = - compactify(segments mkString NAME_JOIN_STRING) - - val MODULE_SUFFIX_STRING: String = NameTransformer.MODULE_SUFFIX_STRING - val NAME_JOIN_STRING: String = NameTransformer.NAME_JOIN_STRING - val SINGLETON_SUFFIX: String = ".type" - - val ANON_CLASS_NAME: NameType = "$anon" - val ANON_FUN_NAME: NameType = "$anonfun" - val EMPTY: NameType = "" - val EMPTY_PACKAGE_NAME: NameType = "" - val IMPL_CLASS_SUFFIX = "$class" - val IMPORT: NameType = "" - val MODULE_SUFFIX_NAME: NameType = MODULE_SUFFIX_STRING - val MODULE_VAR_SUFFIX: NameType = "$module" - val NAME_JOIN_NAME: NameType = NAME_JOIN_STRING - val PACKAGE: NameType = "package" - val ROOT: NameType = "" - val SPECIALIZED_SUFFIX: NameType = "$sp" - - // value types (and AnyRef) are all used as terms as well - // as (at least) arguments to the @specialize annotation. - final val Boolean: NameType = "Boolean" - final val Byte: NameType = "Byte" - final val Char: NameType = "Char" - final val Double: NameType = "Double" - final val Float: NameType = "Float" - final val Int: NameType = "Int" - final val Long: NameType = "Long" - final val Short: NameType = "Short" - final val Unit: NameType = "Unit" - - final val ScalaValueNames: scala.List[NameType] = - scala.List(Byte, Char, Short, Int, Long, Float, Double, Boolean, Unit) - - // some types whose companions we utilize - final val AnyRef: NameType = "AnyRef" - final val Array: NameType = "Array" - final val List: NameType = "List" - final val Seq: NameType = "Seq" - final val Symbol: NameType = "Symbol" - final val ClassTag: NameType = "ClassTag" - final val TypeTag : NameType = "TypeTag" - final val ConcreteTypeTag: NameType = "ConcreteTypeTag" - final val Expr: NameType = "Expr" - final val String: NameType = "String" - - // fictions we use as both types and terms - final val ERROR: NameType = "" - final val NO_NAME: NameType = "" // formerly NOSYMBOL - final val WILDCARD: NameType = "_" - } - - /** This should be the first trait in the linearization. */ - // abstract class Keywords extends CommonNames { - abstract class Keywords extends { - private val kw = new KeywordSetBuilder - - final val ABSTRACTkw: TermName = kw("abstract") - final val CASEkw: TermName = kw("case") - final val CLASSkw: TermName = kw("class") - final val CATCHkw: TermName = kw("catch") - final val DEFkw: TermName = kw("def") - final val DOkw: TermName = kw("do") - final val ELSEkw: TermName = kw("else") - final val EXTENDSkw: TermName = kw("extends") - final val FALSEkw: TermName = kw("false") - final val FINALkw: TermName = kw("final") - final val FINALLYkw: TermName = kw("finally") - final val FORkw: TermName = kw("for") - final val FORSOMEkw: TermName = kw("forSome") - final val IFkw: TermName = kw("if") - final val IMPLICITkw: TermName = kw("implicit") - final val IMPORTkw: TermName = kw("import") - final val LAZYkw: TermName = kw("lazy") - final val MACROkw: TermName = kw("macro") - final val MATCHkw: TermName = kw("match") - final val NEWkw: TermName = kw("new") - final val NULLkw: TermName = kw("null") - final val OBJECTkw: TermName = kw("object") - final val OVERRIDEkw: TermName = kw("override") - final val PACKAGEkw: TermName = kw("package") - final val PRIVATEkw: TermName = kw("private") - final val PROTECTEDkw: TermName = kw("protected") - final val RETURNkw: TermName = kw("return") - final val SEALEDkw: TermName = kw("sealed") - final val SUPERkw: TermName = kw("super") - final val THENkw: TermName = kw("then") - final val THISkw: TermName = kw("this") - final val THROWkw: TermName = kw("throw") - final val TRAITkw: TermName = kw("trait") - final val TRUEkw: TermName = kw("true") - final val TRYkw: TermName = kw("try") - final val TYPEkw: TermName = kw("type") - final val VALkw: TermName = kw("val") - final val VARkw: TermName = kw("var") - final val WITHkw: TermName = kw("with") - final val WHILEkw: TermName = kw("while") - final val YIELDkw: TermName = kw("yield") - final val DOTkw: TermName = kw(".") - final val USCOREkw: TermName = kw("_") - final val COLONkw: TermName = kw(":") - final val EQUALSkw: TermName = kw("=") - final val ARROWkw: TermName = kw("=>") - final val LARROWkw: TermName = kw("<-") - final val SUBTYPEkw: TermName = kw("<:") - final val VIEWBOUNDkw: TermName = kw("<%") - final val SUPERTYPEkw: TermName = kw(">:") - final val HASHkw: TermName = kw("#") - final val ATkw: TermName = kw("@") - - final val keywords = kw.result - } with CommonNames { - final val javaKeywords = new JavaKeywords() - } - - abstract class TypeNames extends Keywords with TypeNamesApi { - type NameType = TypeName - protected implicit def createNameType(name: String): TypeName = newTypeNameCached(name) - - final val BYNAME_PARAM_CLASS_NAME: NameType = "" - final val EQUALS_PATTERN_NAME: NameType = "" - final val JAVA_REPEATED_PARAM_CLASS_NAME: NameType = "" - final val LOCAL_CHILD: NameType = "" - final val REFINE_CLASS_NAME: NameType = "" - final val REPEATED_PARAM_CLASS_NAME: NameType = "" - final val WILDCARD_STAR: NameType = "_*" - final val REIFY_TREECREATOR_PREFIX: NameType = "$treecreator" - final val REIFY_TYPECREATOR_PREFIX: NameType = "$typecreator" - - final val Any: NameType = "Any" - final val AnyVal: NameType = "AnyVal" - final val ExprApi: NameType = "ExprApi" - final val Mirror: NameType = "Mirror" - final val Nothing: NameType = "Nothing" - final val Null: NameType = "Null" - final val Object: NameType = "Object" - final val PartialFunction: NameType = "PartialFunction" - final val PrefixType: NameType = "PrefixType" - final val Product: NameType = "Product" - final val Serializable: NameType = "Serializable" - final val Singleton: NameType = "Singleton" - final val Throwable: NameType = "Throwable" - - final val Annotation: NameType = "Annotation" - final val ClassfileAnnotation: NameType = "ClassfileAnnotation" - final val Enum: NameType = "Enum" - final val Group: NameType = "Group" - final val Tree: NameType = "Tree" - final val Type : NameType = "Type" - final val TypeTree: NameType = "TypeTree" - - // Annotation simple names, used in Namer - final val BeanPropertyAnnot: NameType = "BeanProperty" - final val BooleanBeanPropertyAnnot: NameType = "BooleanBeanProperty" - final val bridgeAnnot: NameType = "bridge" - - // Classfile Attributes - final val AnnotationDefaultATTR: NameType = "AnnotationDefault" - final val BridgeATTR: NameType = "Bridge" - final val ClassfileAnnotationATTR: NameType = "RuntimeInvisibleAnnotations" // RetentionPolicy.CLASS. Currently not used (Apr 2009). - final val CodeATTR: NameType = "Code" - final val ConstantValueATTR: NameType = "ConstantValue" - final val DeprecatedATTR: NameType = "Deprecated" - final val ExceptionsATTR: NameType = "Exceptions" - final val InnerClassesATTR: NameType = "InnerClasses" - final val LineNumberTableATTR: NameType = "LineNumberTable" - final val LocalVariableTableATTR: NameType = "LocalVariableTable" - final val RuntimeAnnotationATTR: NameType = "RuntimeVisibleAnnotations" // RetentionPolicy.RUNTIME - final val RuntimeParamAnnotationATTR: NameType = "RuntimeVisibleParameterAnnotations" // RetentionPolicy.RUNTIME (annotations on parameters) - final val ScalaATTR: NameType = "Scala" - final val ScalaSignatureATTR: NameType = "ScalaSig" - final val SignatureATTR: NameType = "Signature" - final val SourceFileATTR: NameType = "SourceFile" - final val SyntheticATTR: NameType = "Synthetic" - - def dropSingletonName(name: Name): TypeName = (name dropRight SINGLETON_SUFFIX.length).toTypeName - def singletonName(name: Name): TypeName = (name append SINGLETON_SUFFIX).toTypeName - def implClassName(name: Name): TypeName = (name append IMPL_CLASS_SUFFIX).toTypeName - def interfaceName(implname: Name): TypeName = (implname dropRight IMPL_CLASS_SUFFIX.length).toTypeName - } - - abstract class TermNames extends Keywords with TermNamesApi { - type NameType = TermName - protected implicit def createNameType(name: String): TermName = newTermNameCached(name) - - /** Base strings from which synthetic names are derived. */ - val BITMAP_PREFIX = "bitmap$" - val CHECK_IF_REFUTABLE_STRING = "check$ifrefutable$" - val DEFAULT_GETTER_STRING = "$default$" - val DEFAULT_GETTER_INIT_STRING = "$lessinit$greater" // CONSTRUCTOR.encoded, less is more - val DO_WHILE_PREFIX = "doWhile$" - val EVIDENCE_PARAM_PREFIX = "evidence$" - val EXCEPTION_RESULT_PREFIX = "exceptionResult" - val EXPAND_SEPARATOR_STRING = "$$" - val INTERPRETER_IMPORT_WRAPPER = "$iw" - val INTERPRETER_LINE_PREFIX = "line" - val INTERPRETER_VAR_PREFIX = "res" - val INTERPRETER_WRAPPER_SUFFIX = "$object" - val LOCALDUMMY_PREFIX = " true - case _ => false - } - - def isOpAssignmentName(name: Name) = name match { - case raw.NE | raw.LE | raw.GE | EMPTY => false - case _ => - name.endChar == '=' && name.startChar != '=' && isOperatorPart(name.startChar) - } - - /** The expanded name of `name` relative to this class `base` with given `separator` - */ - def expandedName(name: TermName, base: Symbol, separator: String = EXPAND_SEPARATOR_STRING): TermName = - newTermNameCached(base.fullName('$') + separator + name) - - /** The expanded setter name of `name` relative to this class `base` - */ - def expandedSetterName(name: TermName, base: Symbol): TermName = - expandedName(name, base, separator = TRAIT_SETTER_SEPARATOR_STRING) - - /** If `name` is an expandedName name, the original name. - * Otherwise `name` itself. - */ - def originalName(name: Name): Name = { - var i = name.length - while (i >= 2 && !(name(i - 1) == '$' && name(i - 2) == '$')) i -= 1 - if (i >= 2) { - while (i >= 3 && name(i - 3) == '$') i -= 1 - name.subName(i, name.length) - } else name - } - - def unspecializedName(name: Name): Name = ( - if (name endsWith SPECIALIZED_SUFFIX) - name.subName(0, name.lastIndexOf('m') - 1) - else name - ) - - /* - def anonNumberSuffix(name: Name): Name = { - ("" + name) lastIndexOf '$' match { - case -1 => nme.EMPTY - case idx => - val s = name drop idx - if (s.toString forall (_.isDigit)) s - else nme.EMPTY - } - } - */ - - /** Return the original name and the types on which this name - * is specialized. For example, - * {{{ - * splitSpecializedName("foo$mIcD$sp") == ('foo', "I", "D") - * }}} - * `foo$mIcD$sp` is the name of a method specialized on two type - * parameters, the first one belonging to the method itself, on Int, - * and another one belonging to the enclosing class, on Double. - */ - def splitSpecializedName(name: Name): (Name, String, String) = - if (name endsWith SPECIALIZED_SUFFIX) { - val name1 = name dropRight SPECIALIZED_SUFFIX.length - val idxC = name1 lastIndexOf 'c' - val idxM = name1 lastIndexOf 'm' - - (name1.subName(0, idxM - 1), - name1.subName(idxC + 1, name1.length).toString, - name1.subName(idxM + 1, idxC).toString) - } else - (name, "", "") - - def getterName(name: TermName): TermName = if (isLocalName(name)) localToGetter(name) else name - def getterToLocal(name: TermName): TermName = name append LOCAL_SUFFIX_STRING - def getterToSetter(name: TermName): TermName = name append SETTER_SUFFIX - def localToGetter(name: TermName): TermName = name dropRight LOCAL_SUFFIX_STRING.length - - def dropLocalSuffix(name: Name): Name = if (name endsWith ' ') name dropRight 1 else name - - def setterToGetter(name: TermName): TermName = { - val p = name.pos(TRAIT_SETTER_SEPARATOR_STRING) - if (p < name.length) - setterToGetter(name drop (p + TRAIT_SETTER_SEPARATOR_STRING.length)) - else - name.subName(0, name.length - SETTER_SUFFIX.length) - } - - // Nominally, name$default$N, encoded for - def defaultGetterName(name: Name, pos: Int): TermName = { - val prefix = if (isConstructorName(name)) DEFAULT_GETTER_INIT_STRING else name - newTermName(prefix + DEFAULT_GETTER_STRING + pos) - } - // Nominally, name from name$default$N, CONSTRUCTOR for - def defaultGetterToMethod(name: Name): TermName = { - val p = name.pos(DEFAULT_GETTER_STRING) - if (p < name.length) { - val q = name.toTermName.subName(0, p) - // i.e., if (q.decoded == CONSTRUCTOR.toString) CONSTRUCTOR else q - if (q.toString == DEFAULT_GETTER_INIT_STRING) CONSTRUCTOR else q - } else name.toTermName - } - - // If the name ends with $nn where nn are - // all digits, strip the $ and the digits. - // Otherwise return the argument. - def stripAnonNumberSuffix(name: Name): Name = { - var pos = name.length - while (pos > 0 && name(pos - 1).isDigit) - pos -= 1 - - if (pos <= 0 || pos == name.length || name(pos - 1) != '$') name - else name.subName(0, pos - 1) - } - - def stripModuleSuffix(name: Name): Name = ( - if (isModuleName(name)) name dropRight MODULE_SUFFIX_STRING.length else name - ) - def localDummyName(clazz: Symbol): TermName = newTermName(LOCALDUMMY_PREFIX + clazz.name + ">") - def superName(name: Name): TermName = newTermName(SUPER_PREFIX_STRING + name) - - /** The name of an accessor for protected symbols. */ - def protName(name: Name): TermName = newTermName(PROTECTED_PREFIX + name) - - /** The name of a setter for protected symbols. Used for inherited Java fields. */ - def protSetterName(name: Name): TermName = newTermName(PROTECTED_SET_PREFIX + name) - - final val Nil: NameType = "Nil" - final val Predef: NameType = "Predef" - final val ScalaRunTime: NameType = "ScalaRunTime" - final val Some: NameType = "Some" - - val _1 : NameType = "_1" - val _2 : NameType = "_2" - val _3 : NameType = "_3" - val _4 : NameType = "_4" - val _5 : NameType = "_5" - val _6 : NameType = "_6" - val _7 : NameType = "_7" - val _8 : NameType = "_8" - val _9 : NameType = "_9" - val _10 : NameType = "_10" - val _11 : NameType = "_11" - val _12 : NameType = "_12" - val _13 : NameType = "_13" - val _14 : NameType = "_14" - val _15 : NameType = "_15" - val _16 : NameType = "_16" - val _17 : NameType = "_17" - val _18 : NameType = "_18" - val _19 : NameType = "_19" - val _20 : NameType = "_20" - val _21 : NameType = "_21" - val _22 : NameType = "_22" - - val x_0 : NameType = "x$0" - val x_1 : NameType = "x$1" - val x_2 : NameType = "x$2" - val x_3 : NameType = "x$3" - val x_4 : NameType = "x$4" - val x_5 : NameType = "x$5" - val x_6 : NameType = "x$6" - val x_7 : NameType = "x$7" - val x_8 : NameType = "x$8" - val x_9 : NameType = "x$9" - - @switch def syntheticParamName(i: Int): TermName = i match { - case 0 => nme.x_0 - case 1 => nme.x_1 - case 2 => nme.x_2 - case 3 => nme.x_3 - case 4 => nme.x_4 - case 5 => nme.x_5 - case 6 => nme.x_6 - case 7 => nme.x_7 - case 8 => nme.x_8 - case 9 => nme.x_9 - case _ => newTermName("x$" + i) - } - - @switch def productAccessorName(j: Int): TermName = j match { - case 1 => nme._1 - case 2 => nme._2 - case 3 => nme._3 - case 4 => nme._4 - case 5 => nme._5 - case 6 => nme._6 - case 7 => nme._7 - case 8 => nme._8 - case 9 => nme._9 - case 10 => nme._10 - case 11 => nme._11 - case 12 => nme._12 - case 13 => nme._13 - case 14 => nme._14 - case 15 => nme._15 - case 16 => nme._16 - case 17 => nme._17 - case 18 => nme._18 - case 19 => nme._19 - case 20 => nme._20 - case 21 => nme._21 - case 22 => nme._22 - case _ => newTermName("_" + j) - } - - val ??? = encode("???") - - val wrapRefArray: NameType = "wrapRefArray" - val wrapByteArray: NameType = "wrapByteArray" - val wrapShortArray: NameType = "wrapShortArray" - val wrapCharArray: NameType = "wrapCharArray" - val wrapIntArray: NameType = "wrapIntArray" - val wrapLongArray: NameType = "wrapLongArray" - val wrapFloatArray: NameType = "wrapFloatArray" - val wrapDoubleArray: NameType = "wrapDoubleArray" - val wrapBooleanArray: NameType = "wrapBooleanArray" - val wrapUnitArray: NameType = "wrapUnitArray" - val genericWrapArray: NameType = "genericWrapArray" - - // Compiler utilized names - - val AnnotatedType: NameType = "AnnotatedType" - val AnnotationInfo: NameType = "AnnotationInfo" - val Any: NameType = "Any" - val AnyVal: NameType = "AnyVal" - val AppliedTypeTree: NameType = "AppliedTypeTree" - val Apply: NameType = "Apply" - val ArrayAnnotArg: NameType = "ArrayAnnotArg" - val Constant: NameType = "Constant" - val ConstantType: NameType = "ConstantType" - val EmptyPackage: NameType = "EmptyPackage" - val EmptyPackageClass: NameType = "EmptyPackageClass" - val ExistentialTypeTree: NameType = "ExistentialTypeTree" - val Flag : NameType = "Flag" - val Ident: NameType = "Ident" - val Import: NameType = "Import" - val Literal: NameType = "Literal" - val LiteralAnnotArg: NameType = "LiteralAnnotArg" - val Modifiers: NameType = "Modifiers" - val NestedAnnotArg: NameType = "NestedAnnotArg" - val NoFlags: NameType = "NoFlags" - val NoPrefix: NameType = "NoPrefix" - val NoSymbol: NameType = "NoSymbol" - val Nothing: NameType = "Nothing" - val NoType: NameType = "NoType" - val Null: NameType = "Null" - val Object: NameType = "Object" - val RootPackage: NameType = "RootPackage" - val RootClass: NameType = "RootClass" - val Select: NameType = "Select" - val StringContext: NameType = "StringContext" - val This: NameType = "This" - val ThisType: NameType = "ThisType" - val Tree : NameType = "Tree" - val Tuple2: NameType = "Tuple2" - val TYPE_ : NameType = "TYPE" - val TypeApply: NameType = "TypeApply" - val TypeRef: NameType = "TypeRef" - val TypeTree: NameType = "TypeTree" - val UNIT : NameType = "UNIT" - val add_ : NameType = "add" - val annotation: NameType = "annotation" - val anyValClass: NameType = "anyValClass" - val append: NameType = "append" - val apply: NameType = "apply" - val applyDynamic: NameType = "applyDynamic" - val applyDynamicNamed: NameType = "applyDynamicNamed" - val applyImpl: NameType = "applyImpl" - val applyOrElse: NameType = "applyOrElse" - val args : NameType = "args" - val argv : NameType = "argv" - val arrayClass: NameType = "arrayClass" - val arrayElementClass: NameType = "arrayElementClass" - val arrayTagToClassManifest: NameType = "arrayTagToClassManifest" - val arrayValue: NameType = "arrayValue" - val array_apply : NameType = "array_apply" - val array_clone : NameType = "array_clone" - val array_length : NameType = "array_length" - val array_update : NameType = "array_update" - val arraycopy: NameType = "arraycopy" - val asTermSymbol: NameType = "asTermSymbol" - val asModuleSymbol: NameType = "asModuleSymbol" - val asMethodSymbol: NameType = "asMethodSymbol" - val asTypeSymbol: NameType = "asTypeSymbol" - val asClassSymbol: NameType = "asClassSymbol" - val asInstanceOf_ : NameType = "asInstanceOf" - val asInstanceOf_Ob : NameType = "$asInstanceOf" - val asTypeConstructor: NameType = "asTypeConstructor" - val assert_ : NameType = "assert" - val assume_ : NameType = "assume" - val basis : NameType = "basis" - val box: NameType = "box" - val build : NameType = "build" - val bytes: NameType = "bytes" - val canEqual_ : NameType = "canEqual" - val checkInitialized: NameType = "checkInitialized" - val classOf: NameType = "classOf" - val clone_ : NameType = if (forMSIL) "MemberwiseClone" else "clone" // sn.OClone causes checkinit failure - val concreteTypeTagToManifest: NameType = "concreteTypeTagToManifest" - val conforms: NameType = "conforms" - val copy: NameType = "copy" - val currentMirror: NameType = "currentMirror" - val definitions: NameType = "definitions" - val delayedInit: NameType = "delayedInit" - val delayedInitArg: NameType = "delayedInit$body" - val drop: NameType = "drop" - val elem: NameType = "elem" - val emptyValDef: NameType = "emptyValDef" - val ensureAccessible : NameType = "ensureAccessible" - val eq: NameType = "eq" - val equalsNumChar : NameType = "equalsNumChar" - val equalsNumNum : NameType = "equalsNumNum" - val equalsNumObject : NameType = "equalsNumObject" - val equals_ : NameType = if (forMSIL) "Equals" else "equals" - val error: NameType = "error" - val eval: NameType = "eval" - val ex: NameType = "ex" - val experimental: NameType = "experimental" - val false_ : NameType = "false" - val filter: NameType = "filter" - val finalize_ : NameType = if (forMSIL) "Finalize" else "finalize" - val find_ : NameType = "find" - val flagsFromBits : NameType = "flagsFromBits" - val flatMap: NameType = "flatMap" - val foreach: NameType = "foreach" - val genericArrayOps: NameType = "genericArrayOps" - val get: NameType = "get" - val getOrElse: NameType = "getOrElse" - val hasNext: NameType = "hasNext" - val hashCode_ : NameType = if (forMSIL) "GetHashCode" else "hashCode" - val hash_ : NameType = "hash" - val head: NameType = "head" - val identity: NameType = "identity" - val implicitly: NameType = "implicitly" - val in: NameType = "in" - val info: NameType = "info" - val inlinedEquals: NameType = "inlinedEquals" - val isArray: NameType = "isArray" - val isDefinedAt: NameType = "isDefinedAt" - val isEmpty: NameType = "isEmpty" - val isInstanceOf_ : NameType = "isInstanceOf" - val isInstanceOf_Ob : NameType = "$isInstanceOf" - val java: NameType = "java" - val key: NameType = "key" - val lang: NameType = "lang" - val length: NameType = "length" - val lengthCompare: NameType = "lengthCompare" - val liftedTree: NameType = "liftedTree" - val `macro` : NameType = "macro" - val macroThis : NameType = "_this" - val macroContext : NameType = "c" - val main: NameType = "main" - val manifest: NameType = "manifest" - val manifestToConcreteTypeTag: NameType = "manifestToConcreteTypeTag" - val map: NameType = "map" - val materializeArrayTag: NameType = "materializeArrayTag" - val materializeClassTag: NameType = "materializeClassTag" - val materializeConcreteTypeTag: NameType = "materializeConcreteTypeTag" - val materializeTypeTag: NameType = "materializeTypeTag" - val mirror : NameType = "mirror" - val moduleClass : NameType = "moduleClass" - val name: NameType = "name" - val ne: NameType = "ne" - val newArray: NameType = "newArray" - val newFreeExistential: NameType = "newFreeExistential" - val newFreeTerm: NameType = "newFreeTerm" - val newFreeType: NameType = "newFreeType" - val newNestedSymbol: NameType = "newNestedSymbol" - val newScopeWith: NameType = "newScopeWith" - val next: NameType = "next" - val nmeNewTermName: NameType = "newTermName" - val nmeNewTypeName: NameType = "newTypeName" - val normalize: NameType = "normalize" - val notifyAll_ : NameType = "notifyAll" - val notify_ : NameType = "notify" - val null_ : NameType = "null" - val ofDim: NameType = "ofDim" - val origin: NameType = "origin" - val prefix : NameType = "prefix" - val productArity: NameType = "productArity" - val productElement: NameType = "productElement" - val productIterator: NameType = "productIterator" - val productPrefix: NameType = "productPrefix" - val readResolve: NameType = "readResolve" - val reflect : NameType = "reflect" - val reify : NameType = "reify" - val rootMirror : NameType = "rootMirror" - val runOrElse: NameType = "runOrElse" - val runtime: NameType = "runtime" - val runtimeClass: NameType = "runtimeClass" - val runtimeMirror: NameType = "runtimeMirror" - val sameElements: NameType = "sameElements" - val scala_ : NameType = "scala" - val selectDynamic: NameType = "selectDynamic" - val selectOverloadedMethod: NameType = "selectOverloadedMethod" - val selectTerm: NameType = "selectTerm" - val selectType: NameType = "selectType" - val self: NameType = "self" - val setAccessible: NameType = "setAccessible" - val setAnnotations: NameType = "setAnnotations" - val setSymbol: NameType = "setSymbol" - val setType: NameType = "setType" - val setTypeSignature: NameType = "setTypeSignature" - val splice: NameType = "splice" - val staticClass : NameType = "staticClass" - val staticModule : NameType = "staticModule" - val synchronized_ : NameType = "synchronized" - val tail: NameType = "tail" - val `then` : NameType = "then" - val this_ : NameType = "this" - val thisPrefix : NameType = "thisPrefix" - val throw_ : NameType = "throw" - val toArray: NameType = "toArray" - val toList: NameType = "toList" - val toObjectArray : NameType = "toObjectArray" - val toSeq: NameType = "toSeq" - val toString_ : NameType = if (forMSIL) "ToString" else "toString" - val tpe : NameType = "tpe" - val tree : NameType = "tree" - val true_ : NameType = "true" - val typedProductIterator: NameType = "typedProductIterator" - val unapply: NameType = "unapply" - val unapplySeq: NameType = "unapplySeq" - val unbox: NameType = "unbox" - val universe: NameType = "universe" - val update: NameType = "update" - val updateDynamic: NameType = "updateDynamic" - val value: NameType = "value" - val valueOf : NameType = "valueOf" - val values : NameType = "values" - val view_ : NameType = "view" - val wait_ : NameType = "wait" - val withFilter: NameType = "withFilter" - val wrap: NameType = "wrap" - val zip: NameType = "zip" - - val synthSwitch: NameType = "$synthSwitch" - - // unencoded operators - object raw { - final val AMP : NameType = "&" - final val BANG : NameType = "!" - final val BAR : NameType = "|" - final val DOLLAR: NameType = "$" - final val GE: NameType = ">=" - final val LE: NameType = "<=" - final val MINUS: NameType = "-" - final val NE: NameType = "!=" - final val PLUS : NameType = "+" - final val SLASH: NameType = "/" - final val STAR : NameType = "*" - final val TILDE: NameType = "~" - - final val isUnary: Set[Name] = Set(MINUS, PLUS, TILDE, BANG) - } - - // value-conversion methods - val toByte: NameType = "toByte" - val toShort: NameType = "toShort" - val toChar: NameType = "toChar" - val toInt: NameType = "toInt" - val toLong: NameType = "toLong" - val toFloat: NameType = "toFloat" - val toDouble: NameType = "toDouble" - - // primitive operation methods for structual types mostly - // overlap with the above, but not for these two. - val toCharacter: NameType = "toCharacter" - val toInteger: NameType = "toInteger" - - def newLazyValSlowComputeName(lzyValName: Name) = lzyValName append LAZY_SLOW_SUFFIX - - // ASCII names for operators - val ADD = encode("+") - val AND = encode("&") - val ASR = encode(">>") - val DIV = encode("/") - val EQ = encode("==") - val EQL = encode("=") - val GE = encode(">=") - val GT = encode(">") - val HASHHASH = encode("##") - val LE = encode("<=") - val LSL = encode("<<") - val LSR = encode(">>>") - val LT = encode("<") - val MINUS = encode("-") - val MOD = encode("%") - val MUL = encode("*") - val NE = encode("!=") - val OR = encode("|") - val PLUS = ADD // technically redundant, but ADD looks funny with MINUS - val SUB = MINUS // ... as does SUB with PLUS - val XOR = encode("^") - val ZAND = encode("&&") - val ZOR = encode("||") - - // unary operators - val UNARY_~ = encode("unary_~") - val UNARY_+ = encode("unary_+") - val UNARY_- = encode("unary_-") - val UNARY_! = encode("unary_!") - - // Grouped here so Cleanup knows what tests to perform. - val CommonOpNames = Set[Name](OR, XOR, AND, EQ, NE) - val ConversionNames = Set[Name](toByte, toChar, toDouble, toFloat, toInt, toLong, toShort) - val BooleanOpNames = Set[Name](ZOR, ZAND, UNARY_!) ++ CommonOpNames - val NumberOpNames = ( - Set[Name](ADD, SUB, MUL, DIV, MOD, LSL, LSR, ASR, LT, LE, GE, GT) - ++ Set(UNARY_+, UNARY_-, UNARY_!) - ++ ConversionNames - ++ CommonOpNames - ) - - val add: NameType = "add" - val complement: NameType = "complement" - val divide: NameType = "divide" - val multiply: NameType = "multiply" - val negate: NameType = "negate" - val positive: NameType = "positive" - val shiftLogicalRight: NameType = "shiftLogicalRight" - val shiftSignedLeft: NameType = "shiftSignedLeft" - val shiftSignedRight: NameType = "shiftSignedRight" - val subtract: NameType = "subtract" - val takeAnd: NameType = "takeAnd" - val takeConditionalAnd: NameType = "takeConditionalAnd" - val takeConditionalOr: NameType = "takeConditionalOr" - val takeModulo: NameType = "takeModulo" - val takeNot: NameType = "takeNot" - val takeOr: NameType = "takeOr" - val takeXor: NameType = "takeXor" - val testEqual: NameType = "testEqual" - val testGreaterOrEqualThan: NameType = "testGreaterOrEqualThan" - val testGreaterThan: NameType = "testGreaterThan" - val testLessOrEqualThan: NameType = "testLessOrEqualThan" - val testLessThan: NameType = "testLessThan" - val testNotEqual: NameType = "testNotEqual" - - def toUnaryName(name: TermName): TermName = name match { - case raw.MINUS => UNARY_- - case raw.PLUS => UNARY_+ - case raw.TILDE => UNARY_~ - case raw.BANG => UNARY_! - case _ => name - } - /** The name of a method which stands in for a primitive operation - * during structural type dispatch. - */ - def primitiveInfixMethodName(name: Name): TermName = name match { - case OR => takeOr - case XOR => takeXor - case AND => takeAnd - case EQ => testEqual - case NE => testNotEqual - case ADD => add - case SUB => subtract - case MUL => multiply - case DIV => divide - case MOD => takeModulo - case LSL => shiftSignedLeft - case LSR => shiftLogicalRight - case ASR => shiftSignedRight - case LT => testLessThan - case LE => testLessOrEqualThan - case GE => testGreaterOrEqualThan - case GT => testGreaterThan - case ZOR => takeConditionalOr - case ZAND => takeConditionalAnd - case _ => NO_NAME - } - /** Postfix/prefix, really. - */ - def primitivePostfixMethodName(name: Name): TermName = name match { - case UNARY_! => takeNot - case UNARY_+ => positive - case UNARY_- => negate - case UNARY_~ => complement - case `toByte` => toByte - case `toShort` => toShort - case `toChar` => toCharacter - case `toInt` => toInteger - case `toLong` => toLong - case `toFloat` => toFloat - case `toDouble` => toDouble - case _ => NO_NAME - } - - /** Translate a String into a list of simple TypeNames and TermNames. - * In all segments before the last, type/term is determined by whether - * the following separator char is '.' or '#'. In the last segment, - * the argument "assumeTerm" determines it. Examples: - * - * package foo { - * object Lorax { object Wog ; class Wog } - * class Lorax { object Zax ; class Zax } - * } - * - * f("foo.Lorax", true) == List("foo": Term, "Lorax": Term) // object Lorax - * f("foo.Lorax", false) == List("foo": Term, "Lorax": Type) // class Lorax - * f("Lorax.Wog", true) == List("Lorax": Term, "Wog": Term) // object Wog - * f("Lorax.Wog", false) == List("Lorax": Term, "Wog": Type) // class Wog - * f("Lorax#Zax", true) == List("Lorax": Type, "Zax": Term) // object Zax - * f("Lorax#Zax", false) == List("Lorax": Type, "Zax": Type) // class Zax - * - * Note that in actual scala syntax you cannot refer to object Zax without an - * instance of Lorax, so Lorax#Zax could only mean the type. One might think - * that Lorax#Zax.type would work, but this is not accepted by the parser. - * For the purposes of referencing that object, the syntax is allowed. - */ - def segments(name: String, assumeTerm: Boolean): List[Name] = { - def mkName(str: String, term: Boolean): Name = - if (term) newTermName(str) else newTypeName(str) - - name.indexWhere(ch => ch == '.' || ch == '#') match { - // it's the last segment: the parameter tells us whether type or term - case -1 => if (name == "") scala.Nil else scala.List(mkName(name, assumeTerm)) - // otherwise, we can tell based on whether '#' or '.' is the following char. - case idx => - val (simple, div, rest) = (name take idx, name charAt idx, newTermName(name) drop (idx + 1)) - mkName(simple, div == '.') :: segments(rest, assumeTerm) - } - } - - def newBitmapName(bitmapPrefix: Name, n: Int) = bitmapPrefix append ("" + n) - - val BITMAP_NORMAL: NameType = BITMAP_PREFIX + "" // initialization bitmap for public/protected lazy vals - val BITMAP_TRANSIENT: NameType = BITMAP_PREFIX + "trans$" // initialization bitmap for transient lazy vals - val BITMAP_CHECKINIT: NameType = BITMAP_PREFIX + "init$" // initialization bitmap for checkinit values - val BITMAP_CHECKINIT_TRANSIENT: NameType = BITMAP_PREFIX + "inittrans$" // initialization bitmap for transient checkinit values - } - - object tpnme extends TypeNames { } - - /** For fully qualified type names. - */ - object fulltpnme extends TypeNames { - val RuntimeNothing: NameType = "scala.runtime.Nothing$" - val RuntimeNull: NameType = "scala.runtime.Null$" - val JavaLangEnum: NameType = "java.lang.Enum" - } - - /** Java binary names, like scala/runtime/Nothing$. - */ - object binarynme { - def toBinary(name: Name) = name mapName (_.replace('.', '/')) - - val RuntimeNothing = toBinary(fulltpnme.RuntimeNothing).toTypeName - val RuntimeNull = toBinary(fulltpnme.RuntimeNull).toTypeName - } - - val javanme = nme.javaKeywords - - // [Eugene++ to Martin] had to move a lot of stuff from here to TermNames to satisfy the contract - // why do we even have stuff in object nme? cf. object tpnme - object nme extends TermNames { - - def isModuleVarName(name: Name): Boolean = - stripAnonNumberSuffix(name) endsWith MODULE_VAR_SUFFIX - - def moduleVarName(name: TermName): TermName = - newTermNameCached("" + name + MODULE_VAR_SUFFIX) - - def getCause = sn.GetCause - def getClass_ = sn.GetClass - def getComponentType = sn.GetComponentType - def getMethod_ = sn.GetMethod - def invoke_ = sn.Invoke - - val isBoxedNumberOrBoolean: NameType = "isBoxedNumberOrBoolean" - val isBoxedNumber: NameType = "isBoxedNumber" - - val reflPolyCacheName: NameType = "reflPoly$Cache" - val reflClassCacheName: NameType = "reflClass$Cache" - val reflParamsCacheName: NameType = "reflParams$Cache" - val reflMethodCacheName: NameType = "reflMethod$Cache" - val reflMethodName: NameType = "reflMethod$Method" - - private val reflectionCacheNames = Set[NameType]( - reflPolyCacheName, - reflClassCacheName, - reflParamsCacheName, - reflMethodCacheName, - reflMethodName - ) - def isReflectionCacheName(name: Name) = reflectionCacheNames exists (name startsWith _) - - @deprecated("Use a method in tpnme", "2.10.0") def dropSingletonName(name: Name): TypeName = tpnme.dropSingletonName(name) - @deprecated("Use a method in tpnme", "2.10.0") def singletonName(name: Name): TypeName = tpnme.singletonName(name) - @deprecated("Use a method in tpnme", "2.10.0") def implClassName(name: Name): TypeName = tpnme.implClassName(name) - @deprecated("Use a method in tpnme", "2.10.0") def interfaceName(implname: Name): TypeName = tpnme.interfaceName(implname) - } - - abstract class SymbolNames { - protected implicit def createNameType(s: String): TypeName = newTypeNameCached(s) - - val BeanProperty : TypeName - val BooleanBeanProperty : TypeName - val BoxedBoolean : TypeName - val BoxedCharacter : TypeName - val BoxedNumber : TypeName - val Class : TypeName - val Delegate : TypeName - val IOOBException : TypeName // IndexOutOfBoundsException - val InvTargetException : TypeName // InvocationTargetException - val JavaSerializable : TypeName - val MethodAsObject : TypeName - val NPException : TypeName // NullPointerException - val Object : TypeName - val String : TypeName - val Throwable : TypeName - val ValueType : TypeName - - val ForName : TermName - val GetCause : TermName - val GetClass : TermName - val GetClassLoader : TermName - val GetComponentType : TermName - val GetMethod : TermName - val Invoke : TermName - val JavaLang : TermName - - val Boxed: immutable.Map[TypeName, TypeName] - } - - class JavaKeywords { - private val kw = new KeywordSetBuilder - - final val ABSTRACTkw: TermName = kw("abstract") - final val ASSERTkw: TermName = kw("assert") - final val BOOLEANkw: TermName = kw("boolean") - final val BREAKkw: TermName = kw("break") - final val BYTEkw: TermName = kw("byte") - final val CASEkw: TermName = kw("case") - final val CATCHkw: TermName = kw("catch") - final val CHARkw: TermName = kw("char") - final val CLASSkw: TermName = kw("class") - final val CONSTkw: TermName = kw("const") - final val CONTINUEkw: TermName = kw("continue") - final val DEFAULTkw: TermName = kw("default") - final val DOkw: TermName = kw("do") - final val DOUBLEkw: TermName = kw("double") - final val ELSEkw: TermName = kw("else") - final val ENUMkw: TermName = kw("enum") - final val EXTENDSkw: TermName = kw("extends") - final val FINALkw: TermName = kw("final") - final val FINALLYkw: TermName = kw("finally") - final val FLOATkw: TermName = kw("float") - final val FORkw: TermName = kw("for") - final val IFkw: TermName = kw("if") - final val GOTOkw: TermName = kw("goto") - final val IMPLEMENTSkw: TermName = kw("implements") - final val IMPORTkw: TermName = kw("import") - final val INSTANCEOFkw: TermName = kw("instanceof") - final val INTkw: TermName = kw("int") - final val INTERFACEkw: TermName = kw("interface") - final val LONGkw: TermName = kw("long") - final val NATIVEkw: TermName = kw("native") - final val NEWkw: TermName = kw("new") - final val PACKAGEkw: TermName = kw("package") - final val PRIVATEkw: TermName = kw("private") - final val PROTECTEDkw: TermName = kw("protected") - final val PUBLICkw: TermName = kw("public") - final val RETURNkw: TermName = kw("return") - final val SHORTkw: TermName = kw("short") - final val STATICkw: TermName = kw("static") - final val STRICTFPkw: TermName = kw("strictfp") - final val SUPERkw: TermName = kw("super") - final val SWITCHkw: TermName = kw("switch") - final val SYNCHRONIZEDkw: TermName = kw("synchronized") - final val THISkw: TermName = kw("this") - final val THROWkw: TermName = kw("throw") - final val THROWSkw: TermName = kw("throws") - final val TRANSIENTkw: TermName = kw("transient") - final val TRYkw: TermName = kw("try") - final val VOIDkw: TermName = kw("void") - final val VOLATILEkw: TermName = kw("volatile") - final val WHILEkw: TermName = kw("while") - - final val keywords = kw.result - } - - private abstract class JavaNames extends SymbolNames { - final val BoxedBoolean: TypeName = "java.lang.Boolean" - final val BoxedByte: TypeName = "java.lang.Byte" - final val BoxedCharacter: TypeName = "java.lang.Character" - final val BoxedDouble: TypeName = "java.lang.Double" - final val BoxedFloat: TypeName = "java.lang.Float" - final val BoxedInteger: TypeName = "java.lang.Integer" - final val BoxedLong: TypeName = "java.lang.Long" - final val BoxedNumber: TypeName = "java.lang.Number" - final val BoxedShort: TypeName = "java.lang.Short" - final val Class: TypeName = "java.lang.Class" - final val Delegate: TypeName = tpnme.NO_NAME - final val IOOBException: TypeName = "java.lang.IndexOutOfBoundsException" - final val InvTargetException: TypeName = "java.lang.reflect.InvocationTargetException" - final val MethodAsObject: TypeName = "java.lang.reflect.Method" - final val NPException: TypeName = "java.lang.NullPointerException" - final val Object: TypeName = "java.lang.Object" - final val String: TypeName = "java.lang.String" - final val Throwable: TypeName = "java.lang.Throwable" - final val ValueType: TypeName = tpnme.NO_NAME - - final val ForName: TermName = newTermName("forName") - final val GetCause: TermName = newTermName("getCause") - final val GetClass: TermName = newTermName("getClass") - final val GetClassLoader: TermName = newTermName("getClassLoader") - final val GetComponentType: TermName = newTermName("getComponentType") - final val GetMethod: TermName = newTermName("getMethod") - final val Invoke: TermName = newTermName("invoke") - final val JavaLang: TermName = newTermName("java.lang") - - val Boxed = immutable.Map[TypeName, TypeName]( - tpnme.Boolean -> BoxedBoolean, - tpnme.Byte -> BoxedByte, - tpnme.Char -> BoxedCharacter, - tpnme.Short -> BoxedShort, - tpnme.Int -> BoxedInteger, - tpnme.Long -> BoxedLong, - tpnme.Float -> BoxedFloat, - tpnme.Double -> BoxedDouble - ) - } - - private class MSILNames extends SymbolNames { - final val BeanProperty: TypeName = tpnme.NO_NAME - final val BooleanBeanProperty: TypeName = tpnme.NO_NAME - final val BoxedBoolean: TypeName = "System.IConvertible" - final val BoxedCharacter: TypeName = "System.IConvertible" - final val BoxedNumber: TypeName = "System.IConvertible" - final val Class: TypeName = "System.Type" - final val Delegate: TypeName = "System.MulticastDelegate" - final val IOOBException: TypeName = "System.IndexOutOfRangeException" - final val InvTargetException: TypeName = "System.Reflection.TargetInvocationException" - final val JavaSerializable: TypeName = tpnme.NO_NAME - final val MethodAsObject: TypeName = "System.Reflection.MethodInfo" - final val NPException: TypeName = "System.NullReferenceException" - final val Object: TypeName = "System.Object" - final val String: TypeName = "System.String" - final val Throwable: TypeName = "System.Exception" - final val ValueType: TypeName = "System.ValueType" - - final val ForName: TermName = newTermName("GetType") - final val GetCause: TermName = newTermName("InnerException") /* System.Reflection.TargetInvocationException.InnerException */ - final val GetClass: TermName = newTermName("GetType") - final lazy val GetClassLoader: TermName = throw new UnsupportedOperationException("Scala reflection is not supported on this platform"); - final val GetComponentType: TermName = newTermName("GetElementType") - final val GetMethod: TermName = newTermName("GetMethod") - final val Invoke: TermName = newTermName("Invoke") - final val JavaLang: TermName = newTermName("System") - - val Boxed = immutable.Map[TypeName, TypeName]( - tpnme.Boolean -> "System.Boolean", - tpnme.Byte -> "System.SByte", // a scala.Byte is signed and a System.SByte too (unlike a System.Byte) - tpnme.Char -> "System.Char", - tpnme.Short -> "System.Int16", - tpnme.Int -> "System.Int32", - tpnme.Long -> "System.Int64", - tpnme.Float -> "System.Single", - tpnme.Double -> "System.Double" - ) - } - - private class J2SENames extends JavaNames { - final val BeanProperty: TypeName = "scala.beans.BeanProperty" - final val BooleanBeanProperty: TypeName = "scala.beans.BooleanBeanProperty" - final val JavaSerializable: TypeName = "java.io.Serializable" - } - - lazy val sn: SymbolNames = - if (forMSIL) new MSILNames - else new J2SENames -} diff --git a/src/compiler/scala/reflect/internal/SymbolTable.scala b/src/compiler/scala/reflect/internal/SymbolTable.scala deleted file mode 100644 index cadd76b1ba..0000000000 --- a/src/compiler/scala/reflect/internal/SymbolTable.scala +++ /dev/null @@ -1,332 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import scala.collection.{ mutable, immutable } -import util._ - -abstract class SymbolTable extends makro.Universe - with Collections - with Names - with Symbols - with Types - with Kinds - with ExistentialsAndSkolems - with FlagSets - with Scopes - with Mirrors - with Definitions - with Constants - with BaseTypeSeqs - with InfoTransformers - with transform.Transforms - with StdNames - with AnnotationInfos - with AnnotationCheckers - with Trees - with TreePrinters - with Positions - with TypeDebugging - with Importers - with Required - with CapturedVariables - with StdAttachments - with StdCreators - with BuildUtils -{ - - val gen = new TreeGen { val global: SymbolTable.this.type = SymbolTable.this } - val treeBuild = gen - - def log(msg: => AnyRef): Unit - def abort(msg: String): Nothing = throw new FatalError(supplementErrorMessage(msg)) - - @deprecated("Give us a reason", "2.10.0") - def abort(): Nothing = abort("unknown error") - - /** Override with final implementation for inlining. */ - def debuglog(msg: => String): Unit = if (settings.debug.value) log(msg) - def debugwarn(msg: => String): Unit = if (settings.debug.value) Console.err.println(msg) - def throwableAsString(t: Throwable): String = "" + t - - /** Prints a stack trace if -Ydebug or equivalent was given, otherwise does nothing. */ - def debugStack(t: Throwable): Unit = debugwarn(throwableAsString(t)) - - /** Overridden when we know more about what was happening during a failure. */ - def supplementErrorMessage(msg: String): String = msg - - private[scala] def printCaller[T](msg: String)(result: T) = { - Console.err.println("%s: %s\nCalled from: %s".format(msg, result, - (new Throwable).getStackTrace.drop(2).take(15).mkString("\n"))) - - result - } - - private[scala] def printResult[T](msg: String)(result: T) = { - Console.err.println(msg + ": " + result) - result - } - private[scala] def logResult[T](msg: String)(result: T): T = { - log(msg + ": " + result) - result - } - private[scala] def logResultIf[T](msg: String, cond: T => Boolean)(result: T): T = { - if (cond(result)) - log(msg + ": " + result) - - result - } - - // For too long have we suffered in order to sort NAMES. - // I'm pretty sure there's a reasonable default for that. - // Notice challenge created by Ordering's invariance. - implicit def lowPriorityNameOrdering[T <: Names#Name]: Ordering[T] = - SimpleNameOrdering.asInstanceOf[Ordering[T]] - - private object SimpleNameOrdering extends Ordering[Names#Name] { - def compare(n1: Names#Name, n2: Names#Name) = ( - if (n1 eq n2) 0 - else n1.toString compareTo n2.toString - ) - } - - /** Dump each symbol to stdout after shutdown. - */ - final val traceSymbolActivity = sys.props contains "scalac.debug.syms" - object traceSymbols extends { - val global: SymbolTable.this.type = SymbolTable.this - } with util.TraceSymbolActivity - - /** Are we compiling for Java SE? */ - // def forJVM: Boolean - - /** Are we compiling for .NET? */ - def forMSIL: Boolean = false - - /** A last effort if symbol in a select . is not found. - * This is overridden by the reflection compiler to make up a package - * when it makes sense (i.e. is a package and is a term name). - */ - def missingHook(owner: Symbol, name: Name): Symbol = NoSymbol - - /** Returns the mirror that loaded given symbol */ - def mirrorThatLoaded(sym: Symbol): Mirror - - /** A period is an ordinal number for a phase in a run. - * Phases in later runs have higher periods than phases in earlier runs. - * Later phases have higher periods than earlier phases in the same run. - */ - type Period = Int - final val NoPeriod = 0 - - /** An ordinal number for compiler runs. First run has number 1. */ - type RunId = Int - final val NoRunId = 0 - - // sigh, this has to be public or atPhase doesn't inline. - var phStack: List[Phase] = Nil - private var ph: Phase = NoPhase - private var per = NoPeriod - - final def atPhaseStack: List[Phase] = phStack - final def phase: Phase = ph - - def atPhaseStackMessage = atPhaseStack match { - case Nil => "" - case ps => ps.reverseMap("->" + _).mkString("(", " ", ")") - } - - final def phase_=(p: Phase) { - //System.out.println("setting phase to " + p) - assert((p ne null) && p != NoPhase, p) - ph = p - per = period(currentRunId, p.id) - } - final def pushPhase(ph: Phase): Phase = { - val current = phase - phase = ph - phStack ::= ph - current - } - final def popPhase(ph: Phase) { - phStack = phStack.tail - phase = ph - } - - /** The current compiler run identifier. */ - def currentRunId: RunId - - /** The run identifier of the given period. */ - final def runId(period: Period): RunId = period >> 8 - - /** The phase identifier of the given period. */ - final def phaseId(period: Period): Phase#Id = period & 0xFF - - /** The period at the start of run that includes `period`. */ - final def startRun(period: Period): Period = period & 0xFFFFFF00 - - /** The current period. */ - final def currentPeriod: Period = { - //assert(per == (currentRunId << 8) + phase.id) - per - } - - /** The phase associated with given period. */ - final def phaseOf(period: Period): Phase = phaseWithId(phaseId(period)) - - final def period(rid: RunId, pid: Phase#Id): Period = - (rid << 8) + pid - - /** Are we later than given phase in compilation? */ - final def isAtPhaseAfter(p: Phase) = - p != NoPhase && phase.id > p.id - - /** Perform given operation at given phase. */ - @inline final def atPhase[T](ph: Phase)(op: => T): T = { - val saved = pushPhase(ph) - try op - finally popPhase(saved) - } - - - /** Since when it is to be "at" a phase is inherently ambiguous, - * a couple unambiguously named methods. - */ - @inline final def beforePhase[T](ph: Phase)(op: => T): T = atPhase(ph)(op) - @inline final def afterPhase[T](ph: Phase)(op: => T): T = atPhase(ph.next)(op) - @inline final def afterCurrentPhase[T](op: => T): T = atPhase(phase.next)(op) - @inline final def beforePrevPhase[T](op: => T): T = atPhase(phase.prev)(op) - - @inline final def atPhaseNotLaterThan[T](target: Phase)(op: => T): T = - if (isAtPhaseAfter(target)) atPhase(target)(op) else op - - final def isValid(period: Period): Boolean = - period != 0 && runId(period) == currentRunId && { - val pid = phaseId(period) - if (phase.id > pid) infoTransformers.nextFrom(pid).pid >= phase.id - else infoTransformers.nextFrom(phase.id).pid >= pid - } - - final def isValidForBaseClasses(period: Period): Boolean = { - def noChangeInBaseClasses(it: InfoTransformer, limit: Phase#Id): Boolean = ( - it.pid >= limit || - !it.changesBaseClasses && noChangeInBaseClasses(it.next, limit) - ); - period != 0 && runId(period) == currentRunId && { - val pid = phaseId(period) - if (phase.id > pid) noChangeInBaseClasses(infoTransformers.nextFrom(pid), phase.id) - else noChangeInBaseClasses(infoTransformers.nextFrom(phase.id), pid) - } - } - - def openPackageModule(container: Symbol, dest: Symbol) { - // unlink existing symbols in the package - for (member <- container.info.decls.iterator) { - if (!member.isPrivate && !member.isConstructor) { - // todo: handle overlapping definitions in some way: mark as errors - // or treat as abstractions. For now the symbol in the package module takes precedence. - for (existing <- dest.info.decl(member.name).alternatives) - dest.info.decls.unlink(existing) - } - } - // enter non-private decls the class - for (member <- container.info.decls.iterator) { - if (!member.isPrivate && !member.isConstructor) { - dest.info.decls.enter(member) - } - } - // enter decls of parent classes - for (p <- container.parentSymbols) { - if (p != definitions.ObjectClass) { - openPackageModule(p, dest) - } - } - } - - /** Convert array parameters denoting a repeated parameter of a Java method - * to `JavaRepeatedParamClass` types. - */ - def arrayToRepeated(tp: Type): Type = tp match { - case MethodType(params, rtpe) => - val formals = tp.paramTypes - assert(formals.last.typeSymbol == definitions.ArrayClass, formals) - val method = params.last.owner - val elemtp = formals.last.typeArgs.head match { - case RefinedType(List(t1, t2), _) if (t1.typeSymbol.isAbstractType && t2.typeSymbol == definitions.ObjectClass) => - t1 // drop intersection with Object for abstract types in varargs. UnCurry can handle them. - case t => - t - } - val newParams = method.newSyntheticValueParams(formals.init :+ definitions.javaRepeatedType(elemtp)) - MethodType(newParams, rtpe) - case PolyType(tparams, rtpe) => - PolyType(tparams, arrayToRepeated(rtpe)) - } - - abstract class SymLoader extends LazyType { - def fromSource = false - } - - /** if there's a `package` member object in `pkgClass`, enter its members into it. */ - def openPackageModule(pkgClass: Symbol) { - - val pkgModule = pkgClass.info.decl(nme.PACKAGEkw) - def fromSource = pkgModule.rawInfo match { - case ltp: SymLoader => ltp.fromSource - case _ => false - } - if (pkgModule.isModule && !fromSource) { - // println("open "+pkgModule)//DEBUG - openPackageModule(pkgModule, pkgClass) - } - } - - object perRunCaches { - import java.lang.ref.WeakReference - import scala.runtime.ScalaRunTime.stringOf - import scala.collection.generic.Clearable - - // Weak references so the garbage collector will take care of - // letting us know when a cache is really out of commission. - private val caches = mutable.HashSet[WeakReference[Clearable]]() - - def recordCache[T <: Clearable](cache: T): T = { - caches += new WeakReference(cache) - cache - } - - def clearAll() = { - debuglog("Clearing " + caches.size + " caches.") - caches foreach { ref => - val cache = ref.get() - if (cache == null) - caches -= ref - else - cache.clear() - } - } - - def newWeakMap[K, V]() = recordCache(mutable.WeakHashMap[K, V]()) - def newMap[K, V]() = recordCache(mutable.HashMap[K, V]()) - def newSet[K]() = recordCache(mutable.HashSet[K]()) - def newWeakSet[K <: AnyRef]() = recordCache(new WeakHashSet[K]()) - } - - /** The set of all installed infotransformers. */ - var infoTransformers = new InfoTransformer { - val pid = NoPhase.id - val changesBaseClasses = true - def transform(sym: Symbol, tpe: Type): Type = tpe - } - - /** The phase which has given index as identifier. */ - val phaseWithId: Array[Phase] - - /** Is this symbol table a part of a compiler universe? - */ - def isCompilerUniverse = false -} diff --git a/src/compiler/scala/reflect/internal/Symbols.scala b/src/compiler/scala/reflect/internal/Symbols.scala deleted file mode 100644 index 86693cf880..0000000000 --- a/src/compiler/scala/reflect/internal/Symbols.scala +++ /dev/null @@ -1,3190 +0,0 @@ - /* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.reflect -package internal - -import scala.collection.{ mutable, immutable } -import scala.collection.mutable.ListBuffer -import util.Statistics._ -import Flags._ - -trait Symbols extends api.Symbols { self: SymbolTable => - import definitions._ - - protected var ids = 0 - - val emptySymbolArray = new Array[Symbol](0) - - def symbolCount = ids // statistics - - protected def nextId() = { ids += 1; ids } - - /** Used for deciding in the IDE whether we can interrupt the compiler */ - //protected var activeLocks = 0 - - /** Used for debugging only */ - //protected var lockedSyms = collection.immutable.Set[Symbol]() - - /** Used to keep track of the recursion depth on locked symbols */ - private var recursionTable = immutable.Map.empty[Symbol, Int] - - private var nextexid = 0 - protected def freshExistentialName(suffix: String) = { - nextexid += 1 - newTypeName("_" + nextexid + suffix) - } - - // Set the fields which point companions at one another. Returns the module. - def connectModuleToClass(m: ModuleSymbol, moduleClass: ClassSymbol): ModuleSymbol = { - moduleClass.sourceModule = m - m setModuleClass moduleClass - m - } - - /** Create a new free term. Its owner is NoSymbol. - */ - def newFreeTermSymbol(name: TermName, info: Type, value: => Any, flags: Long = 0L, origin: String): FreeTermSymbol = - new FreeTermSymbol(name, value, origin) initFlags flags setInfo info - - /** Create a new free type. Its owner is NoSymbol. - */ - def newFreeTypeSymbol(name: TypeName, info: Type, value: => Any, flags: Long = 0L, origin: String): FreeTypeSymbol = - new FreeTypeSymbol(name, value, origin) initFlags flags setInfo info - - /** The original owner of a class. Used by the backend to generate - * EnclosingMethod attributes. - */ - val originalOwner = perRunCaches.newMap[Symbol, Symbol]() - - abstract class SymbolContextApiImpl extends SymbolContextApi { - this: Symbol => - - def kind: String = kindString - def isExistential: Boolean = this.isExistentiallyBound - - def newNestedSymbol(name: Name, pos: Position, newFlags: Long, isClass: Boolean): Symbol = name match { - case n: TermName => newTermSymbol(n, pos, newFlags) - case n: TypeName => if (isClass) newClassSymbol(n, pos, newFlags) else newNonClassSymbol(n, pos, newFlags) - } - - def thisPrefix: Type = thisType - def selfType: Type = typeOfThis - def typeSignature: Type = info - def typeSignatureIn(site: Type): Type = site memberInfo this - - def asType: Type = tpe - def asTypeIn(site: Type): Type = site.memberType(this) - def asTypeConstructor: Type = typeConstructor - def setInternalFlags(flag: Long): this.type = { setFlag(flag); this } - def setTypeSignature(tpe: Type): this.type = { setInfo(tpe); this } - def getAnnotations: List[AnnotationInfo] = { initialize; annotations } - def setAnnotations(annots: AnnotationInfo*): this.type = { setAnnotations(annots.toList); this } - - private def lastElemType(ts: Seq[Type]): Type = ts.last.normalize.typeArgs.head - - private def formalTypes(formals: List[Type], nargs: Int): List[Type] = { - val formals1 = formals mapConserve { - case TypeRef(_, ByNameParamClass, List(arg)) => arg - case formal => formal - } - if (isVarArgTypes(formals1)) { - val ft = lastElemType(formals) - formals1.init ::: List.fill(nargs - (formals1.length - 1))(ft) - } else formals1 - } - - def resolveOverloaded(pre: Type, targs: Seq[Type], actuals: Seq[Type]): Symbol = { - def firstParams(tpe: Type): (List[Symbol], List[Type]) = tpe match { - case PolyType(tparams, restpe) => - val (Nil, formals) = firstParams(restpe) - (tparams, formals) - case MethodType(params, _) => - (Nil, params map (_.tpe)) - case _ => - (Nil, Nil) - } - def isApplicable(alt: Symbol, targs: List[Type], actuals: Seq[Type]) = { - def isApplicableType(tparams: List[Symbol], tpe: Type): Boolean = { - val (tparams, formals) = firstParams(pre memberType alt) - val formals1 = formalTypes(formals, actuals.length) - val actuals1 = - if (isVarArgTypes(actuals)) { - if (!isVarArgTypes(formals)) return false - actuals.init :+ lastElemType(actuals) - } else actuals - if (formals1.length != actuals1.length) return false - - if (tparams.isEmpty) return (actuals1 corresponds formals1)(_ <:< _) - - if (targs.length == tparams.length) - isApplicableType(List(), tpe.instantiateTypeParams(tparams, targs)) - else if (targs.nonEmpty) - false - else { - val tvars = tparams map (TypeVar(_)) - (actuals1 corresponds formals1) { (actual, formal) => - val tp1 = actual.deconst.instantiateTypeParams(tparams, tvars) - val pt1 = actual.instantiateTypeParams(tparams, tvars) - tp1 <:< pt1 - } && - solve(tvars, tparams, List.fill(tparams.length)(COVARIANT), upper = false) - } - } - isApplicableType(List(), pre.memberType(alt)) - } - def isAsGood(alt1: Symbol, alt2: Symbol): Boolean = { - alt1 == alt2 || - alt2 == NoSymbol || { - val (tparams, formals) = firstParams(pre memberType alt1) - isApplicable(alt2, tparams map (_.tpe), formals) - } - } - assert(isOverloaded) - val applicables = alternatives filter (isApplicable(_, targs.toList, actuals)) - def winner(alts: List[Symbol]) = - ((NoSymbol: Symbol) /: alts)((best, alt) => if (isAsGood(alt, best)) alt else best) - val best = winner(applicables) - if (best == winner(applicables.reverse)) best else NoSymbol - } - } - - /** The class for all symbols */ - abstract class Symbol protected[Symbols] (initOwner: Symbol, initPos: Position, initName: Name) - extends SymbolContextApiImpl - with HasFlags - with Annotatable[Symbol] { - - type AccessBoundaryType = Symbol - type AnnotationType = AnnotationInfo - - // TODO - don't allow names to be renamed in this unstructured a fashion. - // Rename as little as possible. Enforce invariants on all renames. - type TypeOfClonedSymbol >: Null <: Symbol { type NameType = Symbol.this.NameType } - - // Abstract here so TypeSymbol and TermSymbol can have a private[this] field - // with the proper specific type. - def rawname: NameType - def name: NameType - def name_=(n: Name): Unit - def asNameType(n: Name): NameType - - private[this] var _rawowner = initOwner // Syncnote: need not be protected, as only assignment happens in owner_=, which is not exposed to api - private[this] var _rawflags: Long = _ - - def rawowner = _rawowner - def rawflags = _rawflags - - private var rawpos = initPos - - val id = nextId() // identity displayed when -uniqid - //assert(id != 3390, initName) - - private[this] var _validTo: Period = NoPeriod - - if (traceSymbolActivity) - traceSymbols.recordNewSymbol(this) - - def validTo = _validTo - def validTo_=(x: Period) { _validTo = x} - - def pos = rawpos - def setPos(pos: Position): this.type = { this.rawpos = pos; this } - def setName(name: Name): this.type = { this.name = asNameType(name) ; this } - - // Update the surrounding scopes - protected[this] def changeNameInOwners(name: Name) { - if (owner.isClass) { - var ifs = owner.infos - while (ifs != null) { - ifs.info.decls.rehash(this, name) - ifs = ifs.prev - } - } - } - - def rawFlagString(mask: Long): String = calculateFlagString(rawflags & mask) - def rawFlagString: String = rawFlagString(flagMask) - def debugFlagString: String = flagString(AllFlags) - - /** String representation of symbol's variance */ - def varianceString: String = - if (variance == 1) "+" - else if (variance == -1) "-" - else "" - - override def flagMask = - if (settings.debug.value && !isAbstractType) AllFlags - else if (owner.isRefinementClass) ExplicitFlags & ~OVERRIDE - else ExplicitFlags - - // make the error message more googlable - def flagsExplanationString = - if (isGADTSkolem) " (this is a GADT skolem)" - else "" - - def shortSymbolClass = getClass.getName.split('.').last.stripPrefix("Symbols$") - def symbolCreationString: String = ( - "%s%25s | %-40s | %s".format( - if (settings.uniqid.value) "%06d | ".format(id) else "", - shortSymbolClass, - name.decode + " in " + owner, - rawFlagString - ) - ) - -// ------ creators ------------------------------------------------------------------- - - final def newValue(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): TermSymbol = - newTermSymbol(name, pos, newFlags) - final def newVariable(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): TermSymbol = - newTermSymbol(name, pos, MUTABLE | newFlags) - final def newValueParameter(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): TermSymbol = - newTermSymbol(name, pos, PARAM | newFlags) - - /** Create local dummy for template (owner of local blocks) */ - final def newLocalDummy(pos: Position): TermSymbol = - newTermSymbol(nme.localDummyName(this), pos) setInfo NoType - final def newMethod(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): MethodSymbol = - createMethodSymbol(name, pos, METHOD | newFlags) - final def newMethodSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): MethodSymbol = - createMethodSymbol(name, pos, METHOD | newFlags) - final def newLabel(name: TermName, pos: Position = NoPosition): MethodSymbol = - newMethod(name, pos, LABEL) - - /** Propagates ConstrFlags (JAVA, specifically) from owner to constructor. */ - final def newConstructor(pos: Position, newFlags: Long = 0L): MethodSymbol = - newMethod(nme.CONSTRUCTOR, pos, getFlag(ConstrFlags) | newFlags) - - /** Static constructor with info set. */ - def newStaticConstructor(pos: Position): MethodSymbol = - newConstructor(pos, STATIC) setInfo UnitClass.tpe - - /** Instance constructor with info set. */ - def newClassConstructor(pos: Position): MethodSymbol = - newConstructor(pos) setInfo MethodType(Nil, this.tpe) - - def newLinkedModule(clazz: Symbol, newFlags: Long = 0L): ModuleSymbol = { - val m = newModuleSymbol(clazz.name.toTermName, clazz.pos, MODULE | newFlags) - connectModuleToClass(m, clazz.asInstanceOf[ClassSymbol]) - } - final def newModule(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = { - val m = newModuleSymbol(name, pos, newFlags | MODULE) - val clazz = newModuleClass(name.toTypeName, pos, m getFlag ModuleToClassFlags) - connectModuleToClass(m, clazz) - } - - final def newPackage(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = { - assert(name == nme.ROOT || isPackageClass, this) - newModule(name, pos, PackageFlags | newFlags) - } - - final def newThisSym(name: TermName = nme.this_, pos: Position = NoPosition): TermSymbol = - newTermSymbol(name, pos, SYNTHETIC) - - final def newImport(pos: Position): TermSymbol = - newTermSymbol(nme.IMPORT, pos) - - final def newModuleSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = - newTermSymbol(name, pos, newFlags).asInstanceOf[ModuleSymbol] - - final def newModuleAndClassSymbol(name: Name, pos: Position, flags: FlagSet): (ModuleSymbol, ClassSymbol) = { - val m = newModuleSymbol(name, pos, flags | MODULE) - val c = newModuleClass(name.toTypeName, pos, m getFlag ModuleToClassFlags) - connectModuleToClass(m, c) - (m, c) - } - - final def newPackageSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = - newTermSymbol(name, pos, newFlags).asInstanceOf[ModuleSymbol] - - final def newModuleClassSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleClassSymbol = - newClassSymbol(name, pos, newFlags).asInstanceOf[ModuleClassSymbol] - - final def newTypeSkolemSymbol(name: TypeName, origin: AnyRef, pos: Position = NoPosition, newFlags: Long = 0L): TypeSkolem = - createTypeSkolemSymbol(name, origin, pos, newFlags) - - /** @param pre type relative to which alternatives are seen. - * for instance: - * class C[T] { - * def m(x: T): T - * def m'(): T - * } - * val v: C[Int] - * - * Then v.m has symbol TermSymbol(flags = {OVERLOADED}, - * tpe = OverloadedType(C[Int], List(m, m'))) - * You recover the type of m doing a - * - * m.tpe.asSeenFrom(pre, C) (generally, owner of m, which is C here). - * - * or: - * - * pre.memberType(m) - */ - final def newOverloaded(pre: Type, alternatives: List[Symbol]): TermSymbol = ( - newTermSymbol(alternatives.head.name.toTermName, alternatives.head.pos, OVERLOADED) - setInfo OverloadedType(pre, alternatives) - ) - - final def newErrorValue(name: TermName): TermSymbol = - newTermSymbol(name, pos, SYNTHETIC | IS_ERROR) setInfo ErrorType - - /** Symbol of a type definition type T = ... - */ - final def newAliasType(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): AliasTypeSymbol = - createAliasTypeSymbol(name, pos, newFlags) - - /** Symbol of an abstract type type T >: ... <: ... - */ - final def newAbstractType(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): AbstractTypeSymbol = - createAbstractTypeSymbol(name, pos, DEFERRED | newFlags) - - /** Symbol of a type parameter - */ - final def newTypeParameter(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol = - newAbstractType(name, pos, PARAM | newFlags) - -// is defined in SymbolCreations -// final def newTypeSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol = -// (if ((newFlags & DEFERRED) != 0) new AbstractTypeSymbol(this, pos, name) -// else new AbstractTypeSymbol(this, pos, name)) setFlag newFlags - - /** Symbol of an existential type T forSome { ... } - */ - final def newExistential(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol = - newAbstractType(name, pos, EXISTENTIAL | newFlags) - - /** Synthetic value parameters when parameter symbols are not available - */ - final def newSyntheticValueParamss(argtypess: List[List[Type]]): List[List[TermSymbol]] = { - var cnt = 0 - def freshName() = { cnt += 1; nme.syntheticParamName(cnt) } - mmap(argtypess)(tp => newValueParameter(freshName(), owner.pos.focus, SYNTHETIC) setInfo tp) - } - - def newSyntheticTypeParam(): TypeSymbol = newSyntheticTypeParam("T0", 0L) - def newSyntheticTypeParam(name: String, newFlags: Long): TypeSymbol = newTypeParameter(newTypeName(name), NoPosition, newFlags) setInfo TypeBounds.empty - def newSyntheticTypeParams(num: Int): List[TypeSymbol] = (0 until num).toList map (n => newSyntheticTypeParam("T" + n, 0L)) - - /** Create a new existential type skolem with this symbol its owner, - * based on the given symbol and origin. - */ - def newExistentialSkolem(basis: Symbol, origin: AnyRef): TypeSkolem = { - val skolem = newTypeSkolemSymbol(basis.name.toTypeName, origin, basis.pos, (basis.flags | EXISTENTIAL) & ~PARAM) - skolem setInfo (basis.info cloneInfo skolem) - } - - // flags set up to maintain TypeSkolem's invariant: origin.isInstanceOf[Symbol] == !hasFlag(EXISTENTIAL) - // CASEACCESSOR | SYNTHETIC used to single this symbol out in deskolemizeGADT - def newGADTSkolem(name: TypeName, origin: Symbol, info: Type): TypeSkolem = - newTypeSkolemSymbol(name, origin, origin.pos, origin.flags & ~(EXISTENTIAL | PARAM) | CASEACCESSOR | SYNTHETIC) setInfo info - - final def freshExistential(suffix: String): TypeSymbol = - newExistential(freshExistentialName(suffix), pos) - - /** Synthetic value parameters when parameter symbols are not available. - * Calling this method multiple times will re-use the same parameter names. - */ - final def newSyntheticValueParams(argtypes: List[Type]): List[TermSymbol] = - newSyntheticValueParamss(List(argtypes)).head - - /** Synthetic value parameter when parameter symbol is not available. - * Calling this method multiple times will re-use the same parameter name. - */ - final def newSyntheticValueParam(argtype: Type): Symbol = - newSyntheticValueParams(List(argtype)).head - - /** Type skolems are type parameters ''seen from the inside'' - * Assuming a polymorphic method m[T], its type is a PolyType which has a TypeParameter - * with name `T` in its typeParams list. While type checking the parameters, result type and - * body of the method, there's a local copy of `T` which is a TypeSkolem. - */ - final def newTypeSkolem: TypeSkolem = - owner.newTypeSkolemSymbol(name.toTypeName, this, pos, flags) - - final def newClass(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ClassSymbol = - newClassSymbol(name, pos, newFlags) - - /** A new class with its info set to a ClassInfoType with given scope and parents. */ - def newClassWithInfo(name: TypeName, parents: List[Type], scope: Scope, pos: Position = NoPosition, newFlags: Long = 0L): ClassSymbol = { - val clazz = newClass(name, pos, newFlags) - clazz setInfo ClassInfoType(parents, scope, clazz) - } - final def newErrorClass(name: TypeName): ClassSymbol = - newClassWithInfo(name, Nil, new ErrorScope(this), pos, SYNTHETIC | IS_ERROR) - - final def newModuleClass(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleClassSymbol = - newModuleClassSymbol(name, pos, newFlags | MODULE) - - final def newAnonymousFunctionClass(pos: Position = NoPosition, newFlags: Long = 0L): ClassSymbol = - newClassSymbol(tpnme.ANON_FUN_NAME, pos, FINAL | SYNTHETIC | newFlags) - - final def newAnonymousFunctionValue(pos: Position, newFlags: Long = 0L): TermSymbol = - newTermSymbol(nme.ANON_FUN_NAME, pos, SYNTHETIC | newFlags) setInfo NoType - - def newImplClass(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ClassSymbol = { - newClassSymbol(name, pos, newFlags | IMPLCLASS) - } - - /** Refinement types P { val x: String; type T <: Number } - * also have symbols, they are refinementClasses - */ - final def newRefinementClass(pos: Position): RefinementClassSymbol = - createRefinementClassSymbol(pos, 0L) - - /** Create a new getter for current symbol (which must be a field) - */ - final def newGetter: MethodSymbol = ( - owner.newMethod(nme.getterName(name.toTermName), NoPosition, getterFlags(flags)) - setPrivateWithin privateWithin - setInfo MethodType(Nil, tpe) - ) - - final def newErrorSymbol(name: Name): Symbol = name match { - case x: TypeName => newErrorClass(x) - case x: TermName => newErrorValue(x) - } - - @deprecated("Use the other signature", "2.10.0") - def newClass(pos: Position, name: TypeName): Symbol = newClass(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newModuleClass(pos: Position, name: TypeName): Symbol = newModuleClass(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newLabel(pos: Position, name: TermName): MethodSymbol = newLabel(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newValue(pos: Position, name: TermName): TermSymbol = newTermSymbol(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newAliasType(pos: Position, name: TypeName): Symbol = newAliasType(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newAbstractType(pos: Position, name: TypeName): Symbol = newAbstractType(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newExistential(pos: Position, name: TypeName): Symbol = newExistential(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newMethod(pos: Position, name: TermName): MethodSymbol = newMethod(name, pos) - -// ----- locking and unlocking ------------------------------------------------------ - - // True if the symbol is unlocked. - // True if the symbol is locked but still below the allowed recursion depth. - // False otherwise - private[scala] def lockOK: Boolean = { - ((_rawflags & LOCKED) == 0L) || - ((settings.Yrecursion.value != 0) && - (recursionTable get this match { - case Some(n) => (n <= settings.Yrecursion.value) - case None => true })) - } - - // Lock a symbol, using the handler if the recursion depth becomes too great. - private[scala] def lock(handler: => Unit): Boolean = { - if ((_rawflags & LOCKED) != 0L) { - if (settings.Yrecursion.value != 0) { - recursionTable get this match { - case Some(n) => - if (n > settings.Yrecursion.value) { - handler - false - } else { - recursionTable += (this -> (n + 1)) - true - } - case None => - recursionTable += (this -> 1) - true - } - } else { handler; false } - } else { - _rawflags |= LOCKED - true -// activeLocks += 1 -// lockedSyms += this - } - } - - // Unlock a symbol - private[scala] def unlock() = { - if ((_rawflags & LOCKED) != 0L) { -// activeLocks -= 1 -// lockedSyms -= this - _rawflags &= ~LOCKED - if (settings.Yrecursion.value != 0) - recursionTable -= this - } - } - -// ----- tests ---------------------------------------------------------------------- - - def isAliasType = false - def isAbstractType = false - def isSkolem = false - - /** A Type, but not a Class. */ - def isNonClassType = false - - /** The bottom classes are Nothing and Null, found in Definitions. */ - def isBottomClass = false - def isSpecialized = this hasFlag SPECIALIZED - - /** These are all tests for varieties of ClassSymbol, which has these subclasses: - * - ModuleClassSymbol - * - RefinementClassSymbol - * - PackageClassSymbol (extends ModuleClassSymbol) - */ - def isAbstractClass = false - def isAnonOrRefinementClass = false - def isAnonymousClass = false - def isCaseClass = false - def isConcreteClass = false - def isImplClass = false // the implementation class of a trait - def isJavaInterface = false - def isModuleClass = false - def isNumericValueClass = false - def isPrimitiveValueClass = false - def isRefinementClass = false - override def isTrait = false - - /** Qualities of Types, always false for TermSymbols. - */ - def isContravariant = false - def isCovariant = false - def isExistentialQuantified = false - def isExistentialSkolem = false - def isExistentiallyBound = false - def isGADTSkolem = false - def isTypeParameter = false - def isTypeParameterOrSkolem = false - def isTypeSkolem = false - def isTypeMacro = false - - /** Qualities of Terms, always false for TypeSymbols. - */ - def isAccessor = false - def isBridge = false - def isCapturedVariable = false - def isClassConstructor = false - def isConstructor = false - def isEarlyInitialized = false - def isGetter = false - def isLocalDummy = false - def isMixinConstructor = false - def isOverloaded = false - def isSetter = false - def isSetterParameter = false - def isValue = false - def isValueParameter = false - def isVariable = false - override def hasDefault = false - def isTermMacro = false - - /** Qualities of MethodSymbols, always false for TypeSymbols - * and other TermSymbols. - */ - def isCaseAccessorMethod = false - def isLiftedMethod = false - def isSourceMethod = false - def isVarargsMethod = false - override def isLabel = false - - /** Package/package object tests */ - def isPackageClass = false - def isPackageObject = false - def isPackageObjectClass = false - def isPackageObjectOrClass = isPackageObject || isPackageObjectClass - def isModuleOrModuleClass = isModule || isModuleClass - - /** Overridden in custom objects in Definitions */ - def isRoot = false - def isRootPackage = false - def isRootSymbol = false // RootPackage and RootClass. TODO: also NoSymbol. - def isEmptyPackage = false - def isEmptyPackageClass = false - - /** Is this symbol an effective root for fullname string? - */ - def isEffectiveRoot = false - - /** For RootClass, this is EmptyPackageClass. For all other symbols, - * the symbol itself. - */ - def ownerOfNewSymbols = this - - final def isLazyAccessor = isLazy && lazyAccessor != NoSymbol - final def isOverridableMember = !(isClass || isEffectivelyFinal) && (this ne NoSymbol) && owner.isClass - - /** Does this symbol denote a wrapper created by the repl? */ - final def isInterpreterWrapper = ( - (this hasFlag MODULE) - && owner.isPackageClass - && nme.isReplWrapperName(name) - ) - @inline final def getFlag(mask: Long): Long = flags & mask - /** Does symbol have ANY flag in `mask` set? */ - @inline final def hasFlag(mask: Long): Boolean = (flags & mask) != 0 - /** Does symbol have ALL the flags in `mask` set? */ - @inline final def hasAllFlags(mask: Long): Boolean = (flags & mask) == mask - - def setFlag(mask: Long): this.type = { _rawflags |= mask ; this } - def resetFlag(mask: Long): this.type = { _rawflags &= ~mask ; this } - def resetFlags() { rawflags &= TopLevelCreationFlags } - - /** Default implementation calls the generic string function, which - * will print overloaded flags as . Subclasses - * of Symbol refine. - */ - override def resolveOverloadedFlag(flag: Long): String = Flags.flagToString(flag) - - /** Set the symbol's flags to the given value, asserting - * that the previous value was 0. - */ - def initFlags(mask: Long): this.type = { - assert(rawflags == 0L, symbolCreationString) - _rawflags = mask - this - } - - final def flags: Long = { - val fs = _rawflags & phase.flagMask - (fs | ((fs & LateFlags) >>> LateShift)) & ~(fs >>> AntiShift) - } - def flags_=(fs: Long) = _rawflags = fs - def rawflags_=(x: Long) { _rawflags = x } - - final def hasGetter = isTerm && nme.isLocalName(name) - - final def isInitializedToDefault = !isType && hasAllFlags(DEFAULTINIT | ACCESSOR) - final def isStaticModule = isModule && isStatic && !isMethod - final def isThisSym = isTerm && owner.thisSym == this - final def isError = hasFlag(IS_ERROR) - final def isErroneous = isError || isInitialized && tpe.isErroneous - - def isHigherOrderTypeParameter = owner.isTypeParameterOrSkolem - - // class C extends D( { class E { ... } ... } ). Here, E is a class local to a constructor - def isClassLocalToConstructor = false - - final def isDerivedValueClass = - isClass && info.firstParent.typeSymbol == AnyValClass && !isPrimitiveValueClass - - final def isMethodWithExtension = - isMethod && owner.isDerivedValueClass && !isParamAccessor && !isConstructor && !hasFlag(SUPERACCESSOR) - - final def isAnonymousFunction = isSynthetic && (name containsName tpnme.ANON_FUN_NAME) - final def isDefinedInPackage = effectiveOwner.isPackageClass - final def needsFlatClasses = phase.flatClasses && rawowner != NoSymbol && !rawowner.isPackageClass - - /** change name by appending $$ - * Do the same for any accessed symbols or setters/getters. - * Implementation in TermSymbol. - */ - def expandName(base: Symbol) { } - - // In java.lang, Predef, or scala package/package object - def isInDefaultNamespace = UnqualifiedOwners(effectiveOwner) - - /** The owner, skipping package objects. - */ - def effectiveOwner = owner.skipPackageObject - - /** If this is a package object or its implementing class, its owner: otherwise this. - */ - def skipPackageObject: Symbol = this - - /** If this is a constructor, its owner: otherwise this. - */ - final def skipConstructor: Symbol = if (isConstructor) owner else this - - /** Conditions where we omit the prefix when printing a symbol, to avoid - * unpleasantries like Predef.String, $iw.$iw.Foo and .Bippy. - */ - final def isOmittablePrefix = /*!settings.debug.value &&*/ ( - UnqualifiedOwners(skipPackageObject) - || isEmptyPrefix - ) - def isEmptyPrefix = ( - isEffectiveRoot // has no prefix for real, or - || isAnonOrRefinementClass // has uninteresting or prefix - || nme.isReplWrapperName(name) // has ugly $iw. prefix (doesn't call isInterpreterWrapper due to nesting) - ) - def isFBounded = info match { - case TypeBounds(_, _) => info.baseTypeSeq exists (_ contains this) - case _ => false - } - - /** Is symbol a monomorphic type? - * assumption: if a type starts out as monomorphic, it will not acquire - * type parameters in later phases. - */ - final def isMonomorphicType = - isType && { - val info = originalInfo - info.isComplete && !info.isHigherKinded - } - - def isStrictFP = hasAnnotation(ScalaStrictFPAttr) || (enclClass hasAnnotation ScalaStrictFPAttr) - def isSerializable = ( - info.baseClasses.exists(p => p == SerializableClass || p == JavaSerializableClass) - || hasAnnotation(SerializableAttr) // last part can be removed, @serializable annotation is deprecated - ) - def hasBridgeAnnotation = hasAnnotation(BridgeClass) - def isDeprecated = hasAnnotation(DeprecatedAttr) - def deprecationMessage = getAnnotation(DeprecatedAttr) flatMap (_ stringArg 0) - def deprecationVersion = getAnnotation(DeprecatedAttr) flatMap (_ stringArg 1) - def deprecatedParamName = getAnnotation(DeprecatedNameAttr) flatMap (_ symbolArg 0) - - // !!! when annotation arguments are not literal strings, but any sort of - // assembly of strings, there is a fair chance they will turn up here not as - // Literal(const) but some arbitrary AST. However nothing in the compiler - // prevents someone from writing a @migration annotation with a calculated - // string. So this needs attention. For now the fact that migration is - // private[scala] ought to provide enough protection. - def hasMigrationAnnotation = hasAnnotation(MigrationAnnotationClass) - def migrationMessage = getAnnotation(MigrationAnnotationClass) flatMap { _.stringArg(0) } - def migrationVersion = getAnnotation(MigrationAnnotationClass) flatMap { _.stringArg(1) } - def elisionLevel = getAnnotation(ElidableMethodClass) flatMap { _.intArg(0) } - def implicitNotFoundMsg = getAnnotation(ImplicitNotFoundClass) flatMap { _.stringArg(0) } - - /** Is this symbol an accessor method for outer? */ - final def isOuterAccessor = { - hasFlag(STABLE | SYNTHETIC) && - originalName == nme.OUTER - } - - /** Is this symbol an accessor method for outer? */ - final def isOuterField = { - hasFlag(SYNTHETIC) && - originalName == nme.OUTER_LOCAL - } - - /** Does this symbol denote a stable value? */ - def isStable = false - - /** Does this symbol denote the primary constructor of its enclosing class? */ - final def isPrimaryConstructor = - isConstructor && owner.primaryConstructor == this - - /** Does this symbol denote an auxiliary constructor of its enclosing class? */ - final def isAuxiliaryConstructor = - isConstructor && !isPrimaryConstructor - - /** Is this symbol a synthetic apply or unapply method in a companion object of a case class? */ - final def isCaseApplyOrUnapply = - isMethod && isCase && isSynthetic - - /** Is this symbol a trait which needs an implementation class? */ - final def needsImplClass = ( - isTrait - && (!isInterface || hasFlag(lateINTERFACE)) - && !isImplClass - ) - - /** Is this a symbol which exists only in the implementation class, not in its trait? */ - final def isImplOnly = isPrivate || ( - (owner.isTrait || owner.isImplClass) && ( - hasAllFlags(LIFTED | MODULE | METHOD) - || isConstructor - || hasFlag(notPRIVATE | LIFTED) && !hasFlag(ACCESSOR | SUPERACCESSOR | MODULE) - ) - ) - final def isModuleVar = hasFlag(MODULEVAR) - - /** Is this symbol static (i.e. with no outer instance)? - * Q: When exactly is a sym marked as STATIC? - * A: If it's a member of a toplevel object, or of an object contained in a toplevel object, or any number of levels deep. - * http://groups.google.com/group/scala-internals/browse_thread/thread/d385bcd60b08faf6 - */ - def isStatic = (this hasFlag STATIC) || owner.isStaticOwner - - /** Is this symbol a static constructor? */ - final def isStaticConstructor: Boolean = - isStaticMember && isClassConstructor - - /** Is this symbol a static member of its class? (i.e. needs to be implemented as a Java static?) */ - final def isStaticMember: Boolean = - hasFlag(STATIC) || owner.isImplClass - - /** Does this symbol denote a class that defines static symbols? */ - final def isStaticOwner: Boolean = - isPackageClass || isModuleClass && isStatic - - def isTopLevelModule = hasFlag(MODULE) && owner.isPackageClass - - /** Is this symbol effectively final? I.e, it cannot be overridden */ - final def isEffectivelyFinal: Boolean = ( - (this hasFlag FINAL | PACKAGE) - || isModuleOrModuleClass && (owner.isPackageClass || !settings.overrideObjects.value) - || isTerm && ( - isPrivate - || isLocal - || owner.isClass && owner.isEffectivelyFinal - ) - ) - - /** Is this symbol locally defined? I.e. not accessed from outside `this` instance */ - final def isLocal: Boolean = owner.isTerm - - /** Is this symbol a constant? */ - final def isConstant: Boolean = isStable && isConstantType(tpe.resultType) - - /** Is this class nested in another class or module (not a package)? */ - def isNestedClass = false - - /** Is this class locally defined? - * A class is local, if - * - it is anonymous, or - * - its owner is a value - * - it is defined within a local class - */ - def isLocalClass = false - - def isStableClass = false - -/* code for fixing nested objects - override final def isModuleClass: Boolean = - super.isModuleClass && !isExpandedModuleClass -*/ - /** Is this class or type defined as a structural refinement type? - */ - final def isStructuralRefinement: Boolean = - (isClass || isType || isModule) && info.normalize/*.underlying*/.isStructuralRefinement - - /** Is this a term symbol only defined in a refinement (so that it needs - * to be accessed by reflection)? - */ - def isOnlyRefinementMember: Boolean = - isTerm && // type members are not affected - owner.isRefinementClass && // owner must be a refinement class - (owner.info decl name) == this && // symbol must be explicitly declared in the refinement (not synthesized from glb) - allOverriddenSymbols.isEmpty && // symbol must not override a symbol in a base class - !isConstant // symbol must not be a constant. Question: Can we exclude @inline methods as well? - - final def isStructuralRefinementMember = owner.isStructuralRefinement && isPossibleInRefinement && isPublic - final def isPossibleInRefinement = !isConstructor && !isOverridingSymbol - - /** Is this symbol a member of class `clazz`? */ - def isMemberOf(clazz: Symbol) = - clazz.info.member(name).alternatives contains this - - /** A a member of class `base` is incomplete if - * (1) it is declared deferred or - * (2) it is abstract override and its super symbol in `base` is - * nonexistent or incomplete. - * - * @param base ... - * @return ... - */ - final def isIncompleteIn(base: Symbol): Boolean = - this.isDeferred || - (this hasFlag ABSOVERRIDE) && { - val supersym = superSymbol(base) - supersym == NoSymbol || supersym.isIncompleteIn(base) - } - - // Does not always work if the rawInfo is a SourcefileLoader, see comment - // in "def coreClassesFirst" in Global. - def exists = !owner.isPackageClass || { rawInfo.load(this); rawInfo != NoType } - - final def isInitialized: Boolean = - validTo != NoPeriod - - // [Eugene] todo. needs to be reviewed and [only then] rewritten without explicit returns - /** Determines whether this symbol can be loaded by subsequent reflective compilation */ - final def isLocatable: Boolean = { - if (this == NoSymbol) return false - if (isRoot || isRootPackage) return true - - if (!owner.isLocatable) return false - if (owner.isTerm) return false - if (isLocalDummy) return false - - if (isType && isNonClassType) return false - if (isRefinementClass) return false - return true - } - - // [Eugene] is it a good idea to add ``dealias'' to Symbol? - /** Expands type aliases */ - def dealias: Symbol = this - - /** The variance of this symbol as an integer */ - final def variance: Int = - if (isCovariant) 1 - else if (isContravariant) -1 - else 0 - - /** The sequence number of this parameter symbol among all type - * and value parameters of symbol's owner. -1 if symbol does not - * appear among the parameters of its owner. - */ - def paramPos: Int = { - def searchIn(tpe: Type, base: Int): Int = { - def searchList(params: List[Symbol], fallback: Type): Int = { - val idx = params indexOf this - if (idx >= 0) idx + base - else searchIn(fallback, base + params.length) - } - tpe match { - case PolyType(tparams, res) => searchList(tparams, res) - case MethodType(params, res) => searchList(params, res) - case _ => -1 - } - } - searchIn(owner.info, 0) - } - -// ------ owner attribute -------------------------------------------------------------- - - def owner: Symbol = rawowner - // TODO - don't allow the owner to be changed without checking invariants, at least - // when under some flag. Define per-phase invariants for owner/owned relationships, - // e.g. after flatten all classes are owned by package classes, there are lots and - // lots of these to be declared (or more realistically, discovered.) - def owner_=(owner: Symbol) { - // don't keep the original owner in presentation compiler runs - // (the map will grow indefinitely, and the only use case is the - // backend). - if (!forInteractive) { - if (originalOwner contains this) () - else originalOwner(this) = rawowner - } - assert(isCompilerUniverse, "owner_= is not thread-safe; cannot be run in reflexive code") - if (traceSymbolActivity) - traceSymbols.recordNewSymbolOwner(this, owner) - _rawowner = owner - } - - def ownerChain: List[Symbol] = this :: owner.ownerChain - def originalOwnerChain: List[Symbol] = this :: originalOwner.getOrElse(this, rawowner).originalOwnerChain - - // Non-classes skip self and return rest of owner chain; overridden in ClassSymbol. - def enclClassChain: List[Symbol] = owner.enclClassChain - - def ownersIterator: Iterator[Symbol] = new Iterator[Symbol] { - private var current = Symbol.this - def hasNext = current ne NoSymbol - def next = { val r = current; current = current.owner; r } - } - - /** Same as `ownerChain contains sym` but more efficient, and - * with a twist for refinement classes (see RefinementClassSymbol.) - */ - def hasTransOwner(sym: Symbol): Boolean = { - var o = this - while ((o ne sym) && (o ne NoSymbol)) o = o.owner - (o eq sym) - } - -// ------ name attribute -------------------------------------------------------------- - - /** If this symbol has an expanded name, its original name, otherwise its name itself. - * @see expandName - */ - def originalName: Name = nme.originalName(name) - - /** The name of the symbol before decoding, e.g. `\$eq\$eq` instead of `==`. - */ - def encodedName: String = name.toString - - /** The decoded name of the symbol, e.g. `==` instead of `\$eq\$eq`. - */ - def decodedName: String = nme.dropLocalSuffix(name).decode - - private def addModuleSuffix(n: Name): Name = - if (needsModuleSuffix) n append nme.MODULE_SUFFIX_STRING else n - - def moduleSuffix: String = ( - if (needsModuleSuffix) nme.MODULE_SUFFIX_STRING - else "" - ) - /** Whether this symbol needs nme.MODULE_SUFFIX_STRING (aka $) appended on the java platform. - */ - def needsModuleSuffix = ( - hasModuleFlag - && !isMethod - && !isImplClass - && !isJavaDefined - ) - /** These should be moved somewhere like JavaPlatform. - */ - def javaSimpleName: Name = addModuleSuffix(nme.dropLocalSuffix(simpleName)) - def javaBinaryName: Name = addModuleSuffix(fullNameInternal('/')) - def javaClassName: String = addModuleSuffix(fullNameInternal('.')).toString - - /** The encoded full path name of this symbol, where outer names and inner names - * are separated by `separator` characters. - * Never translates expansions of operators back to operator symbol. - * Never adds id. - * Drops package objects. - */ - final def fullName(separator: Char): String = fullNameAsName(separator).toString - - /** Doesn't drop package objects, for those situations (e.g. classloading) - * where the true path is needed. - */ - private def fullNameInternal(separator: Char): Name = ( - if (isRoot || isRootPackage || this == NoSymbol) name - else if (owner.isEffectiveRoot) name - else effectiveOwner.enclClass.fullNameAsName(separator) append separator append name - ) - - def fullNameAsName(separator: Char): Name = nme.dropLocalSuffix(fullNameInternal(separator)) - - /** The encoded full path name of this symbol, where outer names and inner names - * are separated by periods. - */ - final def fullName: String = fullName('.') - - /** - * Symbol creation implementations. - */ - - protected def createAbstractTypeSymbol(name: TypeName, pos: Position, newFlags: Long): AbstractTypeSymbol = - new AbstractTypeSymbol(this, pos, name) initFlags newFlags - - protected def createAliasTypeSymbol(name: TypeName, pos: Position, newFlags: Long): AliasTypeSymbol = - new AliasTypeSymbol(this, pos, name) initFlags newFlags - - protected def createTypeSkolemSymbol(name: TypeName, origin: AnyRef, pos: Position, newFlags: Long): TypeSkolem = - new TypeSkolem(this, pos, name, origin) initFlags newFlags - - protected def createClassSymbol(name: TypeName, pos: Position, newFlags: Long): ClassSymbol = - new ClassSymbol(this, pos, name) initFlags newFlags - - protected def createModuleClassSymbol(name: TypeName, pos: Position, newFlags: Long): ModuleClassSymbol = - new ModuleClassSymbol(this, pos, name) initFlags newFlags - - protected def createPackageClassSymbol(name: TypeName, pos: Position, newFlags: Long): PackageClassSymbol = - new PackageClassSymbol(this, pos, name) initFlags newFlags - - protected def createRefinementClassSymbol(pos: Position, newFlags: Long): RefinementClassSymbol = - new RefinementClassSymbol(this, pos) initFlags newFlags - - protected def createPackageObjectClassSymbol(pos: Position, newFlags: Long): PackageObjectClassSymbol = - new PackageObjectClassSymbol(this, pos) initFlags newFlags - - protected def createImplClassSymbol(name: TypeName, pos: Position, newFlags: Long): ClassSymbol = - new ClassSymbol(this, pos, name) with ImplClassSymbol initFlags newFlags - - protected def createTermSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = - new TermSymbol(this, pos, name) initFlags newFlags - - protected def createMethodSymbol(name: TermName, pos: Position, newFlags: Long): MethodSymbol = - new MethodSymbol(this, pos, name) initFlags newFlags - - protected def createModuleSymbol(name: TermName, pos: Position, newFlags: Long): ModuleSymbol = - new ModuleSymbol(this, pos, name) initFlags newFlags - - protected def createPackageSymbol(name: TermName, pos: Position, newFlags: Long): ModuleSymbol = - new ModuleSymbol(this, pos, name) initFlags newFlags - - protected def createValueParameterSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = - new TermSymbol(this, pos, name) initFlags newFlags - - protected def createValueMemberSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = - new TermSymbol(this, pos, name) initFlags newFlags - - final def newTermSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): TermSymbol = { - if ((newFlags & METHOD) != 0) - createMethodSymbol(name, pos, newFlags) - else if ((newFlags & PACKAGE) != 0) - createPackageSymbol(name, pos, newFlags | PackageFlags) - else if ((newFlags & MODULE) != 0) - createModuleSymbol(name, pos, newFlags) - else if ((newFlags & PARAM) != 0) - createValueParameterSymbol(name, pos, newFlags) - else - createValueMemberSymbol(name, pos, newFlags) - } - - final def newClassSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ClassSymbol = { - if (name == tpnme.REFINE_CLASS_NAME) - createRefinementClassSymbol(pos, newFlags) - else if ((newFlags & PACKAGE) != 0) - createPackageClassSymbol(name, pos, newFlags | PackageFlags) - else if (name == tpnme.PACKAGE) - createPackageObjectClassSymbol(pos, newFlags) - else if ((newFlags & MODULE) != 0) - createModuleClassSymbol(name, pos, newFlags) - else if ((newFlags & IMPLCLASS) != 0) - createImplClassSymbol(name, pos, newFlags) - else - createClassSymbol(name, pos, newFlags) - } - - final def newNonClassSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol = { - if ((newFlags & DEFERRED) != 0) - createAbstractTypeSymbol(name, pos, newFlags) - else - createAliasTypeSymbol(name, pos, newFlags) - } - - def newTypeSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol = - newNonClassSymbol(name, pos, newFlags) - - /** The class or term up to which this symbol is accessible, - * or RootClass if it is public. As java protected statics are - * otherwise completely inaccessible in scala, they are treated - * as public. - */ - def accessBoundary(base: Symbol): Symbol = { - if (hasFlag(PRIVATE) || isLocal) owner - else if (hasAllFlags(PROTECTED | STATIC | JAVA)) enclosingRootClass - else if (hasAccessBoundary && !phase.erasedTypes) privateWithin - else if (hasFlag(PROTECTED)) base - else enclosingRootClass - } - - def isLessAccessibleThan(other: Symbol): Boolean = { - val tb = this.accessBoundary(owner) - val ob1 = other.accessBoundary(owner) - val ob2 = ob1.linkedClassOfClass - var o = tb - while (o != NoSymbol && o != ob1 && o != ob2) { - o = o.owner - } - o != NoSymbol && o != tb - } - - /** See comment in HasFlags for how privateWithin combines with flags. - */ - private[this] var _privateWithin: Symbol = _ - def privateWithin = _privateWithin - def privateWithin_=(sym: Symbol) { _privateWithin = sym } - def setPrivateWithin(sym: Symbol): this.type = { privateWithin_=(sym) ; this } - - /** Does symbol have a private or protected qualifier set? */ - final def hasAccessBoundary = (privateWithin != null) && (privateWithin != NoSymbol) - -// ------ info and type ------------------------------------------------------------------- - - private[Symbols] var infos: TypeHistory = null - def originalInfo = { - if (infos eq null) null - else { - var is = infos - while (is.prev ne null) { is = is.prev } - is.info - } - } - - /** Get type. The type of a symbol is: - * for a type symbol, the type corresponding to the symbol itself, - * @M you should use tpeHK for a type symbol with type parameters if - * the kind of the type need not be *, as tpe introduces dummy arguments - * to generate a type of kind * - * for a term symbol, its usual type. - * See the tpe/tpeHK overrides in TypeSymbol for more. - */ - def tpe: Type = info - def tpeHK: Type = tpe - - /** Get type info associated with symbol at current phase, after - * ensuring that symbol is initialized (i.e. type is completed). - */ - def info: Type = try { - var cnt = 0 - while (validTo == NoPeriod) { - //if (settings.debug.value) System.out.println("completing " + this);//DEBUG - assert(infos ne null, this.name) - assert(infos.prev eq null, this.name) - val tp = infos.info - //if (settings.debug.value) System.out.println("completing " + this.rawname + tp.getClass());//debug - - if ((_rawflags & LOCKED) != 0L) { // rolled out once for performance - lock { - setInfo(ErrorType) - throw CyclicReference(this, tp) - } - } else { - _rawflags |= LOCKED -// activeLocks += 1 - // lockedSyms += this - } - val current = phase - try { - phase = phaseOf(infos.validFrom) - tp.complete(this) - } finally { - unlock() - phase = current - } - cnt += 1 - // allow for two completions: - // one: sourceCompleter to LazyType, two: LazyType to completed type - if (cnt == 3) abort("no progress in completing " + this + ":" + tp) - } - rawInfo - } - catch { - case ex: CyclicReference => - debugwarn("... hit cycle trying to complete " + this.fullLocationString) - throw ex - } - - def info_=(info: Type) { - assert(info ne null) - infos = TypeHistory(currentPeriod, info, null) - unlock() - _validTo = if (info.isComplete) currentPeriod else NoPeriod - } - - /** Set initial info. */ - def setInfo(info: Type): this.type = { info_=(info); this } - /** Modifies this symbol's info in place. */ - def modifyInfo(f: Type => Type): this.type = setInfo(f(info)) - /** Substitute second list of symbols for first in current info. */ - def substInfo(syms0: List[Symbol], syms1: List[Symbol]): this.type = - if (syms0.isEmpty) this - else modifyInfo(_.substSym(syms0, syms1)) - - def setInfoOwnerAdjusted(info: Type): this.type = setInfo(info atOwner this) - - /** Set the info and enter this symbol into the owner's scope. */ - def setInfoAndEnter(info: Type): this.type = { - setInfo(info) - owner.info.decls enter this - this - } - - /** Set new info valid from start of this phase. */ - def updateInfo(info: Type): Symbol = { - val pid = phaseId(infos.validFrom) - assert(pid <= phase.id, (pid, phase.id)) - if (pid == phase.id) infos = infos.prev - infos = TypeHistory(currentPeriod, info, infos) - _validTo = if (info.isComplete) currentPeriod else NoPeriod - this - } - - def hasRawInfo: Boolean = infos ne null - def hasCompleteInfo = hasRawInfo && rawInfo.isComplete - - /** Return info without checking for initialization or completing */ - def rawInfo: Type = { - var infos = this.infos - assert(infos != null) - val curPeriod = currentPeriod - val curPid = phaseId(curPeriod) - - if (validTo != NoPeriod) { - // skip any infos that concern later phases - while (curPid < phaseId(infos.validFrom) && infos.prev != null) - infos = infos.prev - - if (validTo < curPeriod) { - // adapt any infos that come from previous runs - val current = phase - try { - infos = adaptInfos(infos) - - //assert(runId(validTo) == currentRunId, name) - //assert(runId(infos.validFrom) == currentRunId, name) - - if (validTo < curPeriod) { - var itr = infoTransformers.nextFrom(phaseId(validTo)) - infoTransformers = itr; // caching optimization - while (itr.pid != NoPhase.id && itr.pid < current.id) { - phase = phaseWithId(itr.pid) - val info1 = itr.transform(this, infos.info) - if (info1 ne infos.info) { - infos = TypeHistory(currentPeriod + 1, info1, infos) - this.infos = infos - } - _validTo = currentPeriod + 1 // to enable reads from same symbol during info-transform - itr = itr.next - } - _validTo = if (itr.pid == NoPhase.id) curPeriod - else period(currentRunId, itr.pid) - } - } finally { - phase = current - } - } - } - infos.info - } - - // adapt to new run in fsc. - private def adaptInfos(infos: TypeHistory): TypeHistory = { - assert(isCompilerUniverse) - if (infos == null || runId(infos.validFrom) == currentRunId) { - infos - } else { - val prev1 = adaptInfos(infos.prev) - if (prev1 ne infos.prev) prev1 - else { - val pid = phaseId(infos.validFrom) - - _validTo = period(currentRunId, pid) - phase = phaseWithId(pid) - - val info1 = ( - if (isPackageClass) infos.info - else adaptToNewRunMap(infos.info) - ) - if (info1 eq infos.info) { - infos.validFrom = validTo - infos - } else { - this.infos = TypeHistory(validTo, info1, prev1) - this.infos - } - } - } - } - - /** Initialize the symbol */ - final def initialize: this.type = { - if (!isInitialized) info - this - } - - /** Was symbol's type updated during given phase? */ - final def isUpdatedAt(pid: Phase#Id): Boolean = { - assert(isCompilerUniverse) - var infos = this.infos - while ((infos ne null) && phaseId(infos.validFrom) != pid + 1) infos = infos.prev - infos ne null - } - - /** Was symbol's type updated during given phase? */ - final def hasTypeAt(pid: Phase#Id): Boolean = { - assert(isCompilerUniverse) - var infos = this.infos - while ((infos ne null) && phaseId(infos.validFrom) > pid) infos = infos.prev - infos ne null - } - - /** Modify term symbol's type so that a raw type C is converted to an existential C[_] - * - * This is done in checkAccessible and overriding checks in refchecks - * We can't do this on class loading because it would result in infinite cycles. - */ - final def cookJavaRawInfo() { - if (hasFlag(TRIEDCOOKING)) return else setFlag(TRIEDCOOKING) // only try once... - val oldInfo = info - doCookJavaRawInfo() - } - - protected def doCookJavaRawInfo(): Unit - - /** The type constructor of a symbol is: - * For a type symbol, the type corresponding to the symbol itself, - * excluding parameters. - * Not applicable for term symbols. - */ - def typeConstructor: Type = - abort("typeConstructor inapplicable for " + this) - - /** The logic approximately boils down to finding the most recent phase - * which immediately follows any of parser, namer, typer, or erasure. - * In effect that means this will return one of: - * - * - packageobjects (follows namer) - * - superaccessors (follows typer) - * - lazyvals (follows erasure) - * - null - */ - private def unsafeTypeParamPhase = { - var ph = phase - while (ph.prev.keepsTypeParams) - ph = ph.prev - - ph - } - /** The type parameters of this symbol, without ensuring type completion. - * assumption: if a type starts out as monomorphic, it will not acquire - * type parameters later. - */ - def unsafeTypeParams: List[Symbol] = - if (isMonomorphicType) Nil - else atPhase(unsafeTypeParamPhase)(rawInfo.typeParams) - - /** The type parameters of this symbol. - * assumption: if a type starts out as monomorphic, it will not acquire - * type parameters later. - */ - def typeParams: List[Symbol] = - if (isMonomorphicType) Nil - else { - // analogously to the "info" getter, here we allow for two completions: - // one: sourceCompleter to LazyType, two: LazyType to completed type - if (validTo == NoPeriod) - atPhase(phaseOf(infos.validFrom))(rawInfo load this) - if (validTo == NoPeriod) - atPhase(phaseOf(infos.validFrom))(rawInfo load this) - - rawInfo.typeParams - } - - /** The value parameter sections of this symbol. - */ - def paramss: List[List[Symbol]] = info.paramss - def hasParamWhich(cond: Symbol => Boolean) = mexists(paramss)(cond) - - /** The least proper supertype of a class; includes all parent types - * and refinement where needed. You need to compute that in a situation like this: - * { - * class C extends P { ... } - * new C - * } - */ - def classBound: Type = { - val tp = refinedType(info.parents, owner) - val thistp = tp.typeSymbol.thisType - val oldsymbuf = new ListBuffer[Symbol] - val newsymbuf = new ListBuffer[Symbol] - for (sym <- info.decls) { - // todo: what about public references to private symbols? - if (sym.isPublic && !sym.isConstructor) { - oldsymbuf += sym - newsymbuf += ( - if (sym.isClass) - tp.typeSymbol.newAbstractType(sym.name.toTypeName, sym.pos).setInfo(sym.existentialBound) - else - sym.cloneSymbol(tp.typeSymbol)) - } - } - val oldsyms = oldsymbuf.toList - val newsyms = newsymbuf.toList - for (sym <- newsyms) { - addMember(thistp, tp, sym modifyInfo (_ substThisAndSym(this, thistp, oldsyms, newsyms))) - } - tp - } - - /** If we quantify existentially over this symbol, - * the bound of the type variable that stands for it - * pre: symbol is a term, a class, or an abstract type (no alias type allowed) - */ - def existentialBound: Type - - /** Reset symbol to initial state - */ - def reset(completer: Type): this.type = { - resetFlags() - infos = null - _validTo = NoPeriod - //limit = NoPhase.id - setInfo(completer) - } - - /** - * Adds the interface scala.Serializable to the parents of a ClassInfoType. - * Note that the tree also has to be updated accordingly. - */ - def makeSerializable() { - info match { - case ci @ ClassInfoType(_, _, _) => - updateInfo(ci.copy(parents = ci.parents :+ SerializableClass.tpe)) - case i => - abort("Only ClassInfoTypes can be made serializable: "+ i) - } - } - -// ----- setters implemented in selected subclasses ------------------------------------- - - def typeOfThis_=(tp: Type) { throw new UnsupportedOperationException("typeOfThis_= inapplicable for " + this) } - def sourceModule_=(sym: Symbol) { throw new UnsupportedOperationException("sourceModule_= inapplicable for " + this) } - def addChild(sym: Symbol) { throw new UnsupportedOperationException("addChild inapplicable for " + this) } - -// ----- annotations ------------------------------------------------------------ - - // null is a marker that they still need to be obtained. - private[this] var _annotations: List[AnnotationInfo] = Nil - - def annotationsString = if (annotations.isEmpty) "" else annotations.mkString("(", ", ", ")") - - /** After the typer phase (before, look at the definition's Modifiers), contains - * the annotations attached to member a definition (class, method, type, field). - */ - def annotations: List[AnnotationInfo] = - _annotations - - def setAnnotations(annots: List[AnnotationInfo]): this.type = { - _annotations = annots - this - } - - def withAnnotations(annots: List[AnnotationInfo]): this.type = - setAnnotations(annots ::: annotations) - - def withoutAnnotations: this.type = - setAnnotations(Nil) - - def filterAnnotations(p: AnnotationInfo => Boolean): this.type = - setAnnotations(annotations filter p) - - def addAnnotation(annot: AnnotationInfo): this.type = - setAnnotations(annot :: annotations) - - // Convenience for the overwhelmingly common case - def addAnnotation(sym: Symbol, args: Tree*): this.type = - addAnnotation(AnnotationInfo(sym.tpe, args.toList, Nil)) - -// ------ comparisons ---------------------------------------------------------------- - - /** A total ordering between symbols that refines the class - * inheritance graph (i.e. subclass.isLess(superclass) always holds). - * the ordering is given by: (_.isType, -_.baseTypeSeq.length) for type symbols, followed by `id`. - */ - final def isLess(that: Symbol): Boolean = { - def baseTypeSeqLength(sym: Symbol) = - if (sym.isAbstractType) 1 + sym.info.bounds.hi.baseTypeSeq.length - else sym.info.baseTypeSeq.length - if (this.isType) - (that.isType && - { val diff = baseTypeSeqLength(this) - baseTypeSeqLength(that) - diff > 0 || diff == 0 && this.id < that.id }) - else - that.isType || this.id < that.id - } - - /** A partial ordering between symbols. - * (this isNestedIn that) holds iff this symbol is defined within - * a class or method defining that symbol - */ - final def isNestedIn(that: Symbol): Boolean = - owner == that || owner != NoSymbol && (owner isNestedIn that) - - /** Is this class symbol a subclass of that symbol, - * and is this class symbol also different from Null or Nothing? */ - def isNonBottomSubClass(that: Symbol): Boolean = false - - /** Overridden in NullClass and NothingClass for custom behavior. - */ - def isSubClass(that: Symbol) = isNonBottomSubClass(that) - - final def isNumericSubClass(that: Symbol): Boolean = - definitions.isNumericSubClass(this, that) - - final def isWeakSubClass(that: Symbol) = - isSubClass(that) || isNumericSubClass(that) - -// ------ overloaded alternatives ------------------------------------------------------ - - def alternatives: List[Symbol] = - if (isOverloaded) info.asInstanceOf[OverloadedType].alternatives - else List(this) - - def filter(cond: Symbol => Boolean): Symbol = - if (isOverloaded) { - val alts = alternatives - val alts1 = alts filter cond - if (alts1 eq alts) this - else if (alts1.isEmpty) NoSymbol - else if (alts1.tail.isEmpty) alts1.head - else owner.newOverloaded(info.prefix, alts1) - } - else if (cond(this)) this - else NoSymbol - - def suchThat(cond: Symbol => Boolean): Symbol = { - val result = filter(cond) - assert(!result.isOverloaded, result.alternatives) - result - } - - @inline final def map(f: Symbol => Symbol): Symbol = if (this eq NoSymbol) this else f(this) - -// ------ cloneing ------------------------------------------------------------------- - - /** A clone of this symbol. */ - final def cloneSymbol: TypeOfClonedSymbol = - cloneSymbol(owner) - - /** A clone of this symbol, but with given owner. */ - final def cloneSymbol(newOwner: Symbol): TypeOfClonedSymbol = - cloneSymbol(newOwner, _rawflags) - final def cloneSymbol(newOwner: Symbol, newFlags: Long): TypeOfClonedSymbol = - cloneSymbol(newOwner, newFlags, null) - final def cloneSymbol(newOwner: Symbol, newFlags: Long, newName: Name): TypeOfClonedSymbol = { - val clone = cloneSymbolImpl(newOwner, newFlags) - ( clone - setPrivateWithin privateWithin - setInfo (this.info cloneInfo clone) - setAnnotations this.annotations - ) - if (clone.thisSym != clone) - clone.typeOfThis = (clone.typeOfThis cloneInfo clone) - - if (newName ne null) - clone setName asNameType(newName) - - clone - } - - /** Internal method to clone a symbol's implementation with the given flags and no info. */ - def cloneSymbolImpl(owner: Symbol, newFlags: Long): TypeOfClonedSymbol - -// ------ access to related symbols -------------------------------------------------- - - /** The next enclosing class. */ - def enclClass: Symbol = if (isClass) this else owner.enclClass - - /** The next enclosing method. */ - def enclMethod: Symbol = if (isSourceMethod) this else owner.enclMethod - - /** The primary constructor of a class. */ - def primaryConstructor: Symbol = NoSymbol - - /** The self symbol (a TermSymbol) of a class with explicit self type, or else the - * symbol itself (a TypeSymbol). - * - * WARNING: you're probably better off using typeOfThis, as it's more uniform across classes with and without self variables. - * - * Example by Paul: - * scala> trait Foo1 { } - * scala> trait Foo2 { self => } - * scala> intp("Foo1").thisSym - * res0: $r.intp.global.Symbol = trait Foo1 - * - * scala> intp("Foo2").thisSym - * res1: $r.intp.global.Symbol = value self - * - * Martin says: The reason `thisSym' is `this' is so that thisType can be this.thisSym.tpe. - * It's a trick to shave some cycles off. - * - * Morale: DO: if (clazz.typeOfThis.typeConstructor ne clazz.typeConstructor) ... - * DON'T: if (clazz.thisSym ne clazz) ... - * - */ - def thisSym: Symbol = this - - /** The type of `this` in a class, or else the type of the symbol itself. */ - def typeOfThis = thisSym.tpe - - /** If symbol is a class, the type this.type in this class, - * otherwise NoPrefix. - * We always have: thisType <:< typeOfThis - */ - def thisType: Type = NoPrefix - - /** For a case class, the symbols of the accessor methods, one for each - * argument in the first parameter list of the primary constructor. - * The empty list for all other classes. - */ - final def caseFieldAccessors: List[Symbol] = - (info.decls filter (_.isCaseAccessorMethod)).toList - - final def constrParamAccessors: List[Symbol] = - info.decls.toList filter (sym => !sym.isMethod && sym.isParamAccessor) - - /** The symbol accessed by this accessor (getter or setter) function. */ - final def accessed: Symbol = accessed(owner.info) - - /** The symbol accessed by this accessor function, but with given owner type. */ - final def accessed(ownerTp: Type): Symbol = { - assert(hasAccessorFlag, this) - ownerTp decl nme.getterToLocal(getterName.toTermName) - } - - /** The module corresponding to this module class (note that this - * is not updated when a module is cloned), or NoSymbol if this is not a ModuleClass. - */ - def sourceModule: Symbol = NoSymbol - - /** The implementation class of a trait. If available it will be the - * symbol with the same owner, and the name of this symbol with $class - * appended to it. - */ - final def implClass: Symbol = owner.info.decl(tpnme.implClassName(name)) - - /** The class that is logically an outer class of given `clazz`. - * This is the enclosing class, except for classes defined locally to constructors, - * where it is the outer class of the enclosing class. - */ - final def outerClass: Symbol = - if (owner.isClass) owner - else if (isClassLocalToConstructor) owner.enclClass.outerClass - else owner.outerClass - - /** For a paramaccessor: a superclass paramaccessor for which this symbol - * is an alias, NoSymbol for all others. - */ - def alias: Symbol = NoSymbol - - /** For a lazy value, its lazy accessor. NoSymbol for all others. */ - def lazyAccessor: Symbol = NoSymbol - - /** If this is a lazy value, the lazy accessor; otherwise this symbol. */ - def lazyAccessorOrSelf: Symbol = if (isLazy) lazyAccessor else this - - /** If this is an accessor, the accessed symbol. Otherwise, this symbol. */ - def accessedOrSelf: Symbol = if (hasAccessorFlag) accessed else this - - /** For an outer accessor: The class from which the outer originates. - * For all other symbols: NoSymbol - */ - def outerSource: Symbol = NoSymbol - - /** The superclass of this class. */ - def superClass: Symbol = if (info.parents.isEmpty) NoSymbol else info.parents.head.typeSymbol - def parentSymbols: List[Symbol] = info.parents map (_.typeSymbol) - - /** The directly or indirectly inherited mixins of this class - * except for mixin classes inherited by the superclass. Mixin classes appear - * in linearization order. - */ - def mixinClasses: List[Symbol] = { - val sc = superClass - ancestors takeWhile (sc ne _) - } - - /** All directly or indirectly inherited classes. */ - def ancestors: List[Symbol] = info.baseClasses drop 1 - - @inline final def enclosingSuchThat(p: Symbol => Boolean): Symbol = { - var sym = this - while (sym != NoSymbol && !p(sym)) - sym = sym.owner - sym - } - - /** The package class containing this symbol, or NoSymbol if there - * is not one. - * TODO: formulate as enclosingSuchThat, after making sure - * we can start with current symbol rather than onwner. - * TODO: Also harmonize with enclClass, enclMethod etc. - */ - def enclosingPackageClass: Symbol = { - var sym = this.owner - while (sym != NoSymbol && !sym.isPackageClass) - sym = sym.owner - sym - } - - /** The package class containing this symbol, or NoSymbol if there - * is not one. */ - def enclosingRootClass: Symbol = enclosingSuchThat(_.isRoot) - - /** The package containing this symbol, or NoSymbol if there - * is not one. */ - def enclosingPackage: Symbol = enclosingPackageClass.companionModule - - /** Return the original enclosing method of this symbol. It should return - * the same thing as enclMethod when called before lambda lift, - * but it preserves the original nesting when called afterwards. - * - * @note This method is NOT available in the presentation compiler run. The - * originalOwner map is not populated for memory considerations (the symbol - * may hang on to lazy types and in turn to whole (outdated) compilation units. - */ - def originalEnclosingMethod: Symbol = { - assert(!forInteractive, "originalOwner is not kept in presentation compiler runs.") - if (isMethod) this - else { - val owner = originalOwner.getOrElse(this, rawowner) - if (isLocalDummy) owner.enclClass.primaryConstructor - else owner.originalEnclosingMethod - } - } - - /** The method or class which logically encloses the current symbol. - * If the symbol is defined in the initialization part of a template - * this is the template's primary constructor, otherwise it is - * the physically enclosing method or class. - * - * Example 1: - * - * def f() { val x = { def g() = ...; g() } } - * - * In this case the owner chain of `g` is `x`, followed by `f` and - * `g.logicallyEnclosingMember == f`. - * - * Example 2: - * - * class C { - * def = { ... } - * val x = { def g() = ...; g() } } - * } - * - * In this case the owner chain of `g` is `x`, followed by `C` but - * g.logicallyEnclosingMember is the primary constructor symbol `` - * (or, for traits: `$init`) of `C`. - * - */ - def logicallyEnclosingMember: Symbol = - if (isLocalDummy) enclClass.primaryConstructor - else if (isMethod || isClass) this - else owner.logicallyEnclosingMember - - /** Kept for source compatibility with 2.9. Scala IDE for Eclipse relies on this. */ - @deprecated("Use enclosingTopLevelClass", "2.10.0") - def toplevelClass: Symbol = enclosingTopLevelClass - - /** The top-level class containing this symbol. */ - def enclosingTopLevelClass: Symbol = - if (owner.isPackageClass) { - if (isClass) this else moduleClass - } else owner.enclosingTopLevelClass - - /** Is this symbol defined in the same scope and compilation unit as `that` symbol? */ - def isCoDefinedWith(that: Symbol) = { - import language.reflectiveCalls - (this.rawInfo ne NoType) && - (this.effectiveOwner == that.effectiveOwner) && { - !this.effectiveOwner.isPackageClass || - (this.sourceFile eq null) || - (that.sourceFile eq null) || - (this.sourceFile == that.sourceFile) || { - // recognize companion object in separate file and fail, else compilation - // appears to succeed but highly opaque errors come later: see bug #1286 - if (this.sourceFile.path != that.sourceFile.path) { - // The cheaper check can be wrong: do the expensive normalization - // before failing. - if (this.sourceFile.canonicalPath != that.sourceFile.canonicalPath) - throw InvalidCompanions(this, that) - } - - false - } - } - } - - /** The internal representation of classes and objects: - * - * class Foo is "the class" or sometimes "the plain class" - * object Foo is "the module" - * class Foo$ is "the module class" (invisible to the user: it implements object Foo) - * - * class Foo < - * ^ ^ (2) \ - * | | | \ - * | (5) | (3) - * | | | \ - * (1) v v \ - * object Foo (4)-> > class Foo$ - * - * (1) companionClass - * (2) companionModule - * (3) linkedClassOfClass - * (4) moduleClass - * (5) companionSymbol - */ - - /** For a module: the class with the same name in the same package. - * For all others: NoSymbol - * Note: does not work for classes owned by methods, see Namers.companionClassOf - * - * object Foo . companionClass --> class Foo - * - * !!! linkedClassOfClass depends on companionClass on the module class getting - * to the class. As presently implemented this potentially returns class for - * any symbol except NoSymbol. - */ - def companionClass: Symbol = flatOwnerInfo.decl(name.toTypeName).suchThat(_ isCoDefinedWith this) - - /** For a class: the module or case class factory with the same name in the same package. - * For all others: NoSymbol - * Note: does not work for modules owned by methods, see Namers.companionModuleOf - * - * class Foo . companionModule --> object Foo - */ - def companionModule: Symbol = NoSymbol - - /** For a module: its linked class - * For a plain class: its linked module or case factory. - * Note: does not work for modules owned by methods, see Namers.companionSymbolOf - * - * class Foo <-- companionSymbol --> object Foo - */ - def companionSymbol: Symbol = NoSymbol - - /** For a module class: its linked class - * For a plain class: the module class of its linked module. - * - * class Foo <-- linkedClassOfClass --> class Foo$ - */ - def linkedClassOfClass: Symbol = NoSymbol - - /** - * Returns the rawInfo of the owner. If the current phase has flat classes, - * it first applies all pending type maps to this symbol. - * - * assume this is the ModuleSymbol for B in the following definition: - * package p { class A { object B { val x = 1 } } } - * - * The owner after flatten is "package p" (see "def owner"). The flatten type map enters - * symbol B in the decls of p. So to find a linked symbol ("object B" or "class B") - * we need to apply flatten to B first. Fixes #2470. - */ - protected final def flatOwnerInfo: Type = { - if (needsFlatClasses) - info - owner.rawInfo - } - - /** If this symbol is an implementation class, its interface, otherwise the symbol itself - * The method follows two strategies to determine the interface. - * - during or after erasure, it takes the last parent of the implementation class - * (which is always the interface, by convention) - * - before erasure, it looks up the interface name in the scope of the owner of the class. - * This only works for implementation classes owned by other classes or traits. - * !!! Why? - */ - def toInterface: Symbol = this - - /** The module class corresponding to this module. - */ - def moduleClass: Symbol = NoSymbol - - /** The non-private symbol whose type matches the type of this symbol - * in in given class. - * - * @param ofclazz The class containing the symbol's definition - * @param site The base type from which member types are computed - */ - final def matchingSymbol(ofclazz: Symbol, site: Type): Symbol = - ofclazz.info.nonPrivateDecl(name).filter(sym => - !sym.isTerm || (site.memberType(this) matches site.memberType(sym))) - - /** The non-private member of `site` whose type and name match the type of this symbol. */ - final def matchingSymbol(site: Type, admit: Long = 0L): Symbol = - site.nonPrivateMemberAdmitting(name, admit).filter(sym => - !sym.isTerm || (site.memberType(this) matches site.memberType(sym))) - - /** The symbol, in class `ofclazz`, that is overridden by this symbol. - * - * @param ofclazz is a base class of this symbol's owner. - */ - final def overriddenSymbol(ofclazz: Symbol): Symbol = - if (isClassConstructor) NoSymbol else matchingSymbol(ofclazz, owner.thisType) - - /** The symbol overriding this symbol in given subclass `ofclazz`. - * - * @param ofclazz is a subclass of this symbol's owner - */ - final def overridingSymbol(ofclazz: Symbol): Symbol = - if (isClassConstructor) NoSymbol else matchingSymbol(ofclazz, ofclazz.thisType) - - /** Returns all symbols overriden by this symbol. */ - final def allOverriddenSymbols: List[Symbol] = - if (!owner.isClass) Nil - else owner.ancestors map overriddenSymbol filter (_ != NoSymbol) - - /** Equivalent to allOverriddenSymbols.nonEmpty, but more efficient. */ - // !!! When if ever will this answer differ from .isOverride? - // How/where is the OVERRIDE flag managed, as compared to how checks - // based on type membership will evaluate? - def isOverridingSymbol = owner.isClass && ( - owner.ancestors exists (cls => matchingSymbol(cls, owner.thisType) != NoSymbol) - ) - /** Equivalent to allOverriddenSymbols.head (or NoSymbol if no overrides) but more efficient. */ - def nextOverriddenSymbol: Symbol = { - if (owner.isClass) owner.ancestors foreach { base => - val sym = overriddenSymbol(base) - if (sym != NoSymbol) - return sym - } - NoSymbol - } - - /** Returns all symbols overridden by this symbol, plus all matching symbols - * defined in parents of the selftype. - */ - final def extendedOverriddenSymbols: List[Symbol] = - if (!owner.isClass) Nil - else owner.thisSym.ancestors map overriddenSymbol filter (_ != NoSymbol) - - /** The symbol accessed by a super in the definition of this symbol when - * seen from class `base`. This symbol is always concrete. - * pre: `this.owner` is in the base class sequence of `base`. - */ - final def superSymbol(base: Symbol): Symbol = { - var bcs = base.info.baseClasses.dropWhile(owner != _).tail - var sym: Symbol = NoSymbol - while (!bcs.isEmpty && sym == NoSymbol) { - if (!bcs.head.isImplClass) - sym = matchingSymbol(bcs.head, base.thisType).suchThat(!_.isDeferred) - bcs = bcs.tail - } - sym - } - - /** The getter of this value or setter definition in class `base`, or NoSymbol if - * none exists. - */ - final def getter(base: Symbol): Symbol = base.info.decl(getterName) filter (_.hasAccessorFlag) - - def getterName: TermName = ( - if (isSetter) nme.setterToGetter(name.toTermName) - else if (nme.isLocalName(name)) nme.localToGetter(name.toTermName) - else name.toTermName - ) - - /** The setter of this value or getter definition, or NoSymbol if none exists */ - final def setter(base: Symbol): Symbol = setter(base, false) - - final def setter(base: Symbol, hasExpandedName: Boolean): Symbol = { - var sname = nme.getterToSetter(nme.getterName(name.toTermName)) - if (hasExpandedName) sname = nme.expandedSetterName(sname, base) - base.info.decl(sname) filter (_.hasAccessorFlag) - } - - /** Return the accessor method of the first parameter of this class. - * or NoSymbol if it does not exist. - */ - def firstParamAccessor: Symbol = NoSymbol - - /** The case module corresponding to this case class - * @pre case class is a member of some other class or package - */ - final def caseModule: Symbol = { - var modname = name.toTermName - if (privateWithin.isClass && !privateWithin.isModuleClass && !hasFlag(EXPANDEDNAME)) - modname = nme.expandedName(modname, privateWithin) - initialize.owner.info.decl(modname).suchThat(_.isModule) - } - - /** If this symbol is a type parameter skolem (not an existential skolem!) - * its corresponding type parameter, otherwise this */ - def deSkolemize: Symbol = this - - /** If this symbol is an existential skolem the location (a Tree or null) - * where it was unpacked. Resulttype is AnyRef because trees are not visible here. */ - def unpackLocation: AnyRef = null - - /** Remove private modifier from symbol `sym`s definition. If `sym` is a - * is not a constructor nor a static module rename it by expanding its name to avoid name clashes - * @param base the fully qualified name of this class will be appended if name expansion is needed - */ - final def makeNotPrivate(base: Symbol) { - if (this.isPrivate) { - setFlag(notPRIVATE) - // Marking these methods final causes problems for proxies which use subclassing. If people - // write their code with no usage of final, we probably shouldn't introduce it ourselves - // unless we know it is safe. ... Unfortunately if they aren't marked final the inliner - // thinks it can't inline them. So once again marking lateFINAL, and in genjvm we no longer - // generate ACC_FINAL on "final" methods which are actually lateFINAL. - if (isMethod && !isDeferred) - setFlag(lateFINAL) - if (!isStaticModule && !isClassConstructor) { - expandName(base) - if (isModule) moduleClass.makeNotPrivate(base) - } - } - } - - /** Remove any access boundary and clear flags PROTECTED | PRIVATE. - */ - def makePublic = this setPrivateWithin NoSymbol resetFlag AccessFlags - - /** The first parameter to the first argument list of this method, - * or NoSymbol if inapplicable. - */ - def firstParam = info.params match { - case p :: _ => p - case _ => NoSymbol - } -/* code for fixing nested objects - def expandModuleClassName() { - name = newTypeName(name.toString + "$") - } - - def isExpandedModuleClass: Boolean = name(name.length - 1) == '$' -*/ - - /** Desire to re-use the field in ClassSymbol which stores the source - * file to also store the classfile, but without changing the behavior - * of sourceFile (which is expected at least in the IDE only to - * return actual source code.) So sourceFile has classfiles filtered out. - */ - private def sourceFileOnly(file: AbstractFileType): AbstractFileType = - if ((file eq null) || (file.path endsWith ".class")) null else file - - private def binaryFileOnly(file: AbstractFileType): AbstractFileType = - if ((file eq null) || !(file.path endsWith ".class")) null else file - - final def binaryFile: AbstractFileType = binaryFileOnly(associatedFile) - final def sourceFile: AbstractFileType = sourceFileOnly(associatedFile) - - /** Overridden in ModuleSymbols to delegate to the module class. */ - def associatedFile: AbstractFileType = enclosingTopLevelClass.associatedFile - def associatedFile_=(f: AbstractFileType) { abort("associatedFile_= inapplicable for " + this) } - - @deprecated("Use associatedFile_= instead", "2.10.0") - def sourceFile_=(f: AbstractFileType): Unit = associatedFile_=(f) - - /** If this is a sealed class, its known direct subclasses. - * Otherwise, the empty set. - */ - def children: Set[Symbol] = Set() - - /** Recursively assemble all children of this symbol. - */ - def sealedDescendants: Set[Symbol] = children.flatMap(_.sealedDescendants) + this - - @inline final def orElse(alt: => Symbol): Symbol = if (this ne NoSymbol) this else alt - @inline final def andAlso(f: Symbol => Unit): Symbol = { if (this ne NoSymbol) f(this) ; this } - -// ------ toString ------------------------------------------------------------------- - - /** A tag which (in the ideal case) uniquely identifies class symbols */ - final def tag: Int = fullName.## - - /** The simple name of this Symbol */ - final def simpleName: Name = name - - /** The String used to order otherwise identical sealed symbols. - * This uses data which is stable across runs and variable classpaths - * (the initial Name) before falling back on id, which varies depending - * on exactly when a symbol is loaded. - */ - final def sealedSortName: String = initName + "#" + id - - /** String representation of symbol's definition key word */ - final def keyString: String = - if (isJavaInterface) "interface" - else if (isTrait && !isImplClass) "trait" - else if (isClass) "class" - else if (isType && !isParameter) "type" - else if (isVariable) "var" - else if (isPackage) "package" - else if (isModule) "object" - else if (isSourceMethod) "def" - else if (isTerm && (!isParameter || isParamAccessor)) "val" - else "" - - private case class SymbolKind(accurate: String, sanitized: String, abbreviation: String) - private def symbolKind: SymbolKind = { - var kind = - if (isTermMacro) ("macro method", "macro method", "MAC") - else if (isInstanceOf[FreeTermSymbol]) ("free term", "free term", "FTE") - else if (isInstanceOf[FreeTypeSymbol]) ("free type", "free type", "FTY") - else if (isPackage) ("package", "package", "PK") - else if (isPackageClass) ("package class", "package", "PKC") - else if (isPackageObject) ("package object", "package", "PKO") - else if (isPackageObjectClass) ("package object class", "package", "PKOC") - else if (isAnonymousClass) ("anonymous class", "anonymous class", "AC") - else if (isRefinementClass) ("refinement class", "", "RC") - else if (isModule) ("module", "object", "MOD") - else if (isModuleClass) ("module class", "object", "MODC") - else if (isGetter) ("getter", if (isSourceMethod) "method" else "value", "GET") - else if (isSetter) ("setter", if (isSourceMethod) "method" else "value", "SET") - else if (isTerm && isLazy) ("lazy value", "lazy value", "LAZ") - else if (isVariable) ("field", "variable", "VAR") - else if (isImplClass) ("implementation class", "class", "IMPL") - else if (isTrait) ("trait", "trait", "TRT") - else if (isClass) ("class", "class", "CLS") - else if (isType) ("type", "type", "TPE") - else if (isClassConstructor && isPrimaryConstructor) ("primary constructor", "constructor", "PCTOR") - else if (isClassConstructor) ("constructor", "constructor", "CTOR") - else if (isSourceMethod) ("method", "method", "METH") - else if (isTerm) ("value", "value", "VAL") - else ("", "", "???") - if (isSkolem) kind = (kind._1, kind._2, kind._3 + "#SKO") - SymbolKind(kind._1, kind._2, kind._3) - } - - /** Accurate string representation of symbols' kind, suitable for developers. */ - final def accurateKindString: String = - symbolKind.accurate - - /** String representation of symbol's kind, suitable for the masses. */ - private def sanitizedKindString: String = - symbolKind.sanitized - - /** String representation of symbol's kind, suitable for the masses. */ - protected[scala] def abbreviatedKindString: String = - symbolKind.abbreviation - - final def kindString: String = - if (settings.debug.value) accurateKindString - else sanitizedKindString - - /** If the name of the symbol's owner should be used when you care about - * seeing an interesting name: in such cases this symbol is e.g. a method - * parameter with a synthetic name, a constructor named "this", an object - * "package", etc. The kind string, if non-empty, will be phrased relative - * to the name of the owner. - */ - def hasMeaninglessName = ( - isSetterParameter // x$1 - || isClassConstructor // this - || isRefinementClass // - || (name == nme.PACKAGE) // package - ) - - /** String representation of symbol's simple name. - * If !settings.debug translates expansions of operators back to operator symbol. - * E.g. $eq => =. - * If settings.uniqid, adds id. - * If settings.Yshowsymkinds, adds abbreviated symbol kind. - */ - def nameString: String = ( - if (!settings.uniqid.value && !settings.Yshowsymkinds.value) "" + decodedName - else if (settings.uniqid.value && !settings.Yshowsymkinds.value) decodedName + "#" + id - else if (!settings.uniqid.value && settings.Yshowsymkinds.value) decodedName + "#" + abbreviatedKindString - else decodedName + "#" + id + "#" + abbreviatedKindString - ) - - def fullNameString: String = { - def recur(sym: Symbol): String = { - if (sym.isRootSymbol || sym == NoSymbol) sym.nameString - else if (sym.owner.isEffectiveRoot) sym.nameString - else recur(sym.effectiveOwner.enclClass) + "." + sym.nameString - } - - recur(this) - } - - /** If settings.uniqid is set, the symbol's id, else "" */ - final def idString = if (settings.uniqid.value) "#"+id else "" - - /** String representation, including symbol's kind e.g., "class Foo", "method Bar". - * If hasMeaninglessName is true, uses the owner's name to disambiguate identity. - */ - override def toString: String = compose( - kindString, - if (hasMeaninglessName) owner.decodedName + idString else nameString - ) - - /** String representation of location. - */ - def ownsString: String = { - val owns = effectiveOwner - if (owns.isClass && !owns.isEmptyPrefix) "" + owns else "" - } - - /** String representation of location, plus a preposition. Doesn't do much, - * for backward compatibility reasons. - */ - def locationString: String = ownsString match { - case "" => "" - case s => " in " + s - } - def fullLocationString: String = toString + locationString - def signatureString: String = if (hasRawInfo) infoString(rawInfo) else "<_>" - - /** String representation of symbol's definition following its name */ - final def infoString(tp: Type): String = { - def parents = ( - if (settings.debug.value) parentsString(tp.parents) - else briefParentsString(tp.parents) - ) - if (isType) typeParamsString(tp) + ( - if (isClass) " extends " + parents - else if (isAliasType) " = " + tp.resultType - else tp.resultType match { - case rt @ TypeBounds(_, _) => "" + rt - case rt => " <: " + rt - } - ) - else if (isModule) "" // avoid "object X of type X.type" - else tp match { - case PolyType(tparams, res) => typeParamsString(tp) + infoString(res) - case NullaryMethodType(res) => infoString(res) - case MethodType(params, res) => valueParamsString(tp) + infoString(res) - case _ => ": " + tp - } - } - - def infosString = infos.toString - def debugLocationString = fullLocationString + " (flags: " + debugFlagString + ")" - - private def defStringCompose(infoString: String) = compose( - flagString, - keyString, - varianceString + nameString + infoString + flagsExplanationString - ) - /** String representation of symbol's definition. It uses the - * symbol's raw info to avoid forcing types. - */ - def defString = defStringCompose(signatureString) - - /** String representation of symbol's definition, using the supplied - * info rather than the symbol's. - */ - def defStringSeenAs(info: Type) = defStringCompose(infoString(info)) - - /** Concatenate strings separated by spaces */ - private def compose(ss: String*) = ss filter (_ != "") mkString " " - - def isSingletonExistential = - nme.isSingletonName(name) && (info.bounds.hi.typeSymbol isSubClass SingletonClass) - - /** String representation of existentially bound variable */ - def existentialToString = - if (isSingletonExistential && !settings.debug.value) - "val " + tpnme.dropSingletonName(name) + ": " + dropSingletonType(info.bounds.hi) - else defString - } - implicit val SymbolTag = ClassTag[Symbol](classOf[Symbol]) - - /** A class for term symbols */ - class TermSymbol protected[Symbols] (initOwner: Symbol, initPos: Position, initName: TermName) - extends Symbol(initOwner, initPos, initName) with TermSymbolApi { - private[this] var _referenced: Symbol = NoSymbol - privateWithin = NoSymbol - - type TypeOfClonedSymbol = TermSymbol - - private[this] var _rawname: TermName = initName - def rawname = _rawname - def name = _rawname - def name_=(name: Name) { - if (name != rawname) { - log("Renaming %s %s %s to %s".format(shortSymbolClass, debugFlagString, rawname, name)) - changeNameInOwners(name) - _rawname = name.toTermName - } - } - final def asNameType(n: Name) = n.toTermName - - /** Term symbols with the exception of static parts of Java classes and packages. - */ - override def isValue = !(isModule && hasFlag(PACKAGE | JAVA)) - override def isVariable = isMutable && !isMethod - override def isTermMacro = hasFlag(MACRO) - - // interesting only for lambda lift. Captured variables are accessed from inner lambdas. - override def isCapturedVariable = hasAllFlags(MUTABLE | CAPTURED) && !hasFlag(METHOD) - - override def companionSymbol: Symbol = companionClass - override def moduleClass = if (isModule) referenced else NoSymbol - - override def hasDefault = this hasFlag DEFAULTPARAM // overloaded with TRAIT - override def isBridge = this hasFlag BRIDGE - override def isEarlyInitialized = this hasFlag PRESUPER - override def isMethod = this hasFlag METHOD - override def isModule = this hasFlag MODULE - override def isOverloaded = this hasFlag OVERLOADED - override def isPackage = this hasFlag PACKAGE - override def isValueParameter = this hasFlag PARAM - - override def isSetterParameter = isValueParameter && owner.isSetter - override def isAccessor = this hasFlag ACCESSOR - override def isGetter = isAccessor && !isSetter - override def isSetter = isAccessor && nme.isSetterName(name) // todo: make independent of name, as this can be forged. - override def isLocalDummy = nme.isLocalDummyName(name) - override def isClassConstructor = name == nme.CONSTRUCTOR - override def isMixinConstructor = name == nme.MIXIN_CONSTRUCTOR - override def isConstructor = nme.isConstructorName(name) - - override def isPackageObject = isModule && (name == nme.PACKAGE) - override def isStable = !isUnstable - private def isUnstable = ( - isMutable - || (hasFlag(METHOD | BYNAMEPARAM) && !hasFlag(STABLE)) - || (tpe.isVolatile && !hasAnnotation(uncheckedStableClass)) - ) - - // The name in comments is what it is being disambiguated from. - // TODO - rescue CAPTURED from BYNAMEPARAM so we can see all the names. - override def resolveOverloadedFlag(flag: Long) = flag match { - case DEFAULTPARAM => "" // TRAIT - case MIXEDIN => "" // EXISTENTIAL - case LABEL => "