equalsAndHashCodeMacro.scala 7.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * Copyright (c) 2021 jxnu-liguobin && contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

梦境迷离's avatar
梦境迷离 已提交
22 23 24 25 26 27 28 29 30 31
package io.github.dreamylost.macros

import scala.reflect.macros.whitebox

/**
 *
 * @author 梦境迷离
 * @since 2021/7/18
 * @version 1.0
 */
梦境迷离's avatar
梦境迷离 已提交
32 33 34
object equalsAndHashCodeMacro {

  class EqualsAndHashCodeProcessor(override val c: whitebox.Context) extends AbstractMacroProcessor(c) {
梦境迷离's avatar
梦境迷离 已提交
35 36 37

    import c.universe._

梦境迷离's avatar
梦境迷离 已提交
38 39 40 41 42 43 44
    override def impl(annottees: c.universe.Expr[Any]*): c.universe.Expr[Any] = {
      val args: (Boolean, Seq[String]) = extractArgumentsTuple2 {
        case q"new equalsAndHashCode(verbose=$verbose)" => (evalTree(verbose.asInstanceOf[Tree]), Nil)
        case q"new equalsAndHashCode(excludeFields=$excludeFields)" => (false, evalTree(excludeFields.asInstanceOf[Tree]))
        case q"new equalsAndHashCode(verbose=$verbose, excludeFields=$excludeFields)" => (evalTree(verbose.asInstanceOf[Tree]), evalTree(excludeFields.asInstanceOf[Tree]))
        case q"new equalsAndHashCode()" => (false, Nil)
        case _ => c.abort(c.enclosingPosition, ErrorMessage.UNEXPECTED_PATTERN)
梦境迷离's avatar
梦境迷离 已提交
45 46
      }

梦境迷离's avatar
梦境迷离 已提交
47 48 49 50
      val annotateeClass: ClassDef = checkAndGetClassDef(annottees: _*)
      val isCase: Boolean = isCaseClass(annotateeClass)
      if (isCase) {
        c.abort(c.enclosingPosition, s"${ErrorMessage.ONLY_CLASS} classDef: $annotateeClass")
梦境迷离's avatar
梦境迷离 已提交
51
      }
梦境迷离's avatar
梦境迷离 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
      val excludeFields = args._2

      def modifiedDeclaration(classDecl: ClassDef, compDeclOpt: Option[ModuleDef] = None): Any = {
        val (className, annotteeClassParams, annotteeClassDefinitions, superClasses) = classDecl match {
          case q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }" =>
            c.info(c.enclosingPosition, s"modifiedDeclaration className: $tpname, paramss: $paramss", force = args._1)
            (tpname, paramss.asInstanceOf[List[List[Tree]]], stats.asInstanceOf[Seq[Tree]], parents)
          case _ => c.abort(c.enclosingPosition, s"${ErrorMessage.ONLY_CLASS} classDef: $classDecl")
        }
        val ctorFieldNames = annotteeClassParams.flatten.filter(cf => classParamsIsPrivate(cf))
        val allFieldsTermName = ctorFieldNames.map(f => getFieldTermName(f))

        c.info(c.enclosingPosition, s"modifiedDeclaration compDeclOpt: $compDeclOpt, ctorFieldNames: $ctorFieldNames, " +
          s"annotteeClassParams: $superClasses", force = args._1)

        /**
         * Extract the internal fields of members belonging to the class.
         */
        def getClassMemberAllTermName: Seq[TermName] = {
          getClassMemberValDefs(annotteeClassDefinitions).filter(_ match {
            case q"$mods var $tname: $tpt = $expr" if !excludeFields.contains(tname.asInstanceOf[TermName].decodedName.toString) => true
            case q"$mods val $tname: $tpt = $expr" if !excludeFields.contains(tname.asInstanceOf[TermName].decodedName.toString) => true
            case q"$mods val $pat = $expr" if !excludeFields.contains(pat.asInstanceOf[TermName].decodedName.toString) => true
            case q"$mods var $pat = $expr" if !excludeFields.contains(pat.asInstanceOf[TermName].decodedName.toString) => true
            case _ => false
          }).map(f => getFieldTermName(f))
        }
梦境迷离's avatar
梦境迷离 已提交
79

梦境迷离's avatar
梦境迷离 已提交
80 81 82 83 84
        val existsCanEqual = getClassMemberDefDefs(annotteeClassDefinitions) exists {
          case q"$mods def $tname[..$tparams](...$paramss): $tpt = $expr" if tname.toString() == "canEqual" && paramss.nonEmpty =>
            val params = paramss.asInstanceOf[List[List[Tree]]].flatten.map(pp => getMethodParamName(pp))
            params.exists(p => p.decodedName.toString == "Any")
          case _ => false
梦境迷离's avatar
梦境迷离 已提交
85
        }
梦境迷离's avatar
梦境迷离 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101

        // + super.hashCode
        val SDKClasses = Set("java.lang.Object", "scala.AnyRef")
        val canEqualsExistsInSuper = if (superClasses.nonEmpty && !superClasses.forall(sc => SDKClasses.contains(sc.toString()))) { // TODO better way
          true
        } else false

        // equals template
        def ==(termNames: Seq[TermName]): Tree = {
          val getEqualsExpr = (termName: TermName) => {
            q"this.$termName.equals(t.$termName)"
          }
          val equalsExprs = termNames.map(getEqualsExpr)
          val modifiers = if (canEqualsExistsInSuper) Modifiers(Flag.OVERRIDE, typeNames.EMPTY, List()) else Modifiers(NoFlags, typeNames.EMPTY, List())
          val canEqual = if (existsCanEqual) q"" else q"$modifiers def canEqual(that: Any) = that.isInstanceOf[$className]"
          q"""
梦境迷离's avatar
梦境迷离 已提交
102 103 104 105 106 107 108 109
        $canEqual

        override def equals(that: Any): Boolean =
          that match {
            case t: $className => t.canEqual(this) && Seq(..$equalsExprs).forall(f => f) && ${if (canEqualsExistsInSuper) q"super.equals(that)" else q"true"}
            case _ => false
        }
       """
梦境迷离's avatar
梦境迷离 已提交
110
        }
梦境迷离's avatar
梦境迷离 已提交
111

梦境迷离's avatar
梦境迷离 已提交
112 113 114 115 116 117
        // hashcode template
        def ##(termNames: Seq[TermName]): Tree = {
          // the algorithm see https://alvinalexander.com/scala/how-to-define-equals-hashcode-methods-in-scala-object-equality/
          // We use default 1.
          if (!canEqualsExistsInSuper) {
            q"""
梦境迷离's avatar
梦境迷离 已提交
118 119 120 121 122
         override def hashCode(): Int = {
            val state = Seq(..$termNames)
            state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
          }
          """
梦境迷离's avatar
梦境迷离 已提交
123 124
          } else {
            q"""
梦境迷离's avatar
梦境迷离 已提交
125 126 127 128 129
         override def hashCode(): Int = {
            val state = Seq(..$termNames)
            state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b) + super.hashCode
          }
          """
梦境迷离's avatar
梦境迷离 已提交
130
          }
梦境迷离's avatar
梦境迷离 已提交
131 132
        }

梦境迷离's avatar
梦境迷离 已提交
133 134 135 136 137
        val allTernNames = allFieldsTermName ++ getClassMemberAllTermName
        val hashcode = ##(allTernNames)
        val equals = ==(allTernNames)
        val equalsAndHashcode =
          q"""
梦境迷离's avatar
梦境迷离 已提交
138 139 140
          ..$equals
          $hashcode
         """
梦境迷离's avatar
梦境迷离 已提交
141 142 143 144 145 146
        // return with object if it exists
        val resTree = annotateeClass match {
          case q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }" =>
            val originalStatus = q"{ ..$stats }"
            val append =
              q"""
梦境迷离's avatar
梦境迷离 已提交
147 148 149
              ..$originalStatus
              ..$equalsAndHashcode
             """
梦境迷离's avatar
梦境迷离 已提交
150 151 152
            q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..${append} }"
        }
        c.Expr[Any](treeResultWithCompanionObject(resTree, annottees: _*))
梦境迷离's avatar
梦境迷离 已提交
153 154
      }

梦境迷离's avatar
梦境迷离 已提交
155 156
      val resTree = handleWithImplType(annottees: _*)(modifiedDeclaration)
      printTree(force = args._1, resTree.tree)
梦境迷离's avatar
梦境迷离 已提交
157

梦境迷离's avatar
梦境迷离 已提交
158 159
      resTree
    }
梦境迷离's avatar
梦境迷离 已提交
160 161
  }
}