types.scala

来自「JAVA 语言的函数式编程扩展」· SCALA 代码 · 共 1,661 行 · 第 1/5 页

SCALA
1,661
字号
/* NSC -- new Scala compiler * Copyright 2005-2008 LAMP/EPFL * @author  Martin Odersky */// $Id: Types.scala 14561 2008-04-09 09:57:10Z odersky $package scala.tools.nsc.symtabimport scala.collection.immutableimport scala.collection.mutable.{ListBuffer, HashMap}import scala.compat.Platform.currentTimeimport scala.tools.nsc.ast.TreeGenimport scala.tools.nsc.util.{HashSet, Position, NoPosition}import Flags._/* A standard type pattern match:  case ErrorType =>    // internal: error  case WildcardType =>    // internal: unknown  case NoType =>  case NoPrefix =>  case ThisType(sym) =>    // sym.this.type  case SingleType(pre, sym) =>    // pre.sym.type  case ConstantType(value) =>    // int(2)  case TypeRef(pre, sym, args) =>    // pre.sym[targs]  case RefinedType(parents, defs) =>    // parent1 with ... with parentn { defs }  case AnnotatedType(attribs, tp, selfsym) =>    // tp @attribs  // the following are non-value types; you cannot write them down in Scala source.  case TypeBounds(lo, hi) =>      // >: lo <: hi  case ClassInfoType(parents, defs, clazz) =>    // same as RefinedType except as body of class  case MethodType(paramtypes, result) =>    // (paramtypes)result  case PolyType(tparams, result) =>    // [tparams]result where result is a MethodType or ClassInfoType    // or    // []T  for a eval-by-name type  case ExistentialType(tparams, result) =>    // exists[tparams]result  // the last five types are not used after phase `typer'.   case OverloadedType(pre, tparams, alts) =>    // all alternatives of an overloaded ident  case AntiPolyType(pre: Type, targs) =>  case TypeVar(_, _) =>    // a type variable  case DeBruijnIndex(level, index)*/trait Types {  self: SymbolTable =>  import definitions._  //statistics  var singletonClosureCount = 0  var compoundClosureCount = 0  var typerefClosureCount = 0  var findMemberCount = 0  var noMemberCount = 0  var multMemberCount = 0  var findMemberMillis = 0l  var subtypeCount = 0  var subtypeMillis = 0l  private var explainSwitch = false  private var checkMalformedSwitch = false // todo: it's now always false. Remove all code that depends on this switch.  private final val LubGlbMargin = 0  private final val LogPendingSubTypesThreshold = 50  private final val LogPendingBaseTypesThreshold = 50  /** The current skolemization level, needed for the algorithms   *  in isSameType, isSubType that do constraint solving under a prefix    */  var skolemizationLevel = 0  /** A log of type variable with their original constraints. Used in order   *  to undo constraints in the case of isSubType/isSameType failure.   */  type UndoLog = List[(TypeVar, TypeConstraint)]  var undoLog: UndoLog = List()  /** A map from lists to compound types that have the given list as parents.   *  This is used to avoid duplication in the computation of closure and baseClasses.   *  It makes use of the fact that these two operations depend only on the parents,   *  not on the refinement.   */  var intersectionWitness = new HashMap[List[Type], Type]  private object gen extends TreeGen {    val global : Types.this.type = Types.this  }  import gen._  // @M toString that is safe during debugging (does not normalize, ...)  def debugString(tp: Type): String = tp match {     case TypeRef(pre, sym, args) => "TypeRef"+(debugString(pre), sym, args map debugString)     case ThisType(sym) => "ThisType("+sym+")"    case SingleType(pre, sym) => "SingleType"+(debugString(pre), sym)    case RefinedType(parents, defs) => "RefinedType"+(parents map debugString, defs.toList)    case ClassInfoType(parents, defs, clazz) =>  "ClassInfoType"+(parents map debugString, defs.toList, clazz)    case PolyType(tparams, result) => "PolyType"+(tparams, debugString(result))    case TypeBounds(lo, hi) => "TypeBounds "+debugString(lo)+","+debugString(hi)    case TypeVar(origin, constr) => "TypeVar "+origin+","+constr    case ExistentialType(tparams, qtpe) => "ExistentialType("+(tparams map (_.defString))+","+debugString(qtpe)+")"    case _ => tp.toString  }  /** A proxy for a type (identified by field `underlying') that forwards most    *  operations to it (for exceptions, see WrappingProxy, which forwards even more operations.   *  every operation that is overridden for some kind of types should be forwarded.   */  trait SimpleTypeProxy extends Type {    def underlying: Type    // the following operations + those in RewrappingTypeProxy are all operations     // in class Type that are overridden in some subclass    // Important to keep this up-to-date when new operations are added!    override def isTrivial = underlying.isTrivial    override def isHigherKinded: Boolean = underlying.isHigherKinded    override def isNotNull = underlying.isNotNull    override def isError = underlying.isError    override def isErroneous = underlying.isErroneous    override def isStable: Boolean = underlying.isStable    override def finalResultType = underlying.finalResultType    override def paramSectionCount = underlying.paramSectionCount    override def paramTypes = underlying.paramTypes    override def termSymbol = underlying.termSymbol    override def termSymbolDirect = underlying.termSymbolDirect    override def typeParams = underlying.typeParams    override def boundSyms = underlying.boundSyms    override def typeSymbol = underlying.typeSymbol    override def typeSymbolDirect = underlying.typeSymbolDirect    override def widen = underlying.widen    override def typeOfThis = underlying.typeOfThis    override def bounds = underlying.bounds    override def parents = underlying.parents    override def prefix = underlying.prefix    override def decls = underlying.decls    override def baseType(clazz: Symbol) = underlying.baseType(clazz)    override def closure = underlying.closure    override def closureDepth = underlying.closureDepth    override def baseClasses = underlying.baseClasses  }  /** A proxy for a type (identified by field `underlying') that forwards most    *  operations to it. Every operation that is overridden for some kind of types is   *  forwarded here. Some opererations are rewrapped again.   */  trait RewrappingTypeProxy extends SimpleTypeProxy {    protected def maybeRewrap(newtp: Type) = if (newtp eq underlying) this else rewrap(newtp)    protected def rewrap(newtp: Type): Type    // the following are all operations in class Type that are overridden in some subclass    // Important to keep this up-to-date when new operations are added!    override def widen = maybeRewrap(underlying.widen)    override def narrow = underlying.narrow    override def deconst = maybeRewrap(underlying.deconst)    override def resultType = maybeRewrap(underlying.resultType)    override def resultType(actuals: List[Type]) = maybeRewrap(underlying.resultType(actuals))    override def finalResultType = maybeRewrap(underlying.finalResultType)    override def paramSectionCount = 0    override def paramTypes: List[Type] = List()    override def typeArgs = underlying.typeArgs    override def notNull = maybeRewrap(underlying.notNull)    override def instantiateTypeParams(formals: List[Symbol], actuals: List[Type]) = underlying.instantiateTypeParams(formals, actuals)    override def skolemizeExistential(owner: Symbol, origin: AnyRef) = underlying.skolemizeExistential(owner, origin)    override def normalize = maybeRewrap(underlying.normalize)    override def cloneInfo(owner: Symbol) = maybeRewrap(underlying.cloneInfo(owner))    override def prefixString = underlying.prefixString    override def isComplete = underlying.isComplete    override def complete(sym: Symbol) = underlying.complete(sym)    override def load(sym: Symbol) { underlying.load(sym) }    override def withAttributes(attribs: List[AnnotationInfo]) = maybeRewrap(underlying.withAttributes(attribs))    override def withoutAttributes = maybeRewrap(underlying.withoutAttributes)  }    /** The base class for all types */  abstract class Type {        /** Types for which asSeenFrom always is the identity, no matter what     *  prefix or owner.     */    def isTrivial: Boolean = false    /** Is this type higher-kinded, i.e., is it a type constructor @M */    def isHigherKinded: Boolean = false         /** Does this type denote a stable reference (i.e. singleton type)? */    def isStable: Boolean = false    /** Is this type guaranteed not to have `null' as a value? */    def isNotNull: Boolean = false    /** Does this depend on an enclosing method parameter? */    def isDependent: Boolean = {      IsDependentTraverser.result = false      IsDependentTraverser.traverse(this)      IsDependentTraverser.result    }    /** The term symbol associated with the type      * Note that the symbol of the normalized type is returned (@see normalize)      */    def termSymbol: Symbol = NoSymbol    /** The type symbol associated with the type      * Note that the symbol of the normalized type is returned (@see normalize)      */    def typeSymbol: Symbol = NoSymbol    /** The term symbol *directly* associated with the type      */    def termSymbolDirect: Symbol = termSymbol    /** The type symbol *directly* associated with the type      */    def typeSymbolDirect: Symbol = typeSymbol    /** The base type underlying a type proxy,     *  identity on all other types */    def underlying: Type = this    /** Widen from singleton type to its underlying non-singleton base type     *  by applying one or more `underlying' derefernces,     *  identity for all other types */    def widen: Type = this    /** Map a constant type or not-null-type to its underlying base type,     *  identity for all other types */    def deconst: Type = this    /** The type of `this' of a class type or reference type     */    def typeOfThis: Type = typeSymbol.typeOfThis    /** Map to a singleton type which is a subtype of this type.     */    def narrow: Type =      if (phase.erasedTypes) this      else refinedType(List(this), commonOwner(this), EmptyScope).narrow    /** For a TypeBounds type, itself;     *  for a reference denoting an abstract type, its bounds,     *  for all other types, a TypeBounds type all of whose bounds are this type.     */    def bounds: TypeBounds = mkTypeBounds(this, this)    /** For a class or intersection type, its parents.     *  For a TypeBounds type, the parents of its hi bound.     *  inherited by typerefs, singleton types, and refinement types,     *  The empty list for all other types */    def parents: List[Type] = List()    /** For a typeref or single-type, the prefix of the normalized type (@see normalize). NoType for all other types. */    def prefix: Type = NoType    /** A chain of all typeref or singletype prefixes of this type, longest first */    def prefixChain: List[Type] = this match {      case TypeRef(pre, _, _) => pre :: pre.prefixChain      case SingleType(pre, _) => pre :: pre.prefixChain      case _ => List()    }    /** For a typeref, its arguments. The empty list for all other types */    def typeArgs: List[Type] = List()    /** For a method or poly type, its direct result type,      *  the type itself for all other types */    def resultType: Type = this    def resultType(actuals: List[Type]) = this    def resultApprox: Type = ApproximateDeBruijnMap(resultType)    /** For a curried method or poly type its non-method result type,      *  the type itself for all other types */    def finalResultType: Type = this    /** For a method or poly type, the number of its value parameter sections,     *  0 for all other types */    def paramSectionCount: Int = 0    /** For a method or poly type, the types of its first value parameter section,     *  the empty list for all other types */    def paramTypes: List[Type] = List()    /** For a (potentially wrapped) poly type, its type parameters,     *  the empty list for all other types */    def typeParams: List[Symbol] = List()    /** For a (potentially wrapped) poly or existential type, its bound symbols,     *  the empty list for all other types */    def boundSyms: List[Symbol] = List()    /** Mixin a NotNull trait unless type already has one */    def notNull: Type =       if (isNotNull || phase.erasedTypes) this else NotNullType(this)        /** Replace formal type parameter symbols with actual type arguments.      *     * Amounts to substitution except for higher-kinded types. (See overridden method in TypeRef) -- @M (contact adriaan.moors at cs.kuleuven.be)     */    def instantiateTypeParams(formals: List[Symbol], actuals: List[Type]): Type = this.subst(formals, actuals)    def skolemizeExistential(owner: Symbol, origin: AnyRef): Type = this        /** Reduce to beta eta-long normal form. Expands type aliases and converts higher-kinded TypeRef's to PolyTypes. @M */    def normalize = this // @MAT        /** Is this type produced as a repair for an error? */    def isError: Boolean = typeSymbol.isError || termSymbol.isError    /** Is this type produced as a repair for an error? */    def isErroneous: Boolean = {      ErroneousTraverser.result = false      ErroneousTraverser.traverse(this)      ErroneousTraverser.result    }    /** Does this type denote a reference type which can be null? */    // def isNullable: Boolean = false

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?