From 4704baff553b4805656ad98f23fe564fa6da9857 Mon Sep 17 00:00:00 2001 From: Chicken Bones Date: Sun, 23 Jun 2013 16:18:03 +1000 Subject: [PATCH] Separated the dynamic class compilation from MultipartGenerator to allow for testing alternate generation methods (ASM, Proxy reflection) Added passThroughInterface generation (not quite operational under scala compiler implementation) --- .../multipart/MultipartGenerator.scala | 223 ++++--------- .../multipart/asm/IMultipartFactory.scala | 11 + .../multipart/asm/ScalaCompilerFactory.scala | 298 ++++++++++++++++++ 3 files changed, 368 insertions(+), 164 deletions(-) create mode 100644 codechicken/multipart/asm/IMultipartFactory.scala create mode 100644 codechicken/multipart/asm/ScalaCompilerFactory.scala diff --git a/codechicken/multipart/MultipartGenerator.scala b/codechicken/multipart/MultipartGenerator.scala index 366247a..53b389e 100644 --- a/codechicken/multipart/MultipartGenerator.scala +++ b/codechicken/multipart/MultipartGenerator.scala @@ -1,9 +1,8 @@ package codechicken.multipart +import scala.reflect.runtime.universe._ import net.minecraft.tileentity.TileEntity import scala.collection.immutable.Map -import scala.reflect.runtime.universe._ -import scala.tools.reflect.ToolBox import net.minecraft.world.World import codechicken.core.vec.BlockCoord import codechicken.multipart.handler.MultipartProxy @@ -11,172 +10,42 @@ import cpw.mods.fml.common.FMLCommonHandler import cpw.mods.fml.relauncher.Side import codechicken.core.packet.PacketCustom import net.minecraft.network.packet.Packet53BlockChange +import scala.collection.mutable.ListBuffer +import scala.collection.mutable.ListBuffer +import codechicken.multipart.asm.IMultipartFactory +import codechicken.multipart.asm.ScalaCompilerFactory object MultipartGenerator { - private var ugenid = 0 - var mirror = scala.reflect.runtime.currentMirror - var tb = mirror.mkToolBox() - def Apply(f:Tree, args:Tree*) = scala.reflect.runtime.universe.Apply(f, List(args:_*)) - def Apply(f:Tree, args:List[Tree]) = scala.reflect.runtime.universe.Apply(f, args) - def Invoke(s:Tree, n:TermName, args:Tree*) = Apply(Select(s, n), args:_*) - def literalUnit = Literal(Constant(())) - def PkgIdent(s:String):Tree = Ident(mirror.staticClass(s)) - - def getType(obj:Any) = mirror.classSymbol(obj.getClass).toType - - def defaultConstructor() = - DefDef( - Modifiers(), - nme.CONSTRUCTOR, //method name - List(), //type params - List(List()), //params - TypeTree(), //return type - Block( - Invoke(//body - Super(This(tpnme.EMPTY), tpnme.EMPTY), - nme.CONSTRUCTOR - ) - ) - ) - - def normalClassDef(mods:FlagSet, name:String, parents:List[String], methods:List[Tree]) = - ClassDef( - Modifiers(mods), - name, - List(), - Template( - parents.map(PkgIdent(_)), - emptyValDef, - methods - ) - ) - - def uniqueName(prefix:String):String = { - val ret = prefix+"$$"+ugenid - ugenid += 1 - return ret - } - - abstract class Generator - { - def generate():TileMultipart - } - - object SuperSet - { - val TileMultipartType = typeOf[TileMultipart] - val TileMultipartClientType = typeOf[TileMultipartClient] - def apply(types:Seq[Type], client:Boolean) = new SuperSet(types, client) - } - - class SuperSet(types:Seq[Type], client:Boolean) - { - import SuperSet._ - val set = baseType+:types.sortWith(_.toString < _.toString) - - def interfaces = set - def baseType = if(client) TileMultipartClientType else TileMultipartType - - override def equals(obj:Any) = obj match - { - case x:SuperSet => set == x.set - case _ => false - } - - override def hashCode() = set.hashCode - - def generate():TileMultipart = - { - return generatorMap.getOrElse(this, gen_sync).generate - } - - def gen_sync():Generator = tb.synchronized - { - return generatorMap.getOrElse(this, { - var gen = generator - generatorMap = generatorMap+(this->gen) - gen - }) - } - - def generator():Generator = - { - val s = System.currentTimeMillis - val defClass = - normalClassDef( - NoFlags, - uniqueName("TileMultipart_cmp"), - set.map(_.typeSymbol.fullName).toList, - List( - defaultConstructor - ) - ) - val defGenClass = - normalClassDef( - Flag.FINAL, - uniqueName("TileMultipart_gen"), - List("codechicken.multipart.MultipartGenerator.Generator"), - List(//methods - defaultConstructor, - DefDef( - Modifiers(Flag.OVERRIDE), - "generate":TermName, - List(), - List(List()), - TypeTree(), - Invoke( - New(Ident(defClass.name)), - nme.CONSTRUCTOR - ) - ) - ) - ) - val constructGenClass = - Invoke(//return new generator instance - New(Ident(defGenClass.name)), - nme.CONSTRUCTOR - ) - - val v = tb.eval(Block(defClass, defGenClass, constructGenClass)).asInstanceOf[Generator] - val dummy = v.generate - tileTraitMap=tileTraitMap+(dummy.getClass->types.toSet) - MultipartProxy.onTileClassBuilt(dummy.getClass) - println("Generation ["+types.mkString(", ")+"] took: "+(System.currentTimeMillis-s)) - return v.asInstanceOf[Generator] - } - } - - private var generatorMap:Map[SuperSet, Generator] = Map() private var tileTraitMap:Map[Class[_], Set[Type]] = Map() - private var interfaceTraitMap_c:Map[Type, Seq[Type]] = Map() - private var interfaceTraitMap_s:Map[Type, Seq[Type]] = Map() + private var interfaceTraitMap_c:Map[Type, Type] = Map() + private var interfaceTraitMap_s:Map[Type, Type] = Map() private var partTraitMap_c:Map[Class[_], Seq[Type]] = Map() private var partTraitMap_s:Map[Class[_], Seq[Type]] = Map() - SuperSet(Seq(), false).generate//default impl, boots generator - if(FMLCommonHandler.instance.getEffectiveSide == Side.CLIENT) - SuperSet(Seq(), true).generate + var factory:IMultipartFactory = ScalaCompilerFactory - private def partTraitMap(client:Boolean) = if(client) partTraitMap_c else partTraitMap_s + def getType(obj:Any) = mirror.classSymbol(obj.getClass).toType - private def interfaceTraitMap(client:Boolean) = if(client) partTraitMap_c else interfaceTraitMap_s - - private def traitsForPart(part:TMultiPart, client:Boolean):Seq[Type] = + def partTraitMap(client:Boolean) = if(client) partTraitMap_c else partTraitMap_s + + def interfaceTraitMap(client:Boolean) = if(client) partTraitMap_c else interfaceTraitMap_s + + def traitsForPart(part:TMultiPart, client:Boolean):Seq[Type] = { var ret = partTraitMap(client).getOrElse(part.getClass, null) if(ret == null) { if(client) { - ret = getType(part).baseClasses.flatMap(s => interfaceTraitMap_c.getOrElse(s.asClass.toType, List())).distinct + ret = getType(part).baseClasses.flatMap(s => interfaceTraitMap_c.get(s.asClass.toType)).distinct partTraitMap_c = partTraitMap_c+(part.getClass -> ret) } else { - ret = getType(part).baseClasses.flatMap(s => interfaceTraitMap_s.getOrElse(s.asClass.toType, List())).distinct + ret = getType(part).baseClasses.flatMap(s => interfaceTraitMap_s.get(s.asClass.toType)).distinct partTraitMap_s = partTraitMap_s+(part.getClass -> ret) } } @@ -208,7 +77,7 @@ object MultipartGenerator partTraits = partTraits.filter(!tileTraits(_)) if(!partTraits.isEmpty) { - ntile = SuperSet(partTraits++tileTraits, world.isRemote).generate + ntile = factory.generateTile(partTraits++tileTraits, world.isRemote) world.setBlockTileEntity(pos.x, pos.y, pos.z, ntile) ntile.loadFrom(tile) } @@ -216,7 +85,7 @@ object MultipartGenerator else { world.setBlock(pos.x, pos.y, pos.z, MultipartProxy.block.blockID) - ntile = SuperSet(partTraits, world.isRemote).generate + ntile = factory.generateTile(partTraits, world.isRemote) world.setBlockTileEntity(pos.x, pos.y, pos.z, ntile) } ntile.addPart(part) @@ -226,7 +95,7 @@ object MultipartGenerator /** * Check if tile satisfies all the interfaces required by parts. If not, return a new generated copy of tile */ - def generateCompositeTile(tile:TileEntity, parts:Seq[TMultiPart], client:Boolean):TileMultipart = + private[multipart] def generateCompositeTile(tile:TileEntity, parts:Seq[TMultiPart], client:Boolean):TileMultipart = { var partTraits = parts.flatMap(traitsForPart(_, client)).distinct if(tile != null && tile.isInstanceOf[TileMultipart]) @@ -236,20 +105,20 @@ object MultipartGenerator return tile.asInstanceOf[TileMultipart] } - return SuperSet(partTraits, client).generate + return factory.generateTile(partTraits, client) } /** * Check if there are any redundant interfaces on tile, if so, replace tile with new copy */ - def partRemoved(tile:TileMultipart, part:TMultiPart):TileMultipart = + private[multipart] def partRemoved(tile:TileMultipart, part:TMultiPart):TileMultipart = { val client = tile.worldObj.isRemote var partTraits = tile.partList.flatMap(traitsForPart(_, client)) var testSet = partTraits.toSet if(!traitsForPart(part, client).forall(testSet(_))) { - val ntile = SuperSet(testSet.toSeq, client).generate + val ntile = factory.generateTile(testSet.toSeq, client) tile.worldObj.setBlockTileEntity(tile.xCoord, tile.yCoord, tile.zCoord, ntile) ntile.loadFrom(tile) return ntile @@ -269,24 +138,50 @@ object MultipartGenerator */ def registerTrait(s_interface:String, c_trait:String, s_trait:String) { - val iSymbol = mirror.staticClass(s_interface).asClass + val iSymbol = mirror.staticClass(s_interface).asClass if(c_trait != null) { val tSymbol = mirror.staticClass(c_trait).asClass - //TODO some checking - var reg = interfaceTraitMap_c.getOrElse(iSymbol.toType, Seq()) - if(!reg.contains(tSymbol.toType)) - reg = reg:+tSymbol.toType - interfaceTraitMap_c = interfaceTraitMap_c+(iSymbol.toType->reg) + if(interfaceTraitMap_c.contains(iSymbol.toType)) + System.err.println("Trait already registered for "+iSymbol) + else + interfaceTraitMap_c = interfaceTraitMap_c+(iSymbol.toType->tSymbol.toType) } if(s_trait != null) { val tSymbol = mirror.staticClass(s_trait).asClass - //TODO some checking - var reg = interfaceTraitMap_s.getOrElse(iSymbol.toType, Seq()) - if(!reg.contains(tSymbol.toType)) - reg = reg:+tSymbol.toType - interfaceTraitMap_s = interfaceTraitMap_s+(iSymbol.toType->reg) + if(interfaceTraitMap_s.contains(iSymbol.toType)) + System.err.println("Trait already registered for "+iSymbol) + else + interfaceTraitMap_s = interfaceTraitMap_s+(iSymbol.toType->tSymbol.toType) } } + + def registerPassThroughInterface(s_interface:String):Unit = registerPassThroughInterface(s_interface, true, true) + + def registerPassThroughInterface(s_interface:String, client:Boolean, server:Boolean) + { + val iSymbol = mirror.staticClass(s_interface).asClass + val tType = factory.generatePassThroughTrait(iSymbol) + if(client) + { + if(interfaceTraitMap_c.contains(iSymbol.toType)) + System.err.println("Trait already registered for "+iSymbol) + else + interfaceTraitMap_c = interfaceTraitMap_c+(iSymbol.toType->tType) + } + if(server) + { + if(interfaceTraitMap_s.contains(iSymbol.toType)) + System.err.println("Trait already registered for "+iSymbol) + else + interfaceTraitMap_s = interfaceTraitMap_s+(iSymbol.toType->tType) + } + } + + def registerTileClass(clazz:Class[_ <: TileEntity], traits:Set[Type]) + { + tileTraitMap=tileTraitMap+(clazz->traits) + MultipartProxy.onTileClassBuilt(clazz) + } } \ No newline at end of file diff --git a/codechicken/multipart/asm/IMultipartFactory.scala b/codechicken/multipart/asm/IMultipartFactory.scala new file mode 100644 index 0000000..b41984a --- /dev/null +++ b/codechicken/multipart/asm/IMultipartFactory.scala @@ -0,0 +1,11 @@ +package codechicken.multipart.asm + +import scala.reflect.runtime.universe._ +import codechicken.multipart.TileMultipart + +trait IMultipartFactory +{ + def generatePassThroughTrait(iSymbol:ClassSymbol):Type + + def generateTile(types:Seq[Type], client:Boolean):TileMultipart +} \ No newline at end of file diff --git a/codechicken/multipart/asm/ScalaCompilerFactory.scala b/codechicken/multipart/asm/ScalaCompilerFactory.scala new file mode 100644 index 0000000..2026caa --- /dev/null +++ b/codechicken/multipart/asm/ScalaCompilerFactory.scala @@ -0,0 +1,298 @@ +package codechicken.multipart.asm + +import scala.reflect.runtime.universe._ +import scala.tools.reflect.ToolBox +import Flag._ +import codechicken.multipart.TileMultipart +import codechicken.multipart.TileMultipartClient +import codechicken.multipart.handler.MultipartProxy +import cpw.mods.fml.common.FMLCommonHandler +import codechicken.multipart.TMultiPart +import cpw.mods.fml.relauncher.Side +import codechicken.multipart.MultipartGenerator + +object ScalaCompilerFactory extends IMultipartFactory +{ + private var ugenid = 0 + + var mirror = scala.reflect.runtime.currentMirror + var tb = mirror.mkToolBox() + + def Apply(f:Tree, args:Tree*) = scala.reflect.runtime.universe.Apply(f, List(args:_*)) + def Apply(f:Tree, args:List[Tree]) = scala.reflect.runtime.universe.Apply(f, args) + def TypeApply(f:Tree, args:Tree*) = scala.reflect.runtime.universe.TypeApply(f, List(args:_*)) + def TypeApply(f:Tree, args:List[Tree]) = scala.reflect.runtime.universe.TypeApply(f, args) + def Invoke(s:Tree, n:TermName, args:Tree*) = Apply(Select(s, n), args:_*) + def literalUnit = Literal(Constant(())) + def const(o:Any) = Literal(Constant(o)) + def PkgIdent(s:String):Tree = Ident(mirror.staticClass(s)) + + def typeSymbol(s:String):TypeSymbol = mirror.staticClass(s) + + def defaultConstructor() = + DefDef( + Modifiers(), + nme.CONSTRUCTOR, //method name + List(), //type params + List(List()), //params + TypeTree(), //return type + Block( + Invoke(//body + Super(This(tpnme.EMPTY), tpnme.EMPTY), + nme.CONSTRUCTOR + ) + ) + ) + + def normalClassDef(mods:FlagSet, name:String, parents:List[TypeSymbol], methods:List[Tree]) = + ClassDef( + Modifiers(mods), + name, + List(), + Template( + parents.map(Ident(_)), + emptyValDef, + methods + ) + ) + + def uniqueName(prefix:String):String = { + val ret = prefix+"$$"+ugenid + ugenid += 1 + return ret + } + + abstract class Generator + { + def generate():TileMultipart + } + + object SuperSet + { + val TileMultipartType = typeOf[TileMultipart] + val TileMultipartClientType = typeOf[TileMultipartClient] + def apply(types:Seq[Type], client:Boolean) = new SuperSet(types, client) + } + + class SuperSet(types:Seq[Type], client:Boolean) + { + import SuperSet._ + val set = baseType+:types.sortWith(_.toString < _.toString) + + def interfaces = set + def baseType = if(client) TileMultipartClientType else TileMultipartType + + override def equals(obj:Any) = obj match + { + case x:SuperSet => set == x.set + case _ => false + } + + override def hashCode() = set.hashCode + + def generate():TileMultipart = + { + return generatorMap.getOrElse(this, gen_sync).generate + } + + def gen_sync():Generator = tb.synchronized + { + return generatorMap.getOrElse(this, { + var gen = generator + generatorMap = generatorMap+(this->gen) + gen + }) + } + + def generator():Generator = + { + val s = System.currentTimeMillis + val defClass = + normalClassDef( + NoFlags, + uniqueName("TileMultipart_cmp"), + set.map(_.typeSymbol.asType).toList, + List( + defaultConstructor + ) + ) + val defGenClass = + normalClassDef( + FINAL, + uniqueName("TileMultipart_gen"), + List(typeOf[Generator].typeSymbol.asType), + List(//methods + defaultConstructor, + DefDef( + Modifiers(OVERRIDE), + "generate":TermName, + List(), + List(List()), + TypeTree(), + Invoke( + New(Ident(defClass.name)), + nme.CONSTRUCTOR + ) + ) + ) + ) + val constructGenClass = + Invoke(//return new generator instance + New(Ident(defGenClass.name)), + nme.CONSTRUCTOR + ) + + val v = tb.eval(Block(defClass, defGenClass, constructGenClass)).asInstanceOf[Generator] + val dummy = v.generate + MultipartGenerator.registerTileClass(dummy.getClass, types.toSet) + println("Generation ["+types.mkString(", ")+"] took: "+(System.currentTimeMillis-s)) + return v.asInstanceOf[Generator] + } + } + + private var generatorMap:Map[SuperSet, Generator] = Map() + + SuperSet(Seq(), false).generate//default impl, boots generator + if(FMLCommonHandler.instance.getEffectiveSide == Side.CLIENT) + SuperSet(Seq(), true).generate + + private def symbolToValDef(m:Symbol) = + ValDef(Modifiers(PARAM), m.asTerm.name.decoded, Ident(m), EmptyTree) + + private def passThroughMethod(tname:String, m:MethodSymbol):Tree = + DefDef( + Modifiers(Flag.OVERRIDE), + m.name, + List(), + m.paramss.map(_.map(m => symbolToValDef(m))), + TypeTree(), + Apply( + Select( + Select(This(tname), "impl"), + m.name.toTermName), + m.paramss.flatMap(_.map{m => + Ident(m.name) + }) + ) + ) + + private def passThroughTraitName(iName:String) = + "T" + (if(iName.startsWith("I")) iName.substring(1) else iName) + + def generatePassThroughTrait(iSymbol:ClassSymbol):Type = + { + val tname = uniqueName(passThroughTraitName(iSymbol.name.decoded)) + val methods = iSymbol.toType.members.filter(_.isJava).map(m => passThroughMethod(tname, m.asMethod)) + val traitDef = + normalClassDef( + ABSTRACT | INTERFACE | TRAIT, + tname, + List( + typeSymbol("codechicken.multipart.TileMultipart"), + iSymbol), + List( + ValDef(//pass through field + Modifiers(MUTABLE | DEFAULTINIT), + "impl", + Ident(iSymbol), + EmptyTree), + DefDef( + Modifiers(OVERRIDE), + "partAdded":TermName, + List(), + List( + List( + ValDef(Modifiers(PARAM), "part", PkgIdent("codechicken.multipart.TMultiPart"), EmptyTree) + )), + TypeTree(), + Block( + If( + TypeApply( + Select(Ident("part"), "isInstanceOf"), + Ident(iSymbol)), + Apply( + Select(This(tname), "impl_$eq"), + TypeApply( + Select(Ident("part"), "asInstanceOf"), + Ident(iSymbol))), + literalUnit), + Apply( + Select(Super(This(tpnme.EMPTY), tpnme.EMPTY), "partAdded"), + Ident("part") + ) + )), + DefDef( + Modifiers(OVERRIDE), + "partRemoved":TermName, + List(), + List( + List( + ValDef(Modifiers(PARAM), "part", PkgIdent("codechicken.multipart.TMultiPart"), EmptyTree), + ValDef(Modifiers(PARAM), "p", PkgIdent("scala.Int"), EmptyTree) + )), + TypeTree(), + Block( + If( + Apply( + Select(Ident("part"), "$eq$eq"), + Select(This(tname), "impl")), + Apply( + Select(This(tname), "impl_$eq"), + const(null)), + literalUnit), + Apply( + Select(Super(This(tpnme.EMPTY), tpnme.EMPTY), "partRemoved"), + Ident("part"), + Ident("p") + ) + )), + DefDef( + Modifiers(OVERRIDE), + "occlusionTest":TermName, + List(), + List( + List( + ValDef(Modifiers(PARAM), "parts", + AppliedTypeTree( + PkgIdent("scala.collection.Seq"), + List(PkgIdent("codechicken.multipart.TMultiPart"))), + EmptyTree), + ValDef(Modifiers(PARAM), "npart", PkgIdent("codechicken.multipart.TMultiPart"), EmptyTree) + )), + TypeTree(), + Invoke( + Invoke( + Select( + TypeApply( + Select(Ident("npart"), "isInstanceOf"), + Ident(iSymbol)), + "unary_$bang"), + "$bar$bar", + Invoke( + Select(This(tname), "impl"), + "$eq$eq", + const(null))), + "$amp$amp", + Invoke( + Super(This(tpnme.EMPTY), tpnme.EMPTY), + "occlusionTest", + Ident("parts"), + Ident("npart") + ) + ) + ) + ) + ++methods + ) + + val retType = + TypeApply( + Ident("classOf"), + Ident(tname:TypeName)) + + val clazz = tb.eval(Block(traitDef, retType)).asInstanceOf[Class[_]] + return mirror.classSymbol(clazz).asType.toType + } + + def generateTile(types:Seq[Type], client:Boolean) = SuperSet(types, client).generate +} \ No newline at end of file