[
  {
    "path": ".gitignore",
    "content": "﻿.vs\n*.pdb\n*.mdb\nSGFAppCommon/obj\nSGFAppDemo/obj\nSGFAppILRScript/obj\nSGFCore/obj\nSGFDebuger/obj\nSGFServerLite/obj\nSGFUnity/obj\n"
  },
  {
    "path": "Apps/DirConfig.json",
    "content": "DB,4.3.2.1,32154\nDB,4.3.2.1,32153\nZone,5.3.2.1,32154\n"
  },
  {
    "path": "Apps/ILRuntime.dll.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "Apps/SGFAppDemo.exe.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "Apps/SGFAppILRScript.dll.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "Apps/SGFCore.dll.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "Apps/SGFCore.xml",
    "content": "<?xml version=\"1.0\"?>\n<doc>\n    <assembly>\n        <name>SGFCore</name>\n    </assembly>\n    <members>\n        <member name=\"T:SGF.Codec.PBSerializer\">\n            <summary>\n            序列化帮助类\n            </summary>\n        </member>\n        <member name=\"M:SGF.Codec.PBSerializer.NSerialize``1(``0)\">\n            <summary>\n            序列化pb数据\n            </summary>\n            <typeparam name=\"T\"></typeparam>\n            <param name=\"t\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"M:SGF.Codec.PBSerializer.NDeserialize``1(System.Byte[])\">\n            <summary>\n            反序列化pb数据\n            </summary>\n            <typeparam name=\"T\"></typeparam>\n            <param name=\"buffer\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"M:SGF.Event.SGFEventTable`1.GetEvent(System.String)\">\n            <summary>\n            获取Type所指定的ModuleEvent（它其实是一个EventTable）\n            如果不存在，则实例化一个\n            </summary>\n            <param name=\"type\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"M:SGF.Math.SGFRandom.Rnd\">\n            <summary>\n            采用线性同余算法产生一个0~1之间的随机小数\n            </summary>\n            <returns></returns>\n        </member>\n        <member name=\"M:SGF.Module.BusinessModule.Event(System.String)\">\n            <summary>\n            实现抽象事件功能\n            可以像这样使用：obj.Event(\"onLogin\").AddListener(...)        \n            事件的发送方法：this.Event(\"onLogin\").Invoke(args)\n            而不需要在编码时先定义好，以提高模块的抽象程度\n            但是在模块内部的类不应该过于抽象，比如数据发生更新了，\n            在UI类这样使用：obj.onUpdate.AddListener(...)\n            这两种方法在使用形式上，保持了一致性！\n            </summary>\n            <param name=\"type\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"M:SGF.Module.BusinessModule.Create(System.Object)\">\n            <summary>\n            调用它以创建模块\n            </summary>\n            <param name=\"args\"></param>\n        </member>\n        <member name=\"M:SGF.Module.BusinessModule.Release\">\n            <summary>\n            调用它以释放模块\n            </summary>\n        </member>\n        <member name=\"M:SGF.Module.BusinessModule.HandleMessage(System.String,System.Object[])\">\n            <summary>\n            当模块收到消息后，对消息进行一些处理\n            </summary>\n            <param name=\"msg\"></param>\n            <param name=\"args\"></param>\n        </member>\n        <member name=\"M:SGF.Module.BusinessModule.OnModuleMessage(System.String,System.Object[])\">\n            <summary>\n            由派生类去实现，用于处理消息\n            </summary>\n            <param name=\"msg\"></param>\n            <param name=\"args\"></param>\n        </member>\n        <member name=\"M:SGF.Module.BusinessModule.Show(System.Object)\">\n            <summary>\n            显示业务模块的主UI\n            一般业务模块都有UI，这是游戏业务模块的特点\n            </summary>\n        </member>\n        <member name=\"M:SGF.Module.LuaModule.#ctor(System.String)\">\n            <summary>\n            构造函数传入Name\n            是因为Lua模块无法通过反射来获取Name\n            </summary>\n            <param name=\"name\"></param>\n        </member>\n        <member name=\"M:SGF.Module.LuaModule.Create(System.Object)\">\n            <summary>\n            这里应该去加载Lua脚本\n            并且将EventManager映射到Lua脚本中\n            </summary>\n            <param name=\"args\"></param>\n        </member>\n        <member name=\"M:SGF.Module.LuaModule.Release\">\n            <summary>\n            调用它以卸载Lua脚本\n            </summary>\n        </member>\n        <member name=\"M:SGF.Module.ModuleBase.Release\">\n            <summary>\n            调用它以释放模块\n            </summary>\n        </member>\n        <member name=\"F:SGF.Module.ModuleManager.m_mapModules\">\n            <summary>\n            已创建的模块列表\n            </summary>\n        </member>\n        <member name=\"F:SGF.Module.ModuleManager.m_mapCacheMessage\">\n            <summary>\n            当目标模块未创建时，缓存的消息对象\n            </summary>\n        </member>\n        <member name=\"F:SGF.Module.ModuleManager.m_mapPreListenEvents\">\n            <summary>\n            当目标模块未创建时，预监听的事件\n            </summary>\n        </member>\n        <member name=\"F:SGF.Module.ModuleManager.m_domain\">\n            <summary>\n            用于模块反射的域\n            </summary>\n        </member>\n        <member name=\"M:SGF.Module.ModuleManager.Init(System.String)\">\n            <summary>\n            初始化\n            </summary>\n            <param name=\"domain\">业务模块所在的域</param>\n        </member>\n        <member name=\"M:SGF.Module.ModuleManager.CreateModule``1(System.Object)\">\n            <summary>\n            通过类型创建一个业务模块\n            </summary>\n            <typeparam name=\"T\"></typeparam>\n            <param name=\"args\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"M:SGF.Module.ModuleManager.CreateModule(System.String,System.Object)\">\n            <summary>\n            通过名字创建一个业务模块\n            先通过名字反射出Class，如果不存在\n            则通过扫描Lua文件目录加载LuaModule\n            </summary>\n            <param name=\"name\">业务模块的名字</param>\n            <param name=\"args\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"M:SGF.Module.ModuleManager.ReleaseModule(SGF.Module.BusinessModule)\">\n            <summary>\n            释放一个由ModuleManager创建的模块\n            遵守谁创建谁释放的原则\n            </summary>\n            <param name=\"module\"></param>\n        </member>\n        <member name=\"M:SGF.Module.ModuleManager.ReleaseAll\">\n            <summary>\n            释放所有模块\n            </summary>\n        </member>\n        <member name=\"M:SGF.Module.ModuleManager.GetModule(System.String)\">\n            <summary>\n            通过名字获取一个Module\n            如果未创建过该Module，则返回null\n            </summary>\n            <param name=\"name\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"M:SGF.Module.ModuleManager.ShowModule(System.String,System.Object)\">\n            <summary>\n            显示业务模块的默认UI\n            </summary>\n            <param name=\"name\"></param>\n        </member>\n        <member name=\"M:SGF.Module.ModuleManager.SendMessage(System.String,System.String,System.Object[])\">\n            <summary>\n            向指定的模块发送消息\n            </summary>\n            <param name=\"target\"></param>\n            <param name=\"msg\"></param>\n            <param name=\"args\"></param>\n        </member>\n        <member name=\"M:SGF.Module.ModuleManager.Event(System.String,System.String)\">\n            <summary>\n            监听指定模块的指定事件\n            </summary>\n            <param name=\"target\"></param>\n            <param name=\"type\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"P:SGF.Module.ServiceModule`1.Instance\">\n            <summary>\n            用于实现单例\n            </summary>\n        </member>\n        <member name=\"M:SGF.Module.ServiceModule`1.CheckSingleton\">\n            <summary>\n            调用它以创建模块\n            并且检查它是否以单例形式创建\n            </summary>\n            <param name=\"args\"></param>\n        </member>\n        <member name=\"F:SGF.Network.NetBuffer.m_16b\">\n            <summary>\n            临时字节长度\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.NetBuffer.Arrangement(System.Int32)\">\n            <summary>\n            去掉已经读完的字节\n            装POSITION设置成0\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.NetBuffer.UpdateLenAndGetWritePos(System.Int32,System.Int32)\">\n            <summary>\n            将位置设置到最大\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.NetBuffer.AddBytes(System.Byte[],System.Int32,System.Int32)\">\n            <summary>\n            将Byte[]写入Buffer的末尾\n            不移动游标，返回长度\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.NetBuffer.CopyWith(SGF.Network.NetBuffer,System.Int32,System.Boolean)\">\n            <summary>\n            把src对象的数组copy到本对象，从dstOffect的地方开始\n            不移动游标，返回长度\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.NetBuffer.CopyWith(SGF.Network.NetBuffer,System.Int32,System.Int32,System.Boolean)\">\n            <summary>\n            把src对象的数组从srcOffset开始copy到本对象从dstOffect的地方开始\n            不移动游标，返回长度\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.NetBuffer.AddLength(System.Int32,System.Int32)\">\n            <summary>\n            从指定Pos增加指定Len\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.NetBuffer.ReadBytes(System.Byte[],System.Int32,System.Int32)\">\n            读取数据\n             \n        </member>\n        <member name=\"T:SGF.Network.NetBufferReader\">\n            <summary>\n            字节读出\n            </summary>\n        </member>\n        <member name=\"T:SGF.Network.NetBufferWriter\">\n            <summary>\n            字节写入...\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Client.FSPManager.SetFrameListener(System.Action{System.Int32,SGF.Network.FSPLite.FSPFrame})\">\n            <summary>\n            设置帧数据的监听\n            </summary>\n            <param name=\"listener\"></param>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Client.FSPManager.OnFSPListener(SGF.Network.FSPLite.FSPFrame)\">\n            <summary>\n            监听来自FSPClient的帧数据\n            </summary>\n            <param name=\"frame\"></param>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Client.FSPManager.EnterFrame\">\n            <summary>\n            由外界驱动\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Client.FSPManager.ExecuteFrame(System.Int32,SGF.Network.FSPLite.FSPFrame)\">\n            <summary>\n            执行每一帧\n            </summary>\n            <param name=\"frameId\"></param>\n            <param name=\"frame\"></param>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Client.FSPManager.SendFSP(System.Int32,System.Int32)\">\n            <summary>\n            给外界用来发送FSPVkey的\n            </summary>\n            <param name=\"vkey\"></param>\n            <param name=\"arg\"></param>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Client.FSPManager.SendFSPLocal(System.Int32,System.Int32)\">\n            <summary>\n            用于本地兼容，比如打PVE的时候，也可以用帧同步兼容\n            </summary>\n            <param name=\"vkey\"></param>\n            <param name=\"arg\"></param>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPGameState.None\">\n            <summary>\n            0 初始状态\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPGameState.Create\">\n            <summary>\n            游戏创建状态\n            只有在该状态下，才允许加入玩家\n            当所有玩家都发VKey.GameBegin后，进入下一个状态\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPGameState.GameBegin\">\n            <summary>\n            游戏开始状态\n            在该状态下，等待所有玩家发VKey.RoundBegin，或者 判断玩家是否掉线\n            当所有人都发送VKey.RoundBegin，进入下一个状态\n            当有玩家掉线，则从FSPGame中删除该玩家：\n                判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPGameState.RoundBegin\">\n            <summary>\n            回合开始状态\n            （这个时候客户端可能在加载资源）\n            在该状态下，等待所有玩家发VKey.ControlStart， 或者 判断玩家是否掉线\n            当所有人都发送VKey.ControlStart，进入下一个状态\n            当有玩家掉线，则从FSPGame中删除该玩家：\n                判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPGameState.ControlStart\">\n            <summary>\n            可以开始操作状态\n            （因为每个回合可能都会有加载过程，不同的玩家加载速度可能不同，需要用一个状态统一一下）\n            在该状态下，接收玩家的业务VKey， 或者 VKey.RoundEnd，或者VKey.GameExit\n            当所有人都发送VKey.RoundEnd，进入下一个状态\n            当有玩家掉线，或者发送VKey.GameExit，则从FSPGame中删除该玩家：\n                判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPGameState.RoundEnd\">\n            <summary>\n            回合结束状态\n            （大部分游戏只有1个回合，也有些游戏有多个回合，由客户端逻辑决定）\n            在该状态下，等待玩家发送VKey.GameEnd，或者 VKey.RoundBegin（如果游戏不只1个回合的话）\n            当所有人都发送VKey.GameEnd，或者 VKey.RoundBegin时，进入下一个状态\n            当有玩家掉线，则从FSPGame中删除该玩家：\n                判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPGameState.GameEnd\">\n            <summary>\n            游戏结束状态\n            在该状态下，不再接收任何Vkey，然后给所有玩家发VKey.GameEnd，并且等待FSPServer关闭\n            </summary>\n        </member>\n        <member name=\"T:SGF.Network.FSPLite.FSPVKey\">\n            <summary>\n            为了兼容键盘和轮盘操作，将玩家的操作抽象为【虚拟按键+参数】的【命令】形式：VKey+Arg\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKey.vkey\">\n            <summary>\n            键值\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKey.args\">\n            <summary>\n            参数列表\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKey.playerIdOrClientFrameId\">\n            <summary>\n            S2C  服务器下发PlayerId\n            C2S  客户端上报ClientFrameId\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKeyBase.GAME_BEGIN\">\n            <summary>\n            PVP战斗结束\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKeyBase.ROUND_BEGIN\">\n            <summary>\n            对局开始\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKeyBase.LOAD_START\">\n            <summary>\n            开始加载\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKeyBase.LOAD_PROGRESS\">\n            <summary>\n            加载进度条\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKeyBase.CONTROL_START\">\n            <summary>\n            可以开始控制...\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKeyBase.GAME_EXIT\">\n            <summary>\n            发送中途退出\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKeyBase.ROUND_END\">\n            <summary>\n            对局结束\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKeyBase.GAME_END\">\n            <summary>\n            PVP战斗结束\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKeyBase.AUTH\">\n            <summary>\n            UDP身份字段\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.FSPVKeyBase.PING\">\n            <summary>\n            PING 响应回包...\n            </summary>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.Server.FSPGame.MaxPlayerNum\">\n            <summary>\n            最大支持的玩家数：31\n            因为用来保存玩家Flag的Int只有31位有效位可用，不过31已经足够了\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Server.FSPGame.HandleClientCmd(SGF.Network.FSPLite.Server.FSPPlayer,SGF.Network.FSPLite.FSPVKey)\">\n            <summary>\n            处理来自客户端的 Cmd\n            对其中的关键VKey进行处理\n            并且收集业务VKey\n            </summary>\n            <param name=\"player\"></param>\n            <param name=\"cmd\"></param>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Server.FSPGame.EnterFrame\">\n            <summary>\n            驱动游戏状态\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Server.FSPGame.CheckGameAbnormalEnd\">\n            <summary>\n            检测游戏是否异常结束\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Server.FSPGame.OnState_Create\">\n            <summary>\n            游戏创建状态\n            只有在该状态下，才允许加入玩家\n            当所有玩家都发VKey.GameBegin后，进入下一个状态\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Server.FSPGame.OnState_GameBegin\">\n            <summary>\n            游戏开始状态\n            在该状态下，等待所有玩家发VKey.RoundBegin，或者 判断玩家是否掉线\n            当所有人都发送VKey.RoundBegin，进入下一个状态\n            当有玩家掉线，则从FSPGame中删除该玩家：\n                判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Server.FSPGame.OnState_RoundBegin\">\n            <summary>\n            回合开始状态\n            （这个时候客户端可能在加载资源）\n            在该状态下，等待所有玩家发VKey.ControlStart， 或者 判断玩家是否掉线\n            当所有人都发送VKey.ControlStart，进入下一个状态\n            当有玩家掉线，则从FSPGame中删除该玩家：\n                判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Server.FSPGame.OnState_ControlStart\">\n            <summary>\n            可以开始操作状态\n            （因为每个回合可能都会有加载过程，不同的玩家加载速度可能不同，需要用一个状态统一一下）\n            在该状态下，接收玩家的业务VKey， 或者 VKey.RoundEnd，或者VKey.GameExit\n            当所有人都发送VKey.RoundEnd，进入下一个状态\n            当有玩家掉线，或者发送VKey.GameExit，则从FSPGame中删除该玩家：\n                判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Server.FSPGame.OnState_RoundEnd\">\n            <summary>\n            回合结束状态\n            （大部分游戏只有1个回合，也有些游戏有多个回合，由客户端逻辑决定）\n            在该状态下，等待玩家发送VKey.GameEnd，或者 VKey.RoundBegin（如果游戏不只1个回合的话）\n            当所有人都发送VKey.GameEnd，或者 VKey.RoundBegin时，进入下一个状态\n            当有玩家掉线，则从FSPGame中删除该玩家：\n                判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n            </summary>\n        </member>\n        <member name=\"M:SGF.Network.FSPLite.Server.FSPPlayer.IsLose\">\n            <summary>\n            判断是否掉线\n            </summary>\n            <returns></returns>\n        </member>\n        <member name=\"F:SGF.Network.FSPLite.Server.FSPServer.FRAME_TICK_INTERVAL\">\n            <summary>\n            帧间隔...\n            </summary>\n        </member>\n        <member name=\"M:SGF.Utils.TimeUtils.GetTimeStringV2(System.String,System.Int64)\">\n            <summary>\n            如果不显示天, 显示hh就会显示所有小时, 但是又怕有地方需要这样, 因此这里新开一下\n            </summary>\n            <param name=\"format\"></param>\n            <param name=\"seconds\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"T:MiniJSON.Json\">\n             <summary>\n             This class encodes and decodes JSON strings.\n             Spec. details, see http://www.json.org/\n            \n             JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.\n             All numbers are parsed to doubles.\n             </summary>\n        </member>\n        <member name=\"M:MiniJSON.Json.Deserialize(System.String)\">\n            <summary>\n            Parses the string json into a value\n            </summary>\n            <param name=\"json\">A JSON string.</param>\n            <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns>\n        </member>\n        <member name=\"M:MiniJSON.Json.Serialize(System.Object)\">\n            <summary>\n            Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string\n            </summary>\n            <param name=\"json\">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param>\n            <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>\n        </member>\n        <member name=\"M:CollectionExtensions.FilterByType``2(System.Collections.Generic.IEnumerable{``0})\">\n                    Returns all elements of the source which are of FilterType.\n        </member>\n        <member name=\"M:CollectionExtensions.RemoveAllBut``1(System.Collections.Generic.List{``0},System.Predicate{``0})\">\n            <summary>\n            移除不符合条件的元素\n            </summary>\n            <typeparam name=\"T\"></typeparam>\n            <param name=\"source\"></param>\n            <param name=\"match\"></param>\n        </member>\n        <member name=\"M:CollectionExtensions.IsEmpty``1(System.Collections.Generic.ICollection{``0})\">\n            <summary>\n            返回容器是否为空\n            </summary>\n            <typeparam name=\"T\"></typeparam>\n            <param name=\"collection\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"M:CollectionExtensions.AddRange``1(System.Collections.Generic.ICollection{``0},System.Collections.Generic.IEnumerable{``0})\">\n            <summary>\n            批量追加元素\n            </summary>\n            <typeparam name=\"T\"></typeparam>\n            <param name=\"collection\"></param>\n            <param name=\"other\"></param>\n        </member>\n        <member name=\"M:CollectionExtensions.ListToString``1(System.Collections.Generic.IEnumerable{``0})\">\n            <summary>\n            将容器序列化成字符串\n            格式：{a, b, c}\n            </summary>\n            <typeparam name=\"T\"></typeparam>\n            <param name=\"source\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"M:CollectionExtensions.ListToString(System.Object)\">\n            <summary>\n            将容器序列化成字符串\n            </summary>\n            <param name=\"obj\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"M:CollectionExtensions.ButFirst``1(System.Collections.Generic.IEnumerable{``0})\">\n                    Returns an enumerable of all elements of the given list\tbut the first,\n                    keeping them in order.\n        </member>\n        <member name=\"M:CollectionExtensions.ButLast``1(System.Collections.Generic.IEnumerable{``0})\">\n                    Returns an enumarable of all elements in the given \n                    list but the last, keeping them in order.\n        </member>\n        <member name=\"M:CollectionExtensions.MaxBy``1(System.Collections.Generic.IEnumerable{``0},System.Func{``0,System.IComparable})\">\n            <summary>\n            根据给定的方法，求出容器中最大的元素\n            </summary>\n            <typeparam name=\"T\"></typeparam>\n            <param name=\"source\"></param>\n            <param name=\"score\"></param>\n            <returns></returns>\n        </member>\n        <member name=\"M:CollectionExtensions.MinBy``2(System.Collections.Generic.IEnumerable{``0},System.Func{``0,``1})\">\n                    Finds the maximum element in the source as scored by the given function.\n        </member>\n        <member name=\"M:CollectionExtensions.RotateLeft``1(System.Collections.Generic.IEnumerable{``0})\">\n                    Returns a enumerable with elements in order, but the first element is moved to the end.\n        </member>\n        <member name=\"M:CollectionExtensions.RotateRight``1(System.Collections.Generic.IEnumerable{``0})\">\n                    Returns a enumerable with elements in order, but the last element is moved to the front.\n        </member>\n        <member name=\"M:CollectionExtensions.RandomItem``1(System.Collections.Generic.IEnumerable{``0})\">\n                    Returns a random element from the list.\n        </member>\n        <member name=\"M:CollectionExtensions.SampleRandom``1(System.Collections.Generic.IEnumerable{``0},System.Int32)\">\n                    Returns a random sample from the list.\n        </member>\n        <member name=\"M:CollectionExtensions.Shuffle``1(System.Collections.Generic.IList{``0})\">\n            <summary>\n            乱序\n            </summary>\n            <typeparam name=\"T\"></typeparam>\n            <param name=\"source\"></param>\n        </member>\n        <member name=\"M:CollectionExtensions.BinarySearch``2(System.Collections.Generic.ICollection{``0},``1,System.Func{``0,``1})\">\n                    Find an element in a collection by binary searching. \n                    This requires the collection to be sorted on the values returned by getSubElement\n                    This will compare some derived property of the elements in the collection, rather than the elements\n                    themselves.\n        </member>\n        <member name=\"M:CollectionExtensions.BinarySearch``2(System.Collections.Generic.ICollection{``0},``1,System.Func{``0,``1},System.Collections.Generic.IComparer{``1})\">\n                    Find an element in a collection by binary searching. \n                    This requires the collection to be sorted on the values returned by getSubElement\n                    This will compare some derived property of the elements in the collection, rather than the elements\n                    themselves.\n        </member>\n        <member name=\"M:CollectionExtensions.BinarySearch``2(System.Collections.Generic.ICollection{``0},``1,System.Func{``0,``1},System.Int32,System.Int32)\">\n                    Find an element in a collection by binary searching. \n                    This requires the collection to be sorted on the values returned by getSubElement\n                    This will compare some derived property of the elements in the collection, rather than the elements\n                    themselves.\n        </member>\n        <member name=\"M:CollectionExtensions.BinarySearch``2(System.Collections.Generic.ICollection{``0},``1,System.Func{``0,``1},System.Int32,System.Int32,System.Collections.Generic.IComparer{``1})\">\n                    Find an element in a collection by binary searching. \n                    This requires the collection to be sorted on the values returned by getSubElement\n                    This will compare some derived property of the elements in the collection, rather than the elements\n                    themselves.\n        </member>\n        <member name=\"M:ObjectExtensions.ThrowIfNull(System.Object,System.String)\">\n            <summary>\n            对象如果为Null，抛出异常\n            </summary>\n            <param name=\"o\"></param>\n            <param name=\"message\">异常消息</param>\n        </member>\n    </members>\n</doc>\n"
  },
  {
    "path": "Apps/SGFServer.exe.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "Apps/SGFServerDemo.exe.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "ILRuntime/App.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Adapters/Editor/ILRuntimeCLRBinding.cs",
    "content": "﻿#if UNITY_EDITOR\nusing UnityEditor;\nusing UnityEngine;\nusing System;\nusing System.Text;\nusing System.Collections.Generic;\nusing OT.Foundation;\n\n[System.Reflection.Obfuscation(Exclude = true)]\npublic class ILRuntimeCLRBinding\n{\n    [MenuItem(\"ILRuntime/Generate CLR Binding Code\")]\n    static void GenerateCLRBinding()\n    {\n        List<Type> types = new List<Type>();\n        types.Add(typeof(int));\n        types.Add(typeof(float));\n        types.Add(typeof(long));\n        types.Add(typeof(object));\n        types.Add(typeof(string));\n        types.Add(typeof(Array));\n        types.Add(typeof(Vector2));\n        types.Add(typeof(Vector3));\n        types.Add(typeof(Quaternion));\n        types.Add(typeof(GameObject));\n        types.Add(typeof(UnityEngine.Object));\n        types.Add(typeof(Transform));\n        types.Add(typeof(RectTransform));\n        types.Add(typeof(CLRBindingTestClass));\n        types.Add(typeof(Time));\n        types.Add(typeof(Debug));\n        types.Add(typeof(OT.Foundation.Debuger));\n        //所有DLL内的类型的真实C#类型都是ILTypeInstance\n        types.Add(typeof(List<ILRuntime.Runtime.Intepreter.ILTypeInstance>));\n\n        ILRuntime.Runtime.CLRBinding.BindingCodeGenerator.GenerateBindingCode(types, \"Assets/ILRuntime/Generated\");\n\n    }\n\n    [MenuItem(\"ILRuntime/Generate CLR Binding Code by Analysis\")]\n    static void GenerateCLRBindingByAnalysis()\n    {\n        //用新的分析热更dll调用引用来生成绑定代码\n        ILRuntime.Runtime.Enviorment.AppDomain domain = new ILRuntime.Runtime.Enviorment.AppDomain();\n        using (System.IO.FileStream fs = new System.IO.FileStream(\"Assets/StreamingAssets/HotFix_Project.dll\", System.IO.FileMode.Open, System.IO.FileAccess.Read))\n        {\n            domain.LoadAssembly(fs);\n        }\n        //Crossbind Adapter is needed to generate the correct binding code\n        InitILRuntime(domain);\n        ILRuntime.Runtime.CLRBinding.BindingCodeGenerator.GenerateBindingCode(domain, \"Assets/ILRuntime/Generated\");\n    }\n\n    static void InitILRuntime(ILRuntime.Runtime.Enviorment.AppDomain domain)\n    {\n        //这里需要注册所有热更DLL中用到的跨域继承Adapter，否则无法正确抓取引用\n        domain.RegisterCrossBindingAdaptor(new MonoBehaviourAdapter());\n        domain.RegisterCrossBindingAdaptor(new CoroutineAdapter());\n        domain.RegisterCrossBindingAdaptor(new InheritanceAdapter());\n    }\n}\n#endif\n"
  },
  {
    "path": "ILRuntime/ILRuntime/CLR/Method/CLRMethod.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\n\nusing Mono.Cecil;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.CLR.Utils;\nnamespace ILRuntime.CLR.Method\n{\n    public class CLRMethod : IMethod\n    {\n        MethodInfo def;\n        ConstructorInfo cDef;\n        List<IType> parameters;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n        CLRType declaringType;\n        ParameterInfo[] param;\n        bool isConstructor;\n        CLRRedirectionDelegate redirect;\n        IType[] genericArguments;\n        object[] invocationParam;\n        bool isDelegateInvoke;\n        int hashCode = -1;\n        static int instance_id = 0x20000000;\n\n        public IType DeclearingType\n        {\n            get\n            {\n                return declaringType;\n            }\n        }\n        public string Name\n        {\n            get\n            {\n                return def.Name;\n            }\n        }\n        public bool HasThis\n        {\n            get\n            {\n                return isConstructor ? !cDef.IsStatic : !def.IsStatic;\n            }\n        }\n        public int GenericParameterCount\n        {\n            get\n            {\n                if (def.ContainsGenericParameters && def.IsGenericMethodDefinition)\n                {\n                    return def.GetGenericArguments().Length;\n                }\n                return 0;\n            }\n        }\n        public bool IsGenericInstance\n        {\n            get\n            {\n                return genericArguments != null;\n            }\n        }\n\n        public bool IsDelegateInvoke\n        {\n            get\n            {\n                return isDelegateInvoke;\n            }\n        }\n\n        public bool IsStatic\n        {\n            get { return def.IsStatic; }\n        }\n\n        public CLRRedirectionDelegate Redirection { get { return redirect; } }\n\n        public MethodInfo MethodInfo { get { return def; } }\n\n        public ConstructorInfo ConstructorInfo { get { return cDef; } }\n\n        public IType[] GenericArguments { get { return genericArguments; } }\n\n        internal CLRMethod(MethodInfo def, CLRType type, ILRuntime.Runtime.Enviorment.AppDomain domain)\n        {\n            this.def = def;\n            declaringType = type;\n            this.appdomain = domain;\n            param = def.GetParameters();\n            if (!def.ContainsGenericParameters)\n            {\n                ReturnType = domain.GetType(def.ReturnType.FullName);\n                if (ReturnType == null)\n                {\n                    ReturnType = domain.GetType(def.ReturnType.AssemblyQualifiedName);\n                }\n            }\n            if (type.IsDelegate && def.Name == \"Invoke\")\n                isDelegateInvoke = true;\n            isConstructor = false;\n\n            if (def != null)\n            {\n                if (def.IsGenericMethod && !def.IsGenericMethodDefinition)\n                {\n                    appdomain.RedirectMap.TryGetValue(def.GetGenericMethodDefinition(), out redirect);\n                }\n                else\n                    appdomain.RedirectMap.TryGetValue(def, out redirect);\n            }\n        }\n        internal CLRMethod(ConstructorInfo def, CLRType type, ILRuntime.Runtime.Enviorment.AppDomain domain)\n        {\n            this.cDef = def;\n            declaringType = type;\n            this.appdomain = domain;\n            param = def.GetParameters();\n            if (!def.ContainsGenericParameters)\n            {\n                ReturnType = type;\n            }\n            isConstructor = true;\n\n            if (def != null)\n            {\n                appdomain.RedirectMap.TryGetValue(cDef, out redirect);\n            }\n        }\n\n        public int ParameterCount\n        {\n            get\n            {\n                return param != null ? param.Length : 0;\n            }\n        }\n\n\n        public List<IType> Parameters\n        {\n            get\n            {\n                if (parameters == null)\n                {\n                    InitParameters();\n                }\n                return parameters;\n            }\n        }\n\n        public IType ReturnType\n        {\n            get;\n            private set;\n        }\n\n        public bool IsConstructor\n        {\n            get\n            {\n                return cDef != null;\n            }\n        }\n\n        void InitParameters()\n        {\n            parameters = new List<IType>();\n            foreach (var i in param)\n            {\n                IType type = appdomain.GetType(i.ParameterType.FullName);\n                if (type == null)\n                    type = appdomain.GetType(i.ParameterType.AssemblyQualifiedName);\n                if (i.ParameterType.IsGenericTypeDefinition)\n                {\n                    if (type == null)\n                        type = appdomain.GetType(i.ParameterType.GetGenericTypeDefinition().FullName);\n                    if (type == null)\n                        type = appdomain.GetType(i.ParameterType.GetGenericTypeDefinition().AssemblyQualifiedName);\n                }\n                if (i.ParameterType.ContainsGenericParameters)\n                {\n                    var t = i.ParameterType;\n                    if (t.HasElementType)\n                        t = i.ParameterType.GetElementType();\n                    else if (t.GetGenericArguments().Length > 0)\n                    {\n                        t = t.GetGenericArguments()[0];\n                    }\n                    type = new ILGenericParameterType(t.Name);\n                }\n                if (type == null)\n                    throw new TypeLoadException();\n                parameters.Add(type);\n            }\n        }\n\n        unsafe StackObject* Minus(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a - sizeof(StackObject) * b);\n        }\n\n        public unsafe object Invoke(Runtime.Intepreter.ILIntepreter intepreter, StackObject* esp, IList<object> mStack, bool isNewObj = false)\n        {\n            if (parameters == null)\n            {\n                InitParameters();\n            }\n            int paramCount = ParameterCount;\n            if (invocationParam == null)\n                invocationParam = new object[paramCount];\n            object[] param = invocationParam;\n            for (int i = paramCount; i >= 1; i--)\n            {\n                var p = Minus(esp, i);\n                var obj = this.param[paramCount - i].ParameterType.CheckCLRTypes(StackObject.ToObject(p, appdomain, mStack));\n                obj = ILIntepreter.CheckAndCloneValueType(obj, appdomain);\n                param[paramCount - i] = obj;\n            }\n\n            if (isConstructor)\n            {\n                if (!isNewObj)\n                {\n                    if (!cDef.IsStatic)\n                    {\n                        object instance = declaringType.TypeForCLR.CheckCLRTypes(StackObject.ToObject((Minus(esp, paramCount + 1)), appdomain, mStack));\n                        if (instance == null)\n                            throw new NullReferenceException();\n                        if (instance is CrossBindingAdaptorType && paramCount == 0)//It makes no sense to call the Adaptor's default constructor\n                            return null;\n                        cDef.Invoke(instance, param);\n                        return null;\n                    }\n                    else\n                    {\n                        throw new NotImplementedException();\n                    }\n                }\n                else\n                {\n                    var res = cDef.Invoke(param);\n\n                    FixReference(paramCount, esp, param, mStack);\n                    return res;\n                }\n\n            }\n            else\n            {\n                object instance = null;\n\n                if (!def.IsStatic)\n                {\n                    instance = declaringType.TypeForCLR.CheckCLRTypes(StackObject.ToObject((Minus(esp, paramCount + 1)), appdomain, mStack));\n                    if (instance == null)\n                        throw new NullReferenceException();\n                }\n                object res = null;\n                /*if (redirect != null)\n                    res = redirect(new ILContext(appdomain, intepreter, esp, mStack, this), instance, param, genericArguments);\n                else*/\n                {\n                    res = def.Invoke(instance, param);\n                }\n\n                FixReference(paramCount, esp, param, mStack);\n                return res;\n            }\n        }\n\n        unsafe void FixReference(int paramCount, StackObject* esp, object[] param, IList<object> mStack)\n        {\n            for (int i = paramCount; i >= 1; i--)\n            {\n                var p = Minus(esp, i);\n                var val = param[paramCount - i];\n                switch (p->ObjectType)\n                {\n                    case ObjectTypes.StackObjectReference:\n                        {\n                            var dst = *(StackObject**)&p->Value;\n                            if (dst->ObjectType >= ObjectTypes.Object)\n                            {\n                                var obj = val;\n                                if (obj is CrossBindingAdaptorType)\n                                    obj = ((CrossBindingAdaptorType)obj).ILInstance;\n                                mStack[dst->Value] = obj;\n                            }\n                            else\n                            {\n                                ILIntepreter.UnboxObject(dst, val);\n                            }\n                        }\n                        break;\n                    case ObjectTypes.FieldReference:\n                        {\n                            var obj = mStack[p->Value];\n                            if(obj is ILTypeInstance)\n                            {\n                                ((ILTypeInstance)obj)[p->ValueLow] = val;\n                            }\n                            else\n                            {\n                                var t = appdomain.GetType(obj.GetType()) as CLRType;\n                                t.GetField(p->ValueLow).SetValue(obj, val);\n                            }\n                        }\n                        break;\n                    case ObjectTypes.StaticFieldReference:\n                        {\n                            var t = appdomain.GetType(p->Value);\n                            if(t is ILType)\n                            {\n                                ((ILType)t).StaticInstance[p->ValueLow] = val;\n                            }\n                            else\n                            {\n                                ((CLRType)t).SetStaticFieldValue(p->ValueLow, val);\n                            }\n                        }\n                        break;\n                }\n            }\n        }\n\n        public IMethod MakeGenericMethod(IType[] genericArguments)\n        {\n            Type[] p = new Type[genericArguments.Length];\n            for (int i = 0; i < genericArguments.Length; i++)\n            {\n                p[i] = genericArguments[i].TypeForCLR;\n            }\n            var t = def.MakeGenericMethod(p);\n            var res = new CLRMethod(t, declaringType, appdomain);\n            res.genericArguments = genericArguments;\n            return res;\n        }\n\n        public override string ToString()\n        {\n            if (def != null)\n                return def.ToString();\n            else\n                return cDef.ToString();\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/CLR/Method/ExceptionHandler.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.TypeSystem;\n\nnamespace ILRuntime.CLR.Method\n{\n    enum ExceptionHandlerType\n    {\n        Catch,\n        Finally,\n        Fault,\n    }\n    class ExceptionHandler\n    {\n        public ExceptionHandlerType HandlerType { get; set; }\n\n        public int TryStart { get; set; }\n        public int TryEnd { get; set; }\n        public int HandlerStart { get; set; }\n        public int HandlerEnd { get; set; }\n        public IType CatchType { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/CLR/Method/ILMethod.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nusing Mono.Cecil;\nusing ILRuntime.Runtime.Intepreter.OpCodes;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Debugger;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Reflection;\nnamespace ILRuntime.CLR.Method\n{\n    public class ILMethod : IMethod\n    {\n        OpCode[] body;\n        MethodDefinition def;\n        List<IType> parameters;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n        ILType declaringType;\n        ExceptionHandler[] exceptionHandler;\n        KeyValuePair<string, IType>[] genericParameters;\n        IType[] genericArguments;\n        Dictionary<int, int[]> jumptables;\n        bool isDelegateInvoke;\n        ILRuntimeMethodInfo refletionMethodInfo;\n        ILRuntimeConstructorInfo reflectionCtorInfo;\n        int paramCnt, localVarCnt;\n        Mono.Collections.Generic.Collection<Mono.Cecil.Cil.VariableDefinition> variables;\n        int hashCode = -1;\n        static int instance_id = 0x10000000;\n\n        public MethodDefinition Definition { get { return def; } }\n\n        public Dictionary<int, int[]> JumpTables { get { return jumptables; } }\n\n        internal IDelegateAdapter DelegateAdapter { get; set; }\n\n        internal int StartLine { get; set; }\n\n        internal int EndLine { get; set; }\n\n        public MethodInfo ReflectionMethodInfo\n        {\n            get\n            {\n                if (IsConstructor)\n                    throw new NotSupportedException();\n                if (refletionMethodInfo == null)\n                    refletionMethodInfo = new ILRuntimeMethodInfo(this);\n                return refletionMethodInfo;\n            }\n        }\n\n        public ConstructorInfo ReflectionConstructorInfo\n        {\n            get\n            {\n                if (!IsConstructor)\n                    throw new NotSupportedException();\n                if (reflectionCtorInfo == null)\n                    reflectionCtorInfo = new ILRuntimeConstructorInfo(this);\n                return reflectionCtorInfo;\n            }\n        }\n\n        internal ExceptionHandler[] ExceptionHandler\n        {\n            get\n            {\n                if (body == null)\n                    InitCodeBody();\n                return exceptionHandler;\n            }\n        }\n\n        public string Name\n        {\n            get\n            {\n                return def.Name;\n            }\n        }\n\n        public IType DeclearingType\n        {\n            get\n            {\n                return declaringType;\n            }\n        }\n\n        public bool HasThis\n        {\n            get\n            {\n                return def.HasThis;\n            }\n        }\n        public int GenericParameterCount\n        {\n            get\n            {\n                if (IsGenericInstance)\n                    return 0;\n                return def.GenericParameters.Count;\n            }\n        }\n        public bool IsGenericInstance\n        {\n            get\n            {\n                return genericParameters != null;\n            }\n        }\n        public Mono.Collections.Generic.Collection<Mono.Cecil.Cil.VariableDefinition> Variables\n        {\n            get\n            {\n                return variables;\n            }\n        }\n\n        public KeyValuePair<string, IType>[] GenericArguments { get { return genericParameters; } }\n\n        public IType[] GenericArugmentsArray { get { return genericArguments; } }\n        public ILMethod(MethodDefinition def, ILType type, ILRuntime.Runtime.Enviorment.AppDomain domain)\n        {\n            this.def = def;\n            declaringType = type;\n            if (def.ReturnType.IsGenericParameter)\n            {\n                ReturnType = FindGenericArgument(def.ReturnType.Name);\n            }\n            else\n                ReturnType = domain.GetType(def.ReturnType, type, this);\n            if (type.IsDelegate && def.Name == \"Invoke\")\n                isDelegateInvoke = true;\n            this.appdomain = domain;\n            paramCnt = def.HasParameters ? def.Parameters.Count : 0;\n#if DEBUG\n            if (def.HasBody)\n            {\n                var sp = DebugService.FindSequencePoint(def.Body.Instructions[0]);\n                if (sp != null)\n                {\n                    StartLine = sp.StartLine;\n                    sp = DebugService.FindSequencePoint(def.Body.Instructions[def.Body.Instructions.Count - 1]);\n                    if (sp != null)\n                    {\n                        EndLine = sp.EndLine;\n                    }\n                }\n            }\n#endif\n        }\n\n        public IType FindGenericArgument(string name)\n        {\n            IType res = declaringType.FindGenericArgument(name);\n            if (res == null && genericParameters != null)\n            {\n                foreach (var i in genericParameters)\n                {\n                    if (i.Key == name)\n                        return i.Value;\n                }\n            }\n            else\n                return res;\n            return null;\n        }\n\n        internal OpCode[] Body\n        {\n            get\n            {\n                if (body == null)\n                    InitCodeBody();\n                return body;\n            }\n        }\n\n        public int LocalVariableCount\n        {\n            get\n            {\n                return localVarCnt;\n            }\n        }\n\n        public bool IsConstructor\n        {\n            get\n            {\n                return def.IsConstructor;\n            }\n        }\n\n        public bool IsDelegateInvoke\n        {\n            get\n            {\n                return isDelegateInvoke;\n            }\n        }\n\n        public bool IsStatic\n        {\n            get { return def.IsStatic; }\n        }\n\n        public int ParameterCount\n        {\n            get\n            {\n                return paramCnt;\n            }\n        }\n\n\n        public List<IType> Parameters\n        {\n            get\n            {\n                if (def.HasParameters && parameters == null)\n                {\n                    InitParameters();\n                }\n                return parameters;\n            }\n        }\n\n        public IType ReturnType\n        {\n            get;\n            private set;\n        }\n        void InitCodeBody()\n        {\n            if (def.HasBody)\n            {\n                localVarCnt = def.Body.Variables.Count;\n                body = new OpCode[def.Body.Instructions.Count];\n                Dictionary<Mono.Cecil.Cil.Instruction, int> addr = new Dictionary<Mono.Cecil.Cil.Instruction, int>();\n                for (int i = 0; i < body.Length; i++)\n                {\n                    var c = def.Body.Instructions[i];\n                    OpCode code = new OpCode();\n                    code.Code = (OpCodeEnum)c.OpCode.Code;\n                    addr[c] = i;\n                    body[i] = code;\n                }\n                for (int i = 0; i < body.Length; i++)\n                {\n                    var c = def.Body.Instructions[i];\n                    InitToken(ref body[i], c.Operand, addr);\n                }\n\n                for (int i = 0; i < def.Body.ExceptionHandlers.Count; i++)\n                {\n                    var eh = def.Body.ExceptionHandlers[i];\n                    if (exceptionHandler == null)\n                        exceptionHandler = new Method.ExceptionHandler[def.Body.ExceptionHandlers.Count];\n                    ExceptionHandler e = new ExceptionHandler();\n                    e.HandlerStart = addr[eh.HandlerStart];\n                    e.HandlerEnd = addr[eh.HandlerEnd] - 1;\n                    e.TryStart = addr[eh.TryStart];\n                    e.TryEnd = addr[eh.TryEnd] - 1;\n                    switch (eh.HandlerType)\n                    {\n                        case Mono.Cecil.Cil.ExceptionHandlerType.Catch:\n                            e.CatchType = appdomain.GetType(eh.CatchType, declaringType, this);\n                            e.HandlerType = ExceptionHandlerType.Catch;\n                            break;\n                        case Mono.Cecil.Cil.ExceptionHandlerType.Finally:\n                            e.HandlerType = ExceptionHandlerType.Finally;\n                            break;\n                        case Mono.Cecil.Cil.ExceptionHandlerType.Fault:\n                            e.HandlerType = ExceptionHandlerType.Fault;\n                            break;\n                        default:\n                            throw new NotImplementedException();\n                    }\n                    exceptionHandler[i] = e;\n                    //Mono.Cecil.Cil.ExceptionHandlerType.\n                }\n                //Release Method body to save memory\n                variables = def.Body.Variables;\n                def.Body = null;\n            }\n            else\n                body = new OpCode[0];\n        }\n\n        unsafe void InitToken(ref OpCode code, object token, Dictionary<Mono.Cecil.Cil.Instruction, int> addr)\n        {\n            switch (code.Code)\n            {\n                case OpCodeEnum.Leave:\n                case OpCodeEnum.Leave_S:\n                case OpCodeEnum.Br:\n                case OpCodeEnum.Br_S:\n                case OpCodeEnum.Brtrue:\n                case OpCodeEnum.Brtrue_S:\n                case OpCodeEnum.Brfalse:\n                case OpCodeEnum.Brfalse_S:\n                //比较流程控制\n                case OpCodeEnum.Beq:\n                case OpCodeEnum.Beq_S:\n                case OpCodeEnum.Bne_Un:\n                case OpCodeEnum.Bne_Un_S:\n                case OpCodeEnum.Bge:\n                case OpCodeEnum.Bge_S:\n                case OpCodeEnum.Bge_Un:\n                case OpCodeEnum.Bge_Un_S:\n                case OpCodeEnum.Bgt:\n                case OpCodeEnum.Bgt_S:\n                case OpCodeEnum.Bgt_Un:\n                case OpCodeEnum.Bgt_Un_S:\n                case OpCodeEnum.Ble:\n                case OpCodeEnum.Ble_S:\n                case OpCodeEnum.Ble_Un:\n                case OpCodeEnum.Ble_Un_S:\n                case OpCodeEnum.Blt:\n                case OpCodeEnum.Blt_S:\n                case OpCodeEnum.Blt_Un:\n                case OpCodeEnum.Blt_Un_S:\n                    code.TokenInteger = addr[(Mono.Cecil.Cil.Instruction)token];\n                    break;\n                case OpCodeEnum.Ldc_I4:\n                    code.TokenInteger = (int)token;\n                    break;\n                case OpCodeEnum.Ldc_I4_S:\n                    code.TokenInteger = (sbyte)token;\n                    break;\n                case OpCodeEnum.Ldc_I8:\n                    code.TokenLong = (long)token;\n                    break;\n                case OpCodeEnum.Ldc_R4:\n                    {\n                        float val = (float)token;\n                        code.TokenInteger = *(int*)&val;\n                    }\n                    break;\n                case OpCodeEnum.Ldc_R8:\n                    {\n                        double val = (double)token;\n                        code.TokenLong = *(long*)&val;\n                    }\n                    break;\n                case OpCodeEnum.Stloc:\n                case OpCodeEnum.Stloc_S:\n                case OpCodeEnum.Ldloc:\n                case OpCodeEnum.Ldloc_S:\n                case OpCodeEnum.Ldloca:\n                case OpCodeEnum.Ldloca_S:\n                    {\n                        Mono.Cecil.Cil.VariableDefinition vd = (Mono.Cecil.Cil.VariableDefinition)token;\n                        code.TokenInteger = vd.Index;\n                    }\n                    break;\n                case OpCodeEnum.Ldarg_S:\n                case OpCodeEnum.Ldarg:\n                case OpCodeEnum.Ldarga:\n                case OpCodeEnum.Ldarga_S:\n                case OpCodeEnum.Starg:\n                case OpCodeEnum.Starg_S:\n                    {\n                        Mono.Cecil.ParameterDefinition vd = (Mono.Cecil.ParameterDefinition)token;\n                        code.TokenInteger = vd.Index;\n                        if (HasThis)\n                            code.TokenInteger++;\n                    }\n                    break;\n                case OpCodeEnum.Call:\n                case OpCodeEnum.Newobj:\n                case OpCodeEnum.Ldftn:\n                case OpCodeEnum.Ldvirtftn:\n                case OpCodeEnum.Callvirt:\n                    {\n                        bool invalidToken;\n                        var m = appdomain.GetMethod(token, declaringType, this, out invalidToken);\n                        if (m != null)\n                        {\n                            if (invalidToken)\n                                code.TokenInteger = m.GetHashCode();\n                            else\n                                code.TokenInteger = token.GetHashCode();\n                        }\n                        else\n                        {\n                            //Cannot find method or the method is dummy\n                            MethodReference _ref = (MethodReference)token;\n                            int paramCnt = _ref.HasParameters ? _ref.Parameters.Count : 0;\n                            if (_ref.HasThis)\n                                paramCnt++;\n                            code.TokenLong = paramCnt;\n                        }\n                    }\n                    break;\n                case OpCodeEnum.Constrained:\n                case OpCodeEnum.Box:\n                case OpCodeEnum.Unbox_Any:\n                case OpCodeEnum.Unbox:\n                case OpCodeEnum.Initobj:\n                case OpCodeEnum.Isinst:\n                case OpCodeEnum.Newarr:\n                case OpCodeEnum.Stobj:\n                case OpCodeEnum.Ldobj:\n                    {\n                        code.TokenInteger = GetTypeTokenHashCode(token);\n                    }\n                    break;\n                case OpCodeEnum.Stfld:\n                case OpCodeEnum.Ldfld:\n                case OpCodeEnum.Ldflda:\n                    {\n                        code.TokenLong = appdomain.GetStaticFieldIndex(token, declaringType, this);\n                    }\n                    break;\n\n                case OpCodeEnum.Stsfld:\n                case OpCodeEnum.Ldsfld:\n                case OpCodeEnum.Ldsflda:\n                    {\n                        code.TokenLong = appdomain.GetStaticFieldIndex(token, declaringType, this);\n                    }\n                    break;\n                case OpCodeEnum.Ldstr:\n                    {\n                        long hashCode = appdomain.CacheString(token);\n                        code.TokenLong = hashCode;\n                    }\n                    break;\n                case OpCodeEnum.Ldtoken:\n                    {\n                        if (token is FieldReference)\n                        {\n                            code.TokenInteger = 0;\n                            code.TokenLong = appdomain.GetStaticFieldIndex(token, declaringType, this);\n                        }\n                        else if (token is TypeReference)\n                        {\n                            code.TokenInteger = 1;\n                            code.TokenLong = GetTypeTokenHashCode(token);\n                        }\n                        else\n                            throw new NotImplementedException();\n                    }\n                    break;\n                case OpCodeEnum.Switch:\n                    {\n                        PrepareJumpTable(token, addr);\n                        code.TokenInteger = token.GetHashCode();\n                    }\n                    break;\n            }\n        }\n\n        int GetTypeTokenHashCode(object token)\n        {\n            var t = appdomain.GetType(token, declaringType, this);\n            bool isGenericParameter = CheckHasGenericParamter(token);\n            if (t == null && isGenericParameter)\n            {\n                t = FindGenericArgument(((TypeReference)token).Name);\n            }\n            if (t != null)\n            {\n                if (t is ILType)\n                {\n                    if (((ILType)t).TypeReference.HasGenericParameters)\n                        return t.GetHashCode();\n                    else\n                        return ((ILType)t).TypeReference.GetHashCode();\n                }\n                else if (isGenericParameter)\n                {\n                    return t.GetHashCode();\n                }\n                else\n                    return token.GetHashCode();\n            }\n            return 0;\n        }\n\n        bool CheckHasGenericParamter(object token)\n        {\n            if (token is TypeReference)\n            {\n                TypeReference _ref = ((TypeReference)token);\n                if (_ref.IsGenericParameter)\n                    return true;\n                if (_ref.IsGenericInstance)\n                {\n                    GenericInstanceType gi = (GenericInstanceType)_ref;\n                    foreach(var i in gi.GenericArguments)\n                    {\n                        if (CheckHasGenericParamter(i))\n                            return true;\n                    }\n                    return false;\n                }\n                else\n                    return false;\n            }\n            else\n                return false;\n        }\n\n        void PrepareJumpTable(object token, Dictionary<Mono.Cecil.Cil.Instruction, int> addr)\n        {\n            int hashCode = token.GetHashCode();\n\n            if (jumptables == null)\n                jumptables = new Dictionary<int, int[]>();\n            if (jumptables.ContainsKey(hashCode))\n                return;\n            Mono.Cecil.Cil.Instruction[] e = token as Mono.Cecil.Cil.Instruction[];\n            int[] addrs = new int[e.Length];\n            for (int i = 0; i < e.Length; i++)\n            {\n                addrs[i] = addr[e[i]];\n            }\n\n            jumptables[hashCode] = addrs;\n        }\n\n        void InitParameters()\n        {\n            parameters = new List<IType>();\n            foreach (var i in def.Parameters)\n            {\n                IType type = null;\n                bool isByRef = false;\n                bool isArray = false;\n                TypeReference pt = i.ParameterType;\n                if (i.ParameterType.IsByReference)\n                {\n                    isByRef = true;\n                    pt = pt.GetElementType();\n                }\n                if (i.ParameterType.IsArray)\n                {\n                    isArray = true;\n                    pt = pt.GetElementType();\n                }\n                if (pt.IsGenericParameter)\n                {\n                    type = FindGenericArgument(pt.Name);\n                    if (type == null && def.HasGenericParameters)\n                    {\n                        bool found = false;\n                        foreach (var j in def.GenericParameters)\n                        {\n                            if (j.Name == pt.Name)\n                            {\n                                found = true;\n                                break;\n                            }\n                        }\n                        if (found)\n                        {\n                            type = new ILGenericParameterType(pt.Name);\n                        }\n                        else\n                            throw new NotSupportedException(\"Cannot find Generic Parameter \" + pt.Name + \" in \" + def.FullName);\n                    }\n\n                    if (isByRef)\n                        type = type.MakeByRefType();\n                    if (isArray)\n                        type = type.MakeArrayType();\n                }\n                else\n                    type = appdomain.GetType(i.ParameterType, declaringType, this);\n                parameters.Add(type);\n            }\n        }\n\n        public IMethod MakeGenericMethod(IType[] genericArguments)\n        {\n            KeyValuePair<string, IType>[] genericParameters = new KeyValuePair<string, IType>[genericArguments.Length];\n            for (int i = 0; i < genericArguments.Length; i++)\n            {\n                string name = def.GenericParameters[i].Name;\n                IType val = genericArguments[i];\n                genericParameters[i] = new KeyValuePair<string, IType>(name, val);\n            }\n\n            ILMethod m = new ILMethod(def, declaringType, appdomain);\n            m.genericParameters = genericParameters;\n            m.genericArguments = genericArguments;\n            if (m.def.ReturnType.IsGenericParameter)\n            {\n                m.ReturnType = m.FindGenericArgument(m.def.ReturnType.Name);\n            }\n            return m;\n        }\n\n        public override string ToString()\n        {\n            StringBuilder sb = new StringBuilder();\n            sb.Append(declaringType.FullName);\n            sb.Append('.');\n            sb.Append(Name);\n            sb.Append('(');\n            bool isFirst = true;\n            if (parameters == null)\n                InitParameters();\n            for (int i = 0; i < parameters.Count; i++)\n            {\n                if (isFirst)\n                    isFirst = false;\n                else\n                    sb.Append(\", \");\n                sb.Append(parameters[i].Name);\n                sb.Append(' ');\n                sb.Append(def.Parameters[i].Name);\n            }\n            sb.Append(')');\n            return sb.ToString();\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/CLR/Method/IMethod.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.TypeSystem;\nnamespace ILRuntime.CLR.Method\n{\n    public interface IMethod\n    {\n        string Name { get; }\n        int ParameterCount { get; }\n\n        bool HasThis { get; }\n\n        IType DeclearingType { get; }\n\n        IType ReturnType { get; }\n        List<IType> Parameters { get; }\n\n        int GenericParameterCount { get; }\n\n        bool IsGenericInstance { get; }\n\n        bool IsConstructor { get; }\n\n        bool IsDelegateInvoke { get; }\n\n        bool IsStatic { get; }\n\n        IMethod MakeGenericMethod(IType[] genericArguments);\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/CLR/TypeSystem/CLRType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nusing Mono.Cecil;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Reflection;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.CLR.TypeSystem\n{\n    public class CLRType : IType\n    {\n        Type clrType;\n        bool isPrimitive, isValueType;\n        Dictionary<string, List<CLRMethod>> methods;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n        List<CLRMethod> constructors;\n        KeyValuePair<string, IType>[] genericArguments;\n        List<CLRType> genericInstances;\n        Dictionary<string, int> fieldMapping;\n        Dictionary<int, FieldInfo> fieldInfoCache;\n        Dictionary<int, CLRFieldGetterDelegate> fieldGetterCache;\n        Dictionary<int, CLRFieldSetterDelegate> fieldSetterCache;\n        Dictionary<int, int> fieldIdxMapping;\n        IType[] orderedFieldTypes;\n\n        CLRMemberwiseCloneDelegate memberwiseCloneDelegate;\n        CLRCreateDefaultInstanceDelegate createDefaultInstanceDelegate;\n        CLRCreateArrayInstanceDelegate createArrayInstanceDelegate;\n        Dictionary<int, int> fieldTokenMapping;\n        IType byRefType, arrayType, elementType;\n        IType[] interfaces;\n        bool isDelegate;\n        IType baseType;\n        bool isBaseTypeInitialized = false, interfaceInitialized = false, valueTypeBinderGot = false;\n        ILRuntimeWrapperType wraperType;\n        ValueTypeBinder valueTypeBinder;\n\n        int hashCode = -1;\n        static int instance_id = 0x20000000;\n\n        public Dictionary<int, FieldInfo> Fields\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return fieldInfoCache;\n            }\n        }\n\n        public Dictionary<int, int> FieldIndexMapping\n        {\n            get { return fieldIdxMapping; }\n        }\n\n        public IType[] OrderedFieldTypes\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return orderedFieldTypes;\n            }\n        }\n\n        public int TotalFieldCount\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return fieldIdxMapping.Count;\n            }\n        }\n\n        public ILRuntime.Runtime.Enviorment.AppDomain AppDomain\n        {\n            get\n            {\n                return appdomain;\n            }\n        }\n\n        public CLRType(Type clrType, Runtime.Enviorment.AppDomain appdomain)\n        {\n            this.clrType = clrType;\n            this.appdomain = appdomain;\n            isPrimitive = clrType.IsPrimitive;\n            isValueType = clrType.IsValueType;\n            isDelegate = clrType.BaseType == typeof(MulticastDelegate);\n        }\n\n        public bool IsGenericInstance\n        {\n            get\n            {\n                return genericArguments != null;\n            }\n        }\n\n        public KeyValuePair<string, IType>[] GenericArguments\n        {\n            get\n            {\n                return genericArguments;\n            }\n        }\n\n        public IType ElementType { get { return elementType; } }\n\n        public bool HasGenericParameter\n        {\n            get\n            {\n                return clrType.ContainsGenericParameters;\n            }\n        }\n\n        public Type TypeForCLR\n        {\n            get\n            {\n                return clrType;\n            }\n        }\n\n        public Type ReflectionType\n        {\n            get\n            {\n                if (wraperType == null)\n                    wraperType = new ILRuntimeWrapperType(this);\n                return wraperType;\n            }\n        }\n        public IType ByRefType\n        {\n            get\n            {\n                return byRefType;\n            }\n        }\n        public IType ArrayType\n        {\n            get\n            {\n                return arrayType;\n            }\n        }\n\n        public bool IsArray\n        {\n            get;private set;\n        }\n\n        public bool IsValueType\n        {\n            get\n            {\n                return isValueType;\n            }\n        }\n        public bool IsDelegate\n        {\n            get\n            {\n                return isDelegate;\n            }\n        }\n\n        public bool IsPrimitive\n        {\n            get\n            {\n                return isPrimitive;\n            }\n        }\n        public string FullName\n        {\n            get\n            {\n                return clrType.FullName;\n            }\n        }\n        public string Name\n        {\n            get\n            {\n                return clrType.Name;\n            }\n        }\n\n        public IType BaseType\n        {\n            get\n            {\n                if (!isBaseTypeInitialized)\n                    InitializeBaseType();\n                return baseType;\n            }\n        }\n\n        public IType[] Implements\n        {\n            get\n            {\n                if (!interfaceInitialized)\n                    InitializeInterfaces();\n                return interfaces;\n            }\n        }\n\n        public ValueTypeBinder ValueTypeBinder\n        {\n            get\n            {\n                if (clrType.IsValueType)\n                {\n                    if (!valueTypeBinderGot)\n                    {\n                        valueTypeBinderGot = true;\n                        if (appdomain.ValueTypeBinders.TryGetValue(clrType, out valueTypeBinder))\n                            valueTypeBinder.CLRType = this;\n                    }\n                    return valueTypeBinder;\n                }\n                else\n                    return null;\n            }\n        }\n\n        public object PerformMemberwiseClone(object target)\n        {\n            if (memberwiseCloneDelegate == null)\n            {\n                if (!AppDomain.MemberwiseCloneMap.TryGetValue(this.clrType, out memberwiseCloneDelegate))\n                {\n                    var memberwiseClone = clrType.GetMethod(\"MemberwiseClone\", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);\n\n                    if (memberwiseClone != null)\n                    {\n                        memberwiseCloneDelegate = (ref object t) => memberwiseClone.Invoke(t, null);\n                    }\n                    else\n                    {\n                        throw new InvalidOperationException(\"Memberwise clone method not found for \" + clrType.FullName);\n                    }\n                }\n            }\n\n            return memberwiseCloneDelegate(ref target);\n        }\n\n        void InitializeBaseType()\n        {\n            baseType = appdomain.GetType(clrType.BaseType);\n            if (baseType.TypeForCLR == typeof(Enum) || baseType.TypeForCLR == typeof(object) || baseType.TypeForCLR == typeof(ValueType) || baseType.TypeForCLR == typeof(System.Enum))\n            {//都是这样，无所谓\n                baseType = null;\n            }\n            isBaseTypeInitialized = true;\n        }\n\n        void InitializeInterfaces()\n        {\n            interfaceInitialized = true;\n            var arr = clrType.GetInterfaces();\n            if (arr.Length >0)\n            {\n                interfaces = new IType[arr.Length];\n                for (int i = 0; i < interfaces.Length; i++)\n                {\n                    interfaces[i] = appdomain.GetType(arr[i]);\n                }\n            }\n        }\n\n        public object GetFieldValue(int hash, object target)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n\n            var getter = GetFieldGetter(hash);\n            if (getter != null)\n            {\n                return getter(ref target);\n            }\n\n            var fieldinfo = GetField(hash);\n            if (fieldinfo != null)\n            {\n                return fieldinfo.GetValue(target);\n            }\n\n            return null;\n        }\n\n        public void SetStaticFieldValue(int hash, object value)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n\n            var setter = GetFieldSetter(hash);\n            object target = null;\n            if (setter != null)\n            {\n                setter(ref target, value);\n                return;\n            }\n\n            var fieldInfo = GetField(hash);\n            if (fieldInfo != null)\n            {\n                fieldInfo.SetValue(null, value);\n            }\n        }\n\n        public unsafe void SetFieldValue(int hash, ref object target, object value)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n\n            var setter = GetFieldSetter(hash);\n            if (setter != null)\n            {\n                setter(ref target, value);\n                return;\n            }\n\n            var fieldInfo = GetField(hash);\n            if (fieldInfo != null)\n            {\n                fieldInfo.SetValue(target, value);\n            }\n        }\n\n        private CLRFieldGetterDelegate GetFieldGetter(int hash)\n        {\n            var dic = fieldGetterCache;\n            CLRFieldGetterDelegate res;\n            if (dic != null && dic.TryGetValue(hash, out res))\n                return res;\n            else if (BaseType != null)\n                return ((CLRType)BaseType).GetFieldGetter(hash);\n            else\n                return null;\n        }\n\n        private CLRFieldSetterDelegate GetFieldSetter(int hash)\n        {\n            var dic = fieldSetterCache;\n            CLRFieldSetterDelegate res;\n            if (dic != null && dic.TryGetValue(hash, out res))\n                return res;\n            else if (BaseType != null)\n                return ((CLRType)BaseType).GetFieldSetter(hash);\n            else\n                return null;\n        }\n\n        public FieldInfo GetField(int hash)\n        {\n            var dic = Fields;\n            FieldInfo res;\n            if (dic.TryGetValue(hash, out res))\n                return res;\n            else if (BaseType != null)\n                return ((CLRType)BaseType).GetField(hash);\n            else\n                return null;\n        }\n\n        void InitializeMethods()\n        {\n            methods = new Dictionary<string, List<CLRMethod>>();\n            constructors = new List<CLRMethod>();\n            foreach (var i in clrType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))\n            {\n                if (i.IsPrivate)\n                    continue;\n                List<CLRMethod> lst;\n                if (!methods.TryGetValue(i.Name, out lst))\n                {\n                    lst = new List<CLRMethod>();\n                    methods[i.Name] = lst;\n                }\n                lst.Add(new CLRMethod(i, this, appdomain));\n            }\n            foreach (var i in clrType.GetConstructors())\n            {\n                constructors.Add(new CLRMethod(i, this, appdomain));\n            }\n        }\n        public List<IMethod> GetMethods()\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<IMethod> res = new List<IMethod>();\n            foreach (var i in methods)\n            {\n                foreach (var j in i.Value)\n                    res.Add(j);\n            }\n\n            return res;\n        }\n\n        public IMethod GetVirtualMethod(IMethod method)\n        {\n            var m = GetMethod(method.Name, method.Parameters, null, method.ReturnType);\n            if (m == null)\n            {\n                return method;\n            }\n            else\n                return m;\n        }\n\n        void InitializeFields()\n        {\n            fieldMapping = new Dictionary<string, int>();\n            fieldInfoCache = new Dictionary<int, FieldInfo>();\n\n            var fields = clrType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);\n            int idx = 0;\n            bool hasValueTypeBinder = ValueTypeBinder != null;\n            if (hasValueTypeBinder)\n            {\n                fieldIdxMapping = new Dictionary<int, int>();\n                orderedFieldTypes = new IType[fields.Length];\n            }\n            foreach (var i in fields)\n            {\n                int hashCode = i.GetHashCode();\n\n                if (i.IsPublic || i.IsFamily || hasValueTypeBinder)\n                {\n                    fieldMapping[i.Name] = hashCode;\n                    fieldInfoCache[hashCode] = i;\n                }\n                if (hasValueTypeBinder && !i.IsStatic)\n                {\n                    orderedFieldTypes[idx] = appdomain.GetType(i.FieldType);\n                    fieldIdxMapping[hashCode] = idx++;\n                }\n\n                CLRFieldGetterDelegate getter;\n                if (AppDomain.FieldGetterMap.TryGetValue(i, out getter))\n                {\n                    if (fieldGetterCache == null) fieldGetterCache = new Dictionary<int, CLRFieldGetterDelegate>();\n                    fieldGetterCache[hashCode] = getter;\n                }\n\n                CLRFieldSetterDelegate setter;\n                if (AppDomain.FieldSetterMap.TryGetValue(i, out setter))\n                {\n                    if (fieldSetterCache == null) fieldSetterCache = new Dictionary<int, CLRFieldSetterDelegate>();\n                    fieldSetterCache[hashCode] = setter;\n                }\n            }\n        }\n        public int GetFieldIndex(object token)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n            int idx;\n            int hashCode = token.GetHashCode();\n            if (fieldTokenMapping == null)\n                fieldTokenMapping = new Dictionary<int, int>();\n            if (fieldTokenMapping.TryGetValue(hashCode, out idx))\n                return idx;\n            FieldReference f = token as FieldReference;\n            if (fieldMapping.TryGetValue(f.Name, out idx))\n            {\n                fieldTokenMapping[hashCode] = idx;\n                return idx;\n            }\n\n            return -1;\n        }\n        public IType FindGenericArgument(string key)\n        {\n            if (genericArguments != null)\n            {\n                foreach (var i in genericArguments)\n                {\n                    if (i.Key == key)\n                        return i.Value;\n                }\n            }\n            return null;\n        }\n        public IMethod GetMethod(string name, int paramCount, bool declaredOnly = false)\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<CLRMethod> lst;\n            if (methods.TryGetValue(name, out lst))\n            {\n                foreach (var i in lst)\n                {\n                    if (i.ParameterCount == paramCount)\n                        return i;\n                }\n            }\n            return null;\n        }\n\n        public IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false)\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<CLRMethod> lst;\n            IMethod genericMethod = null;\n            if (methods.TryGetValue(name, out lst))\n            {\n                foreach (var i in lst)\n                {\n                    if (i.ParameterCount == param.Count)\n                    {\n                        bool match = true;\n                        if (genericArguments != null && i.GenericParameterCount == genericArguments.Length)\n                        {\n                            for (int j = 0; j < param.Count; j++)\n                            {\n                                var p = i.Parameters[j].TypeForCLR;\n                                var q = param[j].TypeForCLR;\n\n                                if (i.Parameters[j].HasGenericParameter)\n                                {\n                                    //TODO should match the generic parameters;\n                                    continue;\n                                }\n                                if (q != p)\n                                {\n                                    match = false;\n                                    break;\n                                }\n                            }\n                            if (match && genericMethod == null)\n                            {\n                                genericMethod = i;\n                            }\n                        }\n                        else\n                        {\n                            if (genericArguments == null)\n                                match = i.GenericArguments == null;\n                            else\n                            {\n                                if (i.GenericArguments == null)\n                                    match = false;\n                                else\n                                    match = i.GenericArguments.Length == genericArguments.Length;\n                            }\n                            for (int j = 0; j < param.Count; j++)\n                            {\n                                var typeA = param[j].TypeForCLR.IsByRef ? param[j].TypeForCLR.GetElementType() : param[j].TypeForCLR;\n                                var typeB = i.Parameters[j].TypeForCLR.IsByRef ? i.Parameters[j].TypeForCLR.GetElementType() : i.Parameters[j].TypeForCLR;\n\n                                if (typeA != typeB)\n                                {\n                                    match = false;\n                                    break;\n                                }\n                            }\n                            if (match)\n                            {\n                                match = returnType == null || i.ReturnType.TypeForCLR == returnType.TypeForCLR;\n                            }\n                            if (match)\n                            {\n\n                                if (i.IsGenericInstance)\n                                {\n                                    if (i.GenericArguments.Length == genericArguments.Length)\n                                    {\n                                        for (int j = 0; j < genericArguments.Length; j++)\n                                        {\n                                            if (i.GenericArguments[j] != genericArguments[j])\n                                            {\n                                                match = false;\n                                                break;\n                                            }\n                                        }\n                                        if (match)\n                                            return i;\n                                    }\n                                }\n                                else\n                                    return i;\n                            }\n                        }\n                    }\n                }\n            }\n            if (genericArguments != null && genericMethod != null)\n            {\n                var m = genericMethod.MakeGenericMethod(genericArguments);\n                lst.Add((CLRMethod)m);\n                return m;\n            }\n            return null;\n        }\n        public bool CanAssignTo(IType type)\n        {\n            if (this == type)\n            {\n                return true;\n            }\n            else\n                return false;\n        }\n\n        public IMethod GetConstructor(List<IType> param)\n        {\n            if (constructors == null)\n                InitializeMethods();\n            foreach (var i in constructors)\n            {\n                if (i.ParameterCount == param.Count)\n                {\n                    bool match = true;\n\n                    for (int j = 0; j < param.Count; j++)\n                    {\n                        if (param[j].TypeForCLR != i.Parameters[j].TypeForCLR)\n                        {\n                            match = false;\n                            break;\n                        }\n                    }\n                    if (match)\n                    {\n                        return i;\n                    }\n                }\n            }\n\n            return null;\n        }\n\n        public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)\n        {\n            if (genericInstances == null)\n                genericInstances = new List<CLRType>();\n            foreach (var i in genericInstances)\n            {\n                bool match = true;\n                for (int j = 0; j < genericArguments.Length; j++)\n                {\n                    if (i.genericArguments[j].Value != genericArguments[j].Value)\n                    {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match)\n                    return i;\n            }\n            Type[] args = new Type[genericArguments.Length];\n            for (int i = 0; i < genericArguments.Length; i++)\n            {\n                args[i] = genericArguments[i].Value.TypeForCLR;\n            }\n            Type newType = clrType.MakeGenericType(args);\n            var res = new CLRType(newType, appdomain);\n            res.genericArguments = genericArguments;\n\n            genericInstances.Add(res);\n            return res;\n        }\n\n        public object CreateDefaultInstance()\n        {\n            if (createDefaultInstanceDelegate == null)\n            {\n                if (!AppDomain.CreateDefaultInstanceMap.TryGetValue(clrType, out createDefaultInstanceDelegate))\n                {\n                    createDefaultInstanceDelegate = () => Activator.CreateInstance(TypeForCLR);\n                }\n            }\n\n            return createDefaultInstanceDelegate();\n        }\n\n        public object CreateArrayInstance(int size)\n        {\n            if (createArrayInstanceDelegate == null)\n            {\n                if (!AppDomain.CreateArrayInstanceMap.TryGetValue(clrType, out createArrayInstanceDelegate))\n                {\n                    createArrayInstanceDelegate = s => Array.CreateInstance(TypeForCLR, s);\n                }\n            }\n\n            return createArrayInstanceDelegate(size);\n        }\n\n        public IType MakeByRefType()\n        {\n            if (byRefType == null)\n            {\n                Type t = clrType.MakeByRefType();\n                byRefType = new CLRType(t, appdomain);\n            }\n            return byRefType;\n        }\n        public IType MakeArrayType()\n        {\n            if (arrayType == null)\n            {\n                Type t = clrType.MakeArrayType();\n                arrayType = new CLRType(t, appdomain);\n                ((CLRType)arrayType).elementType = this;\n                ((CLRType)arrayType).IsArray = true;\n            }\n            return arrayType;\n        }\n\n        public IType ResolveGenericType(IType contextType)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n\n        public override string ToString()\n        {\n            return clrType.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/CLR/TypeSystem/ILGenericParameterType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.CLR.TypeSystem\n{\n    class ILGenericParameterType : IType\n    {\n        string name;\n        ILGenericParameterType arrayType;\n        public ILGenericParameterType(string name)\n        {\n            this.name = name;\n        }\n        public bool IsGenericInstance\n        {\n            get { return false; }\n        }\n\n        public KeyValuePair<string, IType>[] GenericArguments\n        {\n            get { return null; }\n        }\n        public bool HasGenericParameter\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        public Type TypeForCLR\n        {\n            get { return typeof(ILGenericParameterType); }\n        }\n\n        public string FullName\n        {\n            get { return name; }\n        }\n\n        public Runtime.Enviorment.AppDomain AppDomain\n        {\n            get { return null; }\n        }\n\n        public Method.IMethod GetMethod(string name, int paramCount, bool declaredOnly = false)\n        {\n            return null;\n        }\n\n        public Method.IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false)\n        {\n            return null;\n        }\n\n        public List<Method.IMethod> GetMethods()\n        {\n            return null;\n        }\n\n        public Method.IMethod GetConstructor(List<IType> param)\n        {\n            return null;\n        }\n\n        public bool CanAssignTo(IType type)\n        {\n            return false;\n        }\n\n        public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)\n        {\n            return null;\n        }\n\n        public IType ResolveGenericType(IType contextType)\n        {\n            throw new NotImplementedException();\n        }\n\n\n        public int GetFieldIndex(object token)\n        {\n            return -1;\n        }\n\n\n        public IType FindGenericArgument(string key)\n        {\n            return null;\n        }\n\n\n        public IType ByRefType\n        {\n            get { throw new NotImplementedException(); }\n        }\n\n        public IType MakeByRefType()\n        {\n            return this;\n        }\n\n\n        public IType ArrayType\n        {\n            get { return arrayType; }\n        }\n\n        public IType MakeArrayType()\n        {\n            if (arrayType == null)\n                arrayType = new ILGenericParameterType(name + \"[]\");\n            return arrayType;\n        }\n\n\n        public bool IsValueType\n        {\n            get { throw new NotImplementedException(); }\n        }\n\n        public bool IsPrimitive\n        {\n            get { return false; }\n        }\n\n        public string Name\n        {\n            get\n            {\n                return name;\n            }\n        }\n\n        public bool IsDelegate\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        public Type ReflectionType\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public IType BaseType\n        {\n            get\n            {\n                return null;\n            }\n        }\n\n        public Method.IMethod GetVirtualMethod(Method.IMethod method)\n        {\n            return method;\n        }\n\n        public bool IsArray\n        {\n            get { return false; }\n        }\n\n        public IType[] Implements\n        {\n            get\n            {\n                return null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/CLR/TypeSystem/ILType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing Mono.Cecil;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Reflection;\n\nnamespace ILRuntime.CLR.TypeSystem\n{\n    public class ILType : IType\n    {\n        Dictionary<string, List<ILMethod>> methods;\n        TypeReference typeRef;\n        TypeDefinition definition;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n        ILMethod staticConstructor;\n        List<ILMethod> constructors;\n        IType[] fieldTypes;\n        FieldDefinition[] fieldDefinitions;\n        IType[] staticFieldTypes;\n        FieldDefinition[] staticFieldDefinitions;\n        Dictionary<string, int> fieldMapping;\n        Dictionary<string, int> staticFieldMapping;\n        ILTypeStaticInstance staticInstance;\n        Dictionary<int, int> fieldTokenMapping = new Dictionary<int, int>();\n        int fieldStartIdx = -1;\n        int totalFieldCnt = -1;\n        KeyValuePair<string, IType>[] genericArguments;\n        IType baseType, byRefType, arrayType, enumType, elementType;\n        Type arrayCLRType, byRefCLRType;\n        IType[] interfaces;\n        bool baseTypeInitialized = false;\n        bool interfaceInitialized = false;\n        List<ILType> genericInstances;\n        bool isDelegate;\n        ILRuntimeType reflectionType;\n        IType firstCLRBaseType, firstCLRInterface;\n        int hashCode = -1;\n        static int instance_id = 0x10000000;\n        public TypeDefinition TypeDefinition { get { return definition; } }\n\n        public TypeReference TypeReference\n        {\n            get { return typeRef; }\n            set\n            {\n                typeRef = value;\n                RetriveDefinitino(value);\n            }\n        }\n\n        public IType BaseType\n        {\n            get\n            {\n                if (!baseTypeInitialized)\n                    InitializeBaseType();\n                return baseType;\n            }\n        }\n\n        public IType[] Implements\n        {\n            get\n            {\n                if (!interfaceInitialized)\n                    InitializeInterfaces();\n                return interfaces;\n            }\n        }\n\n        public ILTypeStaticInstance StaticInstance\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                if (methods == null)\n                    InitializeMethods();\n                return staticInstance;\n            }\n        }\n\n        public IType[] FieldTypes\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return fieldTypes;\n            }\n        }\n\n        public IType[] StaticFieldTypes\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return staticFieldTypes;\n            }\n        }\n\n        public FieldDefinition[] StaticFieldDefinitions\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return staticFieldDefinitions;\n            }\n        }\n\n        public Dictionary<string, int> FieldMapping\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields(); return fieldMapping;\n            }\n        }\n\n        public IType FirstCLRBaseType\n        {\n            get\n            {\n                if (!baseTypeInitialized)\n                    InitializeBaseType();\n                return firstCLRBaseType;\n            }\n        }\n\n        public IType FirstCLRInterface\n        {\n            get\n            {\n                if (!interfaceInitialized)\n                    InitializeInterfaces();\n                return firstCLRInterface;\n            }\n        }\n        public bool HasGenericParameter\n        {\n            get\n            {\n                return definition.HasGenericParameters && genericArguments == null;\n            }\n        }\n\n        public Dictionary<string, int> StaticFieldMapping { get { return staticFieldMapping; } }\n        public ILRuntime.Runtime.Enviorment.AppDomain AppDomain\n        {\n            get\n            {\n                return appdomain;\n            }\n        }\n\n        internal int FieldStartIndex\n        {\n            get\n            {\n                if (fieldStartIdx < 0)\n                {\n                    if (BaseType != null)\n                    {\n                        if (BaseType is ILType)\n                        {\n                            fieldStartIdx = ((ILType)BaseType).TotalFieldCount;\n                        }\n                        else\n                            fieldStartIdx = 0;\n                    }\n                    else\n                        fieldStartIdx = 0;\n                }\n                return fieldStartIdx;\n            }\n        }\n\n        public int TotalFieldCount\n        {\n            get\n            {\n                if (totalFieldCnt < 0)\n                {\n                    if (fieldMapping == null)\n                        InitializeFields();\n                    if (BaseType != null)\n                    {\n                        if (BaseType is ILType)\n                        {\n                            totalFieldCnt = ((ILType)BaseType).TotalFieldCount + fieldTypes.Length;\n                        }\n                        else\n                            totalFieldCnt = fieldTypes.Length;\n                    }\n                    else\n                        totalFieldCnt = fieldTypes.Length;\n                }\n                return totalFieldCnt;\n            }\n        }\n\n        /// <summary>\n        /// 初始化IL类型\n        /// </summary>\n        /// <param name=\"def\">MONO返回的类型定义</param>\n        /// <param name=\"domain\">ILdomain</param>\n        public ILType(TypeReference def, Runtime.Enviorment.AppDomain domain)\n        {\n            this.typeRef = def;\n            RetriveDefinitino(def);\n            appdomain = domain;\n        }\n\n        /// <summary>\n        /// 加载类型\n        /// </summary>\n        /// <param name=\"def\"></param>\n        void RetriveDefinitino(TypeReference def)\n        {\n            if (!def.IsGenericParameter)\n            {\n                if (def is TypeSpecification)\n                    RetriveDefinitino(def.GetElementType());\n                else\n                    definition = def as TypeDefinition;\n            }\n        }\n\n        public bool IsGenericInstance\n        {\n            get\n            {\n                return genericArguments != null;\n            }\n        }\n        public KeyValuePair<string, IType>[] GenericArguments\n        {\n            get\n            {\n                return genericArguments;\n            }\n        }\n\n        public IType ElementType { get { return elementType; } }\n\n        public bool IsArray\n        {\n            get; private set;\n        }\n\n        private bool? isValueType;\n\n        public bool IsValueType\n        {\n            get\n            {\n                if (isValueType == null)\n                    isValueType = definition.IsValueType;\n\n                return isValueType.Value;\n            }\n        }\n\n        public bool IsDelegate\n        {\n            get\n            {\n                if (!baseTypeInitialized)\n                    InitializeBaseType();\n                return isDelegate;\n            }\n        }\n\n        public bool IsPrimitive\n        {\n            get { return false; }\n        }\n\n        public Type TypeForCLR\n        {\n            get\n            {\n                if (!baseTypeInitialized)\n                    InitializeBaseType();\n                if (typeRef is ArrayType)\n                {\n                    return arrayCLRType;\n                }\n                else if (typeRef is ByReferenceType)\n                {\n                    return byRefCLRType;\n                }\n                else if (definition.IsEnum)\n                {\n                    if (enumType == null)\n                        InitializeFields();\n                    return enumType.TypeForCLR;\n                }\n                else if (FirstCLRBaseType != null && FirstCLRBaseType is CrossBindingAdaptor)\n                {\n                    return ((CrossBindingAdaptor)FirstCLRBaseType).RuntimeType.TypeForCLR;\n                }\n                else if (FirstCLRInterface != null && FirstCLRInterface is CrossBindingAdaptor)\n                {\n                    return ((CrossBindingAdaptor)FirstCLRInterface).RuntimeType.TypeForCLR;\n                }\n                else\n                    return typeof(ILTypeInstance);\n            }\n        }\n\n        public Type ReflectionType\n        {\n            get\n            {\n                if (reflectionType == null)\n                    reflectionType = new ILRuntimeType(this);\n                return reflectionType;\n            }\n        }\n\n        public IType ByRefType\n        {\n            get\n            {\n                return byRefType;\n            }\n        }\n        public IType ArrayType\n        {\n            get\n            {\n                return arrayType;\n            }\n        }\n\n        public bool IsEnum\n        {\n            get\n            {\n                return definition.IsEnum;\n            }\n        }\n        public string FullName\n        {\n            get\n            {\n                return typeRef.FullName;\n            }\n        }\n        public string Name\n        {\n            get\n            {\n                return typeRef.Name;\n            }\n        }\n        public List<IMethod> GetMethods()\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<IMethod> res = new List<IMethod>();\n            foreach (var i in methods)\n            {\n                foreach (var j in i.Value)\n                    res.Add(j);\n            }\n\n            return res;\n        }\n        void InitializeInterfaces()\n        {\n            interfaceInitialized = true;\n            if (definition.HasInterfaces)\n            {\n                interfaces = new IType[definition.Interfaces.Count];\n                for (int i = 0; i < interfaces.Length; i++)\n                {\n                    interfaces[i] = appdomain.GetType(definition.Interfaces[i], this, null);\n                    //only one clrInterface is valid\n                    if (interfaces[i] is CLRType && firstCLRInterface == null)\n                    {\n                        CrossBindingAdaptor adaptor;\n                        if (appdomain.CrossBindingAdaptors.TryGetValue(interfaces[i].TypeForCLR, out adaptor))\n                        {\n                            interfaces[i] = adaptor;\n                            firstCLRInterface = adaptor;\n                        }\n                        else\n                            throw new TypeLoadException(\"Cannot find Adaptor for:\" + interfaces[i].TypeForCLR.ToString());\n                    }\n                }\n            }\n        }\n        void InitializeBaseType()\n        {\n            if (definition.BaseType != null)\n            {\n                bool specialProcess = false;\n                List<int> spIdx = null;\n                if (definition.BaseType.IsGenericInstance)\n                {\n                    GenericInstanceType git = definition.BaseType as GenericInstanceType;\n                    var elementType = appdomain.GetType(definition.BaseType.GetElementType(), this, null);\n                    if (elementType is CLRType)\n                    {\n                        for (int i = 0; i < git.GenericArguments.Count; i++)\n                        {\n                            var ga = git.GenericArguments[i];\n                            if (ga == typeRef)\n                            {\n                                specialProcess = true;\n                                if (spIdx == null)\n                                    spIdx = new List<int>();\n                                spIdx.Add(i);\n                            }\n                        }\n                    }\n                }\n                if (specialProcess)\n                {\n                    //如果泛型参数是自身，则必须要特殊处理，否则会StackOverflow\n                    var elementType = appdomain.GetType(definition.BaseType.GetElementType(), this, null);\n                    foreach (var i in appdomain.CrossBindingAdaptors)\n                    {\n                        if (i.Key.IsGenericType && !i.Key.IsGenericTypeDefinition)\n                        {\n                            var gd = i.Key.GetGenericTypeDefinition();\n                            if (gd == elementType.TypeForCLR)\n                            {\n                                var ga = i.Key.GetGenericArguments();\n                                bool match = true;\n                                foreach (var j in spIdx)\n                                {\n                                    if (ga[j] != i.Value.AdaptorType)\n                                    {\n                                        match = false;\n                                        break;\n                                    }\n                                }\n                                if (match)\n                                {\n                                    baseType = i.Value;\n                                    break;\n                                }\n                            }\n                        }\n                    }\n                    if (baseType == null)\n                    {\n                        throw new TypeLoadException(\"Cannot find Adaptor for:\" + definition.BaseType.FullName);\n                    }\n                }\n                else\n                {\n                    baseType = appdomain.GetType(definition.BaseType, this, null);\n                    if (baseType is CLRType)\n                    {\n                        if (baseType.TypeForCLR == typeof(Enum) || baseType.TypeForCLR == typeof(object) || baseType.TypeForCLR == typeof(ValueType) || baseType.TypeForCLR == typeof(System.Enum))\n                        {//都是这样，无所谓\n                            baseType = null;\n                        }\n                        else if (baseType.TypeForCLR == typeof(MulticastDelegate))\n                        {\n                            baseType = null;\n                            isDelegate = true;\n                        }\n                        else\n                        {\n                            CrossBindingAdaptor adaptor;\n                            if (appdomain.CrossBindingAdaptors.TryGetValue(baseType.TypeForCLR, out adaptor))\n                            {\n                                baseType = adaptor;\n                            }\n                            else\n                                throw new TypeLoadException(\"Cannot find Adaptor for:\" + baseType.TypeForCLR.ToString());\n                            //继承了其他系统类型\n                            //env.logger.Log_Error(\"ScriptType:\" + Name + \" Based On a SystemType:\" + BaseType.Name);\n                            //HasSysBase = true;\n                            //throw new Exception(\"不得继承系统类型，脚本类型系统和脚本类型系统是隔离的\");\n                        }\n                    }\n                }\n            }\n            var curBase = baseType;\n            while (curBase is ILType)\n            {\n                curBase = curBase.BaseType;\n            }\n            firstCLRBaseType = curBase;\n            baseTypeInitialized = true;\n        }\n\n        public IMethod GetMethod(string name)\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<ILMethod> lst;\n            if (methods.TryGetValue(name, out lst))\n            {\n                return lst[0];\n            }\n            return null;\n        }\n\n        public IMethod GetMethod(string name, int paramCount, bool declaredOnly = false)\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<ILMethod> lst;\n            if (methods.TryGetValue(name, out lst))\n            {\n                foreach (var i in lst)\n                {\n                    if (i.ParameterCount == paramCount)\n                        return i;\n                }\n            }\n            if (declaredOnly)\n                return null;\n            else\n            {\n                //skip clr base type, this doesn't make any sense\n                if (BaseType != null && !(BaseType is CrossBindingAdaptor))\n                    return BaseType.GetMethod(name, paramCount, false);\n                else\n                    return null;\n            }\n        }\n\n        void InitializeMethods()\n        {\n            methods = new Dictionary<string, List<ILMethod>>();\n            constructors = new List<ILMethod>();\n            foreach (var i in definition.Methods)\n            {\n                if (i.IsConstructor)\n                {\n                    if (i.IsStatic)\n                        staticConstructor = new ILMethod(i, this, appdomain);\n                    else\n                        constructors.Add(new ILMethod(i, this, appdomain));\n                }\n                else\n                {\n                    List<ILMethod> lst;\n                    if (!methods.TryGetValue(i.Name, out lst))\n                    {\n                        lst = new List<ILMethod>();\n                        methods[i.Name] = lst;\n                    }\n                    var m = new ILMethod(i, this, appdomain);\n                    lst.Add(new ILMethod(i, this, appdomain));\n                }\n            }\n\n            if (staticConstructor != null && (!TypeReference.HasGenericParameters || IsGenericInstance))\n            {\n                appdomain.Invoke(staticConstructor, null, null);\n            }\n        }\n\n        public IMethod GetVirtualMethod(IMethod method)\n        {\n            IType[] genericArguments = null;\n            if (method.IsGenericInstance)\n            {\n                if (method is ILMethod)\n                {\n                    genericArguments = ((ILMethod)method).GenericArugmentsArray;\n                }\n                else\n                {\n                    genericArguments = ((CLRMethod)method).GenericArguments;\n                }\n            }\n\n            var m = GetMethod(method.Name, method.Parameters, genericArguments, method.ReturnType, true);\n            if (m == null)\n            {\n                if (BaseType != null)\n                {\n                    return BaseType.GetVirtualMethod(method);\n                }\n                else\n                    return null;//BaseType == null means base type is Object or Enum\n            }\n            else if (m.IsGenericInstance == method.IsGenericInstance)\n                return m;\n            else\n                return method;\n        }\n\n        public IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false)\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<ILMethod> lst;\n            IMethod genericMethod = null;\n            if (methods.TryGetValue(name, out lst))\n            {\n                for (var idx = 0; idx < lst.Count; idx++)\n                {\n                    var i = lst[idx];\n                    int pCnt = param != null ? param.Count : 0;\n                    if (i.ParameterCount == pCnt)\n                    {\n                        bool match = true;\n                        if (genericArguments != null && i.GenericParameterCount == genericArguments.Length)\n                        {\n                            genericMethod = CheckGenericParams(i, param, ref match);\n                        }\n                        else\n                        {\n                            match = CheckGenericArguments(i, genericArguments);\n                            if (!match)\n                                continue;\n                            for (int j = 0; j < pCnt; j++)\n                            {\n                                if (param[j] != i.Parameters[j])\n                                {\n                                    match = false;\n                                    break;\n                                }\n                            }\n                            if (match)\n                            {\n                                match = returnType == null || i.ReturnType == returnType;\n                            }\n                            if (match)\n                                return i;\n                        }\n                    }\n                }\n            }\n            if (genericArguments != null && genericMethod != null)\n            {\n                var m = genericMethod.MakeGenericMethod(genericArguments);\n                lst.Add((ILMethod)m);\n                return m;\n            }\n            if (declaredOnly)\n                return null;\n            else\n            {\n                if (BaseType != null)\n                    return BaseType.GetMethod(name, param, genericArguments, returnType, false);\n                else\n                    return null;\n            }\n        }\n\n        bool CheckGenericArguments(ILMethod i, IType[] genericArguments)\n        {\n            if (genericArguments == null)\n            {\n                return i.GenericArguments == null;\n            }\n            else\n            {\n                if (i.GenericArguments == null)\n                    return false;\n                else if (i.GenericArguments.Length != genericArguments.Length)\n                    return false;\n                if (i.GenericArguments.Length == genericArguments.Length)\n                {\n                    for (int j = 0; j < genericArguments.Length; j++)\n                    {\n                        if (i.GenericArguments[j].Value != genericArguments[j])\n                            return false;\n                    }\n                    return true;\n                }\n                else\n                    return false;\n            }\n        }\n\n        ILMethod CheckGenericParams(ILMethod i, List<IType> param, ref bool match)\n        {\n            ILMethod genericMethod = null;\n            if (param != null)\n            {\n                for (int j = 0; j < param.Count; j++)\n                {\n                    var p = i.Parameters[j];\n                    if (p.HasGenericParameter)\n                    {\n                        //TODO should match the generic parameters;\n                        continue;\n                    }\n\n                    if (param[j] != p)\n                    {\n                        match = false;\n                        break;\n                    }\n                }\n            }\n            if (match)\n            {\n                genericMethod = i;\n            }\n            return genericMethod;\n        }\n\n        public List<ILMethod> GetConstructors()\n        {\n            if (constructors == null)\n                InitializeMethods();\n            return constructors;\n        }\n\n        public IMethod GetStaticConstroctor()\n        {\n            if (constructors == null)\n                InitializeMethods();\n            return staticConstructor;\n        }\n\n        public IMethod GetConstructor(int paramCnt)\n        {\n            if (constructors == null)\n                InitializeMethods();\n            foreach (var i in constructors)\n            {\n                if (i.ParameterCount == paramCnt)\n                {\n                    return i;\n                }\n            }\n            return null;\n        }\n\n        public IMethod GetConstructor(List<IType> param)\n        {\n            if (constructors == null)\n                InitializeMethods();\n            foreach (var i in constructors)\n            {\n                if (i.ParameterCount == param.Count)\n                {\n                    bool match = true;\n\n                    for (int j = 0; j < param.Count; j++)\n                    {\n                        if (param[j] != i.Parameters[j])\n                        {\n                            match = false;\n                            break;\n                        }\n                    }\n\n                    if (match)\n                        return i;\n                }\n            }\n            return null;\n        }\n\n        public int GetFieldIndex(object token)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n            int idx;\n            int hashCode = token.GetHashCode();\n            if (fieldTokenMapping.TryGetValue(hashCode, out idx))\n                return idx;\n            FieldReference f = token as FieldReference;\n            if (staticFieldMapping != null && staticFieldMapping.TryGetValue(f.Name, out idx))\n            {\n                fieldTokenMapping[hashCode] = idx;\n                return idx;\n            }\n            if (fieldMapping.TryGetValue(f.Name, out idx))\n            {\n                fieldTokenMapping[hashCode] = idx;\n                return idx;\n            }\n\n            return -1;\n        }\n\n        public IType GetField(string name, out int fieldIdx)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n            if (fieldMapping.TryGetValue(name, out fieldIdx))\n            {\n                return fieldTypes[fieldIdx - FieldStartIndex];\n            }\n            else if (BaseType != null && BaseType is ILType)\n            {\n                return ((ILType)BaseType).GetField(name, out fieldIdx);\n            }\n            else\n                return null;\n        }\n\n        public IType GetField(int fieldIdx, out FieldDefinition fd)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n            if (fieldIdx < FieldStartIndex)\n                return ((ILType)BaseType).GetField(fieldIdx, out fd);\n            else\n            {\n                fd = fieldDefinitions[fieldIdx - FieldStartIndex];\n                return fieldTypes[fieldIdx - FieldStartIndex];\n            }\n        }\n\n        void InitializeFields()\n        {\n            fieldMapping = new Dictionary<string, int>();\n            fieldTypes = new IType[definition.Fields.Count];\n            fieldDefinitions = new FieldDefinition[definition.Fields.Count];\n            var fields = definition.Fields;\n            int idx = FieldStartIndex;\n            int idxStatic = 0;\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var field = fields[i];\n                if (field.IsStatic)\n                {\n                    //It makes no sence to initialize\n                    if (!TypeReference.HasGenericParameters || IsGenericInstance)\n                    {\n                        if (staticFieldTypes == null)\n                        {\n                            staticFieldTypes = new IType[definition.Fields.Count];\n                            staticFieldDefinitions = new FieldDefinition[definition.Fields.Count];\n                            staticFieldMapping = new Dictionary<string, int>();\n                        }\n                        staticFieldMapping[field.Name] = idxStatic;\n                        staticFieldDefinitions[idxStatic] = field;\n                        if (field.FieldType.IsGenericParameter)\n                        {\n                            staticFieldTypes[idxStatic] = FindGenericArgument(field.FieldType.Name);\n                        }\n                        else\n                            staticFieldTypes[idxStatic] = appdomain.GetType(field.FieldType, this, null);\n                        idxStatic++;\n                    }\n                }\n                else\n                {\n                    fieldMapping[field.Name] = idx;\n                    fieldDefinitions[idx - FieldStartIndex] = field;\n                    if (field.FieldType.IsGenericParameter)\n                    {\n                        fieldTypes[idx - FieldStartIndex] = FindGenericArgument(field.FieldType.Name);\n                    }\n                    else\n                        fieldTypes[idx - FieldStartIndex] = appdomain.GetType(field.FieldType, this, null);\n                    if (IsEnum)\n                    {\n                        enumType = fieldTypes[idx - FieldStartIndex];\n                    }\n                    idx++;\n                }\n            }\n            Array.Resize(ref fieldTypes, idx - FieldStartIndex);\n            Array.Resize(ref fieldDefinitions, idx - FieldStartIndex);\n\n            if (staticFieldTypes != null)\n            {\n                Array.Resize(ref staticFieldTypes, idxStatic);\n                Array.Resize(ref staticFieldDefinitions, idxStatic);\n                staticInstance = new ILTypeStaticInstance(this);\n            }\n        }\n\n        public IType FindGenericArgument(string key)\n        {\n            if (genericArguments != null)\n            {\n                foreach (var i in genericArguments)\n                {\n                    if (i.Key == key)\n                        return i.Value;\n                }\n            }\n            return null;\n        }\n\n        public bool CanAssignTo(IType type)\n        {\n            bool res = false;\n            if (this == type)\n            {\n                return true;\n            }\n\n            if (BaseType != null)\n            {\n                res = BaseType.CanAssignTo(type);\n\n                if (res) return true;\n            }\n\n            if (Implements != null)\n            {\n                for (int i = 0; i < interfaces.Length; i++)\n                {\n                    var im = interfaces[i];\n                    res = im.CanAssignTo(type);\n                    if (res)\n                        return true;\n                }\n            }\n            return res;\n        }\n\n        public ILTypeInstance Instantiate(bool callDefaultConstructor = true)\n        {\n            var res = new ILTypeInstance(this);\n            if (callDefaultConstructor)\n            {\n                var m = GetConstructor(CLR.Utils.Extensions.EmptyParamList);\n                if (m != null)\n                {\n                    appdomain.Invoke(m, res, null);\n                }\n            }\n            return res;\n        }\n        public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)\n        {\n            if (genericInstances == null)\n                genericInstances = new List<ILType>();\n            foreach (var i in genericInstances)\n            {\n                bool match = true;\n                for (int j = 0; j < genericArguments.Length; j++)\n                {\n                    if (i.genericArguments[j].Value != genericArguments[j].Value)\n                    {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match)\n                    return i;\n            }\n            var res = new ILType(definition, appdomain);\n            res.genericArguments = genericArguments;\n\n            genericInstances.Add(res);\n            return res;\n        }\n\n        public IType MakeByRefType()\n        {\n            if (byRefType == null)\n            {\n                var def = new ByReferenceType(typeRef);\n                byRefType = new ILType(def, appdomain);\n                ((ILType)byRefType).elementType = this;\n                ((ILType)byRefType).byRefCLRType = this.TypeForCLR.MakeByRefType();\n            }\n            return byRefType;\n        }\n\n        public IType MakeArrayType()\n        {\n            if (arrayType == null)\n            {\n                var def = new ArrayType(typeRef);\n                arrayType = new ILType(def, appdomain);\n                ((ILType)arrayType).IsArray = true;\n                ((ILType)arrayType).elementType = this;\n                ((ILType)arrayType).arrayCLRType = this.TypeForCLR.MakeArrayType();\n            }\n            return arrayType;\n        }\n\n        public IType ResolveGenericType(IType contextType)\n        {\n            var ga = contextType.GenericArguments;\n            IType[] kv = new IType[definition.GenericParameters.Count];\n            for (int i = 0; i < kv.Length; i++)\n            {\n                var gp = definition.GenericParameters[i];\n                string name = gp.Name;\n                foreach (var j in ga)\n                {\n                    if (j.Key == name)\n                    {\n                        kv[i] = j.Value;\n                        break;\n                    }\n                }\n            }\n\n            foreach (var i in genericInstances)\n            {\n                bool match = true;\n                for (int j = 0; j < kv.Length; j++)\n                {\n                    if (i.genericArguments[j].Value != kv[j])\n                    {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match)\n                    return i;\n            }\n\n            return null;\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n\n        public override string ToString()\n        {\n            return FullName;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/CLR/TypeSystem/IType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.Method;\n\nnamespace ILRuntime.CLR.TypeSystem\n{\n    public interface IType\n    {\n        bool IsGenericInstance { get; }\n        KeyValuePair<string, IType>[] GenericArguments { get; }\n        Type TypeForCLR { get; }\n        Type ReflectionType { get; }\n\n        IType BaseType { get; }\n\n        IType[] Implements { get; }\n\n        IType ByRefType { get; }\n\n        IType ArrayType { get; }\n\n        string FullName { get; }\n\n        string Name { get; }\n\n        bool IsArray { get; }\n\n        bool IsValueType { get; }\n\n        bool IsDelegate { get; }\n\n        bool IsPrimitive { get; }\n\n        bool HasGenericParameter { get; }\n\n        ILRuntime.Runtime.Enviorment.AppDomain AppDomain { get; }\n\n        /// <summary>\n        /// Get a specified Method in this type\n        /// </summary>\n        /// <param name=\"name\">Name of the Type</param>\n        /// <param name=\"paramCount\">Parameter count</param>\n        /// <param name=\"declaredOnly\">True to search the methods decleared in this type only, false to search base types.</param>\n        /// <returns></returns>\n        IMethod GetMethod(string name, int paramCount, bool declaredOnly = false);\n        /// <summary>\n        ///  Get a specified Method in this type\n        /// </summary>\n        /// <param name=\"name\">Name of the Type</param>\n        /// <param name=\"param\">List of parameter's types</param>\n        /// <param name=\"genericArguments\">List of Generic Arguments</param>\n        /// <param name=\"returnType\">Return Type</param>\n        /// <param name=\"declaredOnly\">True to search the methods decleared in this type only, false to search base types.</param>\n        /// <returns></returns>\n        IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false);\n        IMethod GetVirtualMethod(IMethod method);\n\n        List<IMethod> GetMethods();\n\n        int GetFieldIndex(object token);\n\n        IMethod GetConstructor(List<IType> param);\n\n        bool CanAssignTo(IType type);\n\n        IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments);\n\n        IType MakeByRefType();\n\n        IType MakeArrayType();\n        IType FindGenericArgument(string key);\n\n        IType ResolveGenericType(IType contextType);\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/CLR/Utils/Extensions.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Other;\nusing Mono.Cecil;\nusing ILRuntime.Runtime.Intepreter;\nnamespace ILRuntime.CLR.Utils\n{\n    public delegate TResult Func<T1, T2, T3, T4, T5, TResult>(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5);\n\n    public static class Extensions\n    {\n        public static List<IType> EmptyParamList = new List<IType>();\n        public static List<IType> GetParamList(this MethodReference def, ILRuntime.Runtime.Enviorment.AppDomain appdomain, IType contextType, IMethod contextMethod, IType[] genericArguments)\n        {\n            if (def.HasParameters)\n            {\n                List<IType> param = new List<IType>();\n                var dt = appdomain.GetType(def.DeclaringType, contextType, contextMethod);\n                foreach (var i in def.Parameters)\n                {\n                    IType t = null;\n                    t = appdomain.GetType(i.ParameterType, dt, null);\n                    if (t == null && def.IsGenericInstance)\n                    {\n                        GenericInstanceMethod gim = (GenericInstanceMethod)def;\n                        string name = i.ParameterType.IsByReference ? i.ParameterType.GetElementType().FullName : i.ParameterType.FullName;\n                        \n                        for (int j = 0; j < gim.GenericArguments.Count; j++)\n                        {\n                            var gp = gim.ElementMethod.GenericParameters[j];\n                            var ga = gim.GenericArguments[j];\n                            if (name == gp.Name)\n                            {\n                                t = appdomain.GetType(ga, contextType, contextMethod);\n                                if (t == null && genericArguments != null)\n                                    t = genericArguments[j];\n                                break;\n                            }\n                            else if (name.Contains(gp.Name))\n                            {\n                                if (name == gp.Name)\n                                {\n                                    name = ga.FullName;\n                                }\n                                else if (name == gp.Name + \"[]\")\n                                {\n                                    name = ga.FullName + \"[]\";\n                                }\n                                else\n                                {\n                                    /*name = name.Replace(\"<\" + gp.Name + \">\", \"<\" + ga.FullName + \">\");\n                                    name = name.Replace(\"<\" + gp.Name + \"[\", \"<\" + ga.FullName + \"[\");\n                                    name = name.Replace(\"<\" + gp.Name + \",\", \"<\" + ga.FullName + \",\");\n                                    name = name.Replace(\",\" + gp.Name + \">\", \",\" + ga.FullName + \">\");\n                                    name = name.Replace(\",\" + gp.Name + \"[\", \",\" + ga.FullName + \"[\");\n                                    name = name.Replace(\",\" + gp.Name + \",\", \",\" + ga.FullName + \",\");\n                                    name = name.Replace(\",\" + gp.Name + \"[\", \",\" + ga.FullName + \"[\");*/\n                                    name = ReplaceGenericArgument(name, gp.Name, ga.FullName);\n                                }\n                            }\n                        }\n                        if (t == null)\n                            t = appdomain.GetType(name);\n                    }\n\n                    param.Add(t);\n                }\n                return param;\n            }\n            else\n                return EmptyParamList;\n        }\n\n        static string ReplaceGenericArgument(string typename, string argumentName, string argumentType)\n        {\n            string baseType;\n            StringBuilder sb = new StringBuilder();\n            List<string> ga;\n            bool isArray;\n            Runtime.Enviorment.AppDomain.ParseGenericType(typename, out baseType, out ga, out isArray);\n            if (baseType == argumentName)\n                sb.Append(argumentType);\n            else\n                sb.Append(baseType);\n            if (ga != null && ga.Count > 0)\n            {\n                sb.Append(\"<\");\n                bool isFirst = true;\n                foreach(var i in ga)\n                {\n                    if (isFirst)\n                        isFirst = false;\n                    else\n                        sb.Append(\",\");\n\n                    sb.Append(ReplaceGenericArgument(i, argumentName, argumentType));\n                }\n                sb.Append(\">\");\n            }\n            if (isArray)\n                sb.Append(\"[]\");\n            return sb.ToString();\n        }\n\n        [Flags]\n        public enum TypeFlags\n        {\n            Default = 0,\n            IsPrimitive = 0x1,\n            IsByRef = 0x2,\n            IsEnum = 0x4,\n            IsDelegate = 0x8,\n            IsValueType = 0x10,\n        }\n\n        private static readonly Dictionary<Type, TypeFlags> typeFlags = new Dictionary<Type, TypeFlags>(new ByReferenceKeyComparer<Type>());\n\n        public static bool FastIsEnum(this Type pt)\n        {\n            return (pt.GetTypeFlags() & TypeFlags.IsEnum) != 0;\n        }\n\n        public static bool FastIsByRef(this Type pt)\n        {\n            return (pt.GetTypeFlags() & TypeFlags.IsByRef) != 0;\n        }\n\n        public static bool FastIsPrimitive(this Type pt)\n        {\n            return (pt.GetTypeFlags() & TypeFlags.IsPrimitive) != 0;\n        }\n\n        public static bool FastIsValueType(this Type pt)\n        {\n            return (pt.GetTypeFlags() & TypeFlags.IsValueType) != 0;\n        }\n\n        public static TypeFlags GetTypeFlags(this Type pt)\n        {\n            var result = TypeFlags.Default;\n\n            if (!typeFlags.TryGetValue(pt, out result))\n            {\n                if (pt.IsPrimitive)\n                {\n                    result |= TypeFlags.IsPrimitive;\n                }\n\n                if (pt == typeof(Delegate) || pt.IsSubclassOf(typeof(Delegate)))\n                {\n                    result |= TypeFlags.IsDelegate;\n                }\n\n                if (pt.IsByRef)\n                {\n                    result |= TypeFlags.IsByRef;\n                }\n\n                if (pt.IsEnum)\n                {\n                    result |= TypeFlags.IsEnum;\n                }\n\n                if (pt.IsValueType)\n                {\n                    result |= TypeFlags.IsValueType;\n                }\n\n                typeFlags[pt] = result;\n            }\n\n            return result;\n        }\n\n        public static object CheckCLRTypes(this Type pt, object obj)\n        {\n            if (obj == null)\n                return null;\n\n            var typeFlags = GetTypeFlags(pt);\n\n            if ((typeFlags & TypeFlags.IsPrimitive) != 0 && pt != typeof(int))\n            {\n                if (pt == typeof(bool) && !(obj is bool))\n                {\n                    obj = (int)obj == 1;\n                }\n                else if (pt == typeof(byte) && !(obj is byte))\n                    obj = (byte)(int)obj;\n                else if (pt == typeof(short) && !(obj is short))\n                    obj = (short)(int)obj;\n                else if (pt == typeof(char) && !(obj is char))\n                    obj = (char)(int)obj;\n                else if (pt == typeof(ushort) && !(obj is ushort))\n                    obj = (ushort)(int)obj;\n                else if (pt == typeof(uint) && !(obj is uint))\n                    obj = (uint)(int)obj;\n                else if (pt == typeof(sbyte) && !(obj is sbyte))\n                    obj = (sbyte)(int)obj;\n                else if (pt == typeof(ulong) && !(obj is ulong))\n                {\n                    obj = (ulong)(long)obj;\n                }\n            }\n            else if (obj is ILRuntime.Reflection.ILRuntimeWrapperType)\n            {\n                obj = ((ILRuntime.Reflection.ILRuntimeWrapperType)obj).RealType;\n            }\n            else if ((typeFlags & TypeFlags.IsDelegate) != 0)\n            {\n                if (obj is Delegate)\n                    return obj;\n                if (pt == typeof(Delegate))\n                    return ((IDelegateAdapter)obj).Delegate;\n                return ((IDelegateAdapter)obj).GetConvertor(pt);\n            }\n            else if ((typeFlags & TypeFlags.IsByRef) != 0)\n            {\n                return CheckCLRTypes(pt.GetElementType(), obj);\n            }\n            else if ((typeFlags & TypeFlags.IsEnum) != 0)\n            {\n                return Enum.ToObject(pt, obj);\n            }\n            else if (obj is ILTypeInstance)\n            {\n                var adapter = obj as IDelegateAdapter;\n\n                if (adapter != null && pt != typeof(ILTypeInstance))\n                {\n                    return adapter.Delegate;\n                }\n\n                if (!(obj is ILEnumTypeInstance))\n                {\n                    var ins = (ILTypeInstance)obj;\n                    if (ins.IsValueType)\n                        ins = ins.Clone();\n                    return ins.CLRInstance;\n                }\n            }\n            return obj;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Other/ByReferenceKeyComparer.cs",
    "content": "﻿using System.Collections.Generic;\nusing System.Runtime.CompilerServices;\n\nnamespace ILRuntime.Other\n{\n    class ByReferenceKeyComparer<T> : IEqualityComparer<T>\n    {\n        public bool Equals(T x, T y)\n        {\n            return object.ReferenceEquals(x, y);\n        }\n\n        public int GetHashCode(T obj)\n        {\n            return RuntimeHelpers.GetHashCode(obj);\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Other/DelegateExportAttribute.cs",
    "content": "﻿namespace ILRuntime.Other\n{\n    /// <summary>\n    /// A Delegate Custom Attr, It tells the CodeGenerationTools : this delegate need to register a delegate convertor,when generate ILRuntimeHelper.cs file.\n    /// </summary>\n    public class DelegateExportAttribute : System.Attribute\n    {\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Other/NeedAdaptorAttribute.cs",
    "content": "﻿namespace ILRuntime.Other\n{\n    /// <summary>\n    /// A Class Custom Attr, It tells the CodeGenerationTools :there is a class need to generate an adaptor for ILScript\n    /// </summary>\n    public class NeedAdaptorAttribute : System.Attribute\n    {\n\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Other/ThreadSafeDictionary.cs",
    "content": "﻿using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.Runtime.Versioning;\nusing System.Threading;\n\nnamespace ILRuntime.Other\n{\n    /// <summary>\n    /// A thread safe dictionary for internal use\n    /// </summary>\n    /// <typeparam name=\"K\"></typeparam>\n    /// <typeparam name=\"V\"></typeparam>\n    class ThreadSafeDictionary<K, V> : IDictionary<K, V>\n    {\n        Dictionary<K, V> dic = new Dictionary<K, V>();\n\n        public Dictionary<K,V> InnerDictionary { get { return dic; } }\n        public V this[K key]\n        {\n            get\n            {\n                lock(dic)\n                    return dic[key];\n            }\n\n            set\n            {\n               lock(dic)\n                    dic[key] = value;\n            }\n        }\n\n        public int Count\n        {\n            get\n            {\n                lock(dic)\n                    return dic.Count;\n            }\n        }\n\n        public bool IsReadOnly\n        {\n            get\n            {\n                lock(dic)\n                    return IsReadOnly;\n            }\n        }\n\n        public ICollection<K> Keys\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public ICollection<V> Values\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public void Add(KeyValuePair<K, V> item)\n        {\n            lock (dic)\n                 dic.Add(item.Key, item.Value);\n        }\n\n        public void Add(K key, V value)\n        {\n            lock(dic)\n                dic.Add(key, value);\n        }\n\n        public void Clear()\n        {\n            lock(dic)\n                dic.Clear();\n        }\n\n        public bool Contains(KeyValuePair<K, V> item)\n        {\n           lock(dic)\n                return dic.ContainsKey(item.Key);\n        }\n\n        public bool ContainsKey(K key)\n        {\n            lock(dic)\n                return dic.ContainsKey(key);\n        }\n\n        public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex)\n        {\n            throw new NotImplementedException();\n        }\n\n        public IEnumerator<KeyValuePair<K, V>> GetEnumerator()\n        {\n            throw new NotImplementedException();\n        }\n\n        public bool Remove(KeyValuePair<K, V> item)\n        {\n            throw new NotImplementedException();\n        }\n\n        public bool Remove(K key)\n        {\n            lock(dic)\n                return dic.Remove(key);\n        }\n\n        public bool TryGetValue(K key, out V value)\n        {\n             lock(dic)\n                return dic.TryGetValue(key, out value);\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            throw new NotImplementedException();\n        }\n    }\n}"
  },
  {
    "path": "ILRuntime/ILRuntime/Other/UncheckedList.cs",
    "content": "﻿using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.Runtime.Versioning;\nusing System.Threading;\n\nnamespace ILRuntime.Other\n{\n    /// <summary>\n    /// This is a copy of the latest .NET framework 4.5 List implementation, with all extraneous checking removed.\n    /// </summary>\n    /// <typeparam name=\"T\"></typeparam>\n    [Serializable]\n    public class UncheckedList<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection\n    {\n\n       private const int _defaultCapacity = 4;\n\n        private T[] _items;\n        private int _size;\n        private int _version;\n        [NonSerialized]\n        private Object _syncRoot;\n\n        private static readonly T[] _emptyArray = new T[0];\n\n        // Constructs a UncheckedList. The list is initially empty and has a capacity\n        // of zero. Upon adding the first element to the list the capacity is\n        // increased to _defaultCapacity, and then increased in multiples of two\n        // as required.\n        public UncheckedList()\n        {\n            _items = _emptyArray;\n        }\n\n        // Constructs a UncheckedList with a given initial capacity. The list is\n        // initially empty, but will have room for the given number of elements\n        // before any reallocations are required.\n        // \n        public UncheckedList(int capacity)\n        {\n            if (capacity == 0)\n                _items = _emptyArray;\n            else\n                _items = new T[capacity];\n        }\n\n        // Constructs a UncheckedList, copying the contents of the given collection. The\n        // size and capacity of the new list will both be equal to the size of the\n        // given collection.\n        // \n        public UncheckedList(IEnumerable<T> collection)\n        {\n            ICollection<T> c = collection as ICollection<T>;\n            if (c != null)\n            {\n                int count = c.Count;\n                if (count == 0)\n                {\n                    _items = _emptyArray;\n                }\n                else\n                {\n                    _items = new T[count];\n                    c.CopyTo(_items, 0);\n                    _size = count;\n                }\n            }\n            else\n            {\n                _size = 0;\n                _items = _emptyArray;\n                AddEnumerable(collection);\n            }\n        }\n\n        // Gets and sets the capacity of this list.  The capacity is the size of\n        // the internal array used to hold items.  When set, the internal \n        // array of the list is reallocated to the given capacity.\n        // \n        public int Capacity\n        {\n            get\n            {\n                return _items.Length;\n            }\n            set\n            {\n                if (value != _items.Length)\n                {\n                    if (value > 0)\n                    {\n                        T[] newItems = new T[value];\n                        if (_size > 0)\n                        {\n                            Array.Copy(_items, 0, newItems, 0, _size);\n                        }\n                        _items = newItems;\n                    }\n                    else\n                    {\n                        _items = _emptyArray;\n                    }\n                }\n            }\n        }\n\n        // Read-only property describing how many elements are in the UncheckedList.\n        public int Count\n        {\n            get\n            {\n                return _size;\n            }\n        }\n\n        bool System.Collections.IList.IsFixedSize\n        {\n            get { return false; }\n        }\n\n\n        // Is this UncheckedList read-only?\n        bool ICollection<T>.IsReadOnly\n        {\n            get { return false; }\n        }\n\n        bool System.Collections.IList.IsReadOnly\n        {\n            get { return false; }\n        }\n\n        // Is this UncheckedList synchronized (thread-safe)?\n        bool System.Collections.ICollection.IsSynchronized\n        {\n            get { return false; }\n        }\n\n        // Synchronization root for this object.\n        Object System.Collections.ICollection.SyncRoot\n        {\n            get\n            {\n                if (_syncRoot == null)\n                {\n                    System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);\n                }\n                return _syncRoot;\n            }\n        }\n        // Sets or Gets the element at the given index.\n        // \n        public T this[int index]\n        {\n            get\n            {\n                return _items[index];\n            }\n\n            set\n            {\n                _items[index] = value;\n                _version++;\n            }\n        }\n\n        private static bool IsCompatibleObject(object value)\n        {\n            // Non-null values are fine.  Only accept nulls if T is a class or Nullable<U>.\n            // Note that default(T) is not equal to null for value types except when T is Nullable<U>. \n            return ((value is T) || (value == null && default(T) == null));\n        }\n\n        Object System.Collections.IList.this[int index]\n        {\n            get\n            {\n                return this[index];\n            }\n            set\n            {\n                try\n                {\n                    this[index] = (T)value;\n                }\n                catch (InvalidCastException)\n                {\n                }\n            }\n        }\n\n        // Adds the given object to the end of this list. The size of the list is\n        // increased by one. If required, the capacity of the list is doubled\n        // before adding the new element.\n        public void Add(T item)\n        {\n            var array = _items;\n            var size = _size;\n            _version++;\n            if ((uint)size < (uint)array.Length)\n            {\n                _size = size + 1;\n                array[size] = item;\n            }\n            else\n            {\n                AddWithResize(item);\n            }\n        }\n\n        // Non-inline from UncheckedList.Add to improve its code quality as uncommon path\n        private void AddWithResize(T item)\n        {\n            var size = _size;\n            EnsureCapacity(size + 1);\n            _size = size + 1;\n            _items[size] = item;\n        }\n\n        int System.Collections.IList.Add(Object item)\n        {\n            try\n            {\n                Add((T)item);\n            }\n            catch (InvalidCastException)\n            {\n            }\n\n            return Count - 1;\n        }\n\n\n        // Adds the elements of the given collection to the end of this list. If\n        // required, the capacity of the list is increased to twice the previous\n        // capacity or the new size, whichever is larger.\n        //\n        public void AddRange(IEnumerable<T> collection)\n        {\n            InsertRange(_size, collection);\n        }\n\n        public ReadOnlyCollection<T> AsReadOnly()\n        {\n            return new ReadOnlyCollection<T>(this);\n        }\n\n        // Searches a section of the list for a given element using a binary search\n        // algorithm. Elements of the list are compared to the search value using\n        // the given IComparer interface. If comparer is null, elements of\n        // the list are compared to the search value using the IComparable\n        // interface, which in that case must be implemented by all elements of the\n        // list and the given search value. This method assumes that the given\n        // section of the list is already sorted; if this is not the case, the\n        // result will be incorrect.\n        //\n        // The method returns the index of the given value in the list. If the\n        // list does not contain the given value, the method returns a negative\n        // integer. The bitwise complement operator (~) can be applied to a\n        // negative result to produce the index of the first element (if any) that\n        // is larger than the given search value. This is also the index at which\n        // the search value should be inserted into the list in order for the list\n        // to remain sorted.\n        // \n        // The method uses the Array.BinarySearch method to perform the\n        // search.\n        // \n        public int BinarySearch(int index, int count, T item, IComparer<T> comparer)\n        {\n            if (index < 0) return -1;\n            return Array.BinarySearch<T>(_items, index, count, item, comparer);\n        }\n\n        public int BinarySearch(T item)\n        {\n            return BinarySearch(0, Count, item, null);\n        }\n\n        public int BinarySearch(T item, IComparer<T> comparer)\n        {\n            return BinarySearch(0, Count, item, comparer);\n        }\n\n\n        // Clears the contents of UncheckedList.\n        public void Clear()\n        {\n            if (!typeof(T).IsValueType)\n            {\n                int size = _size;\n                _size = 0;\n                _version++;\n                if (size > 0)\n                {\n                    Array.Clear(_items, 0, size); // Clear the elements so that the gc can reclaim the references.\n                }\n            }\n            else\n            {\n                _size = 0;\n                _version++;\n            }\n        }\n\n        // Contains returns true if the specified element is in the UncheckedList.\n        // It does a linear, O(n) search.  Equality is determined by calling\n        // EqualityComparer<T>.Default.Equals().\n\n        public bool Contains(T item)\n        {\n            // PERF: IndexOf calls Array.IndexOf, which internally\n            // calls EqualityComparer<T>.Default.IndexOf, which\n            // is specialized for different types. This\n            // boosts performance since instead of making a\n            // virtual method call each iteration of the loop,\n            // via EqualityComparer<T>.Default.Equals, we\n            // only make one virtual call to EqualityComparer.IndexOf.\n\n            return _size != 0 && IndexOf(item) != -1;\n        }\n\n        bool System.Collections.IList.Contains(Object item)\n        {\n            if (IsCompatibleObject(item))\n            {\n                return Contains((T)item);\n            }\n            return false;\n        }\n\n        public UncheckedList<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter)\n        {\n            UncheckedList<TOutput> list = new UncheckedList<TOutput>(_size);\n            for (int i = 0; i < _size; i++)\n            {\n                list._items[i] = converter(_items[i]);\n            }\n            list._size = _size;\n            return list;\n        }\n\n        // Copies this UncheckedList into array, which must be of a \n        // compatible array type.  \n        //\n        public void CopyTo(T[] array)\n        {\n            CopyTo(array, 0);\n        }\n\n        // Copies this UncheckedList into array, which must be of a \n        // compatible array type.  \n        //\n        void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)\n        {\n            try\n            {\n                // Array.Copy will check for NULL.\n                Array.Copy(_items, 0, array, arrayIndex, _size);\n            }\n            catch (ArrayTypeMismatchException)\n            {\n            }\n        }\n\n        // Copies a section of this list to the given array at the given index.\n        // \n        // The method uses the Array.Copy method to copy the elements.\n        // \n        public void CopyTo(int index, T[] array, int arrayIndex, int count)\n        {\n            // Delegate rest of error checking to Array.Copy.\n            Array.Copy(_items, index, array, arrayIndex, count);\n        }\n\n        public void CopyTo(T[] array, int arrayIndex)\n        {\n            // Delegate rest of error checking to Array.Copy.\n            Array.Copy(_items, 0, array, arrayIndex, _size);\n        }\n\n        // Ensures that the capacity of this list is at least the given minimum\n        // value. If the current capacity of the list is less than min, the\n        // capacity is increased to twice the current capacity or to min,\n        // whichever is larger.\n        private void EnsureCapacity(int min)\n        {\n            if (_items.Length < min)\n            {\n                int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2;\n                // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.\n                // Note that this check works even when _items.Length overflowed thanks to the (uint) cast\n                if ((uint) newCapacity > Int32.MaxValue) newCapacity = Int32.MaxValue;\n                if (newCapacity < min) newCapacity = min;\n                Capacity = newCapacity;\n            }\n        }\n\n        public bool Exists(Predicate<T> match)\n        {\n            return FindIndex(match) != -1;\n        }\n\n        public T Find(Predicate<T> match)\n        {\n            for (int i = 0; i < _size; i++)\n            {\n                if (match(_items[i]))\n                {\n                    return _items[i];\n                }\n            }\n            return default(T);\n        }\n\n        public UncheckedList<T> FindAll(Predicate<T> match)\n        {\n            UncheckedList<T> list = new UncheckedList<T>();\n            for (int i = 0; i < _size; i++)\n            {\n                if (match(_items[i]))\n                {\n                    list.Add(_items[i]);\n                }\n            }\n            return list;\n        }\n\n        public int FindIndex(Predicate<T> match)\n        {\n            return FindIndex(0, _size, match);\n        }\n\n        public int FindIndex(int startIndex, Predicate<T> match)\n        {\n            return FindIndex(startIndex, _size - startIndex, match);\n        }\n\n        public int FindIndex(int startIndex, int count, Predicate<T> match)\n        {\n            int endIndex = startIndex + count;\n            for (int i = startIndex; i < endIndex; i++)\n            {\n                if (match(_items[i])) return i;\n            }\n            return -1;\n        }\n\n        public T FindLast(Predicate<T> match)\n        {\n            for (int i = _size - 1; i >= 0; i--)\n            {\n                if (match(_items[i]))\n                {\n                    return _items[i];\n                }\n            }\n            return default(T);\n        }\n\n        public int FindLastIndex(Predicate<T> match)\n        {\n            return FindLastIndex(_size - 1, _size, match);\n        }\n\n        public int FindLastIndex(int startIndex, Predicate<T> match)\n        {\n            return FindLastIndex(startIndex, startIndex + 1, match);\n        }\n\n        public int FindLastIndex(int startIndex, int count, Predicate<T> match)\n        {\n            int endIndex = startIndex - count;\n            for (int i = startIndex; i > endIndex; i--)\n            {\n                if (match(_items[i]))\n                {\n                    return i;\n                }\n            }\n            return -1;\n        }\n\n        public void ForEach(Action<T> action)\n        {\n            int version = _version;\n\n            for (int i = 0; i < _size; i++)\n            {\n                if (version != _version)\n                {\n                    break;\n                }\n                action(_items[i]);\n            }\n        }\n\n        // Returns an enumerator for this list with the given\n        // permission for removal of elements. If modifications made to the list \n        // while an enumeration is in progress, the MoveNext and \n        // GetObject methods of the enumerator will throw an exception.\n        //\n        public Enumerator GetEnumerator()\n        {\n            return new Enumerator(this);\n        }\n\n        IEnumerator<T> IEnumerable<T>.GetEnumerator()\n        {\n            return new Enumerator(this);\n        }\n\n        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n        {\n            return new Enumerator(this);\n        }\n\n        public UncheckedList<T> GetRange(int index, int count)\n        {\n            UncheckedList<T> list = new UncheckedList<T>(count);\n            Array.Copy(_items, index, list._items, 0, count);\n            list._size = count;\n            return list;\n        }\n\n\n        // Returns the index of the first occurrence of a given value in a range of\n        // this list. The list is searched forwards from beginning to end.\n        // The elements of the list are compared to the given value using the\n        // Object.Equals method.\n        // \n        // This method uses the Array.IndexOf method to perform the\n        // search.\n        // \n        public int IndexOf(T item)\n        {\n            return Array.IndexOf(_items, item, 0, _size);\n        }\n\n        int System.Collections.IList.IndexOf(Object item)\n        {\n            if (IsCompatibleObject(item))\n            {\n                return IndexOf((T)item);\n            }\n            return -1;\n        }\n\n        // Returns the index of the first occurrence of a given value in a range of\n        // this list. The list is searched forwards, starting at index\n        // index and ending at count number of elements. The\n        // elements of the list are compared to the given value using the\n        // Object.Equals method.\n        // \n        // This method uses the Array.IndexOf method to perform the\n        // search.\n        // \n        public int IndexOf(T item, int index)\n        {\n            return Array.IndexOf(_items, item, index, _size - index);\n        }\n\n        // Returns the index of the first occurrence of a given value in a range of\n        // this list. The list is searched forwards, starting at index\n        // index and upto count number of elements. The\n        // elements of the list are compared to the given value using the\n        // Object.Equals method.\n        // \n        // This method uses the Array.IndexOf method to perform the\n        // search.\n        // \n        public int IndexOf(T item, int index, int count)\n        {\n            return Array.IndexOf(_items, item, index, count);\n        }\n\n        // Inserts an element into this list at a given index. The size of the list\n        // is increased by one. If required, the capacity of the list is doubled\n        // before inserting the new element.\n        // \n        public void Insert(int index, T item)\n        {\n            if (_size == _items.Length) EnsureCapacity(_size + 1);\n            if (index < _size)\n            {\n                Array.Copy(_items, index, _items, index + 1, _size - index);\n            }\n            _items[index] = item;\n            _size++;\n            _version++;\n        }\n\n        void System.Collections.IList.Insert(int index, Object item)\n        {\n            try\n            {\n                Insert(index, (T)item);\n            }\n            catch (InvalidCastException)\n            {\n            }\n        }\n\n        // Inserts the elements of the given collection at a given index. If\n        // required, the capacity of the list is increased to twice the previous\n        // capacity or the new size, whichever is larger.  Ranges may be added\n        // to the end of the list by setting index to the UncheckedList's size.\n        //\n        public void InsertRange(int index, IEnumerable<T> collection)\n        {\n            ICollection<T> c = collection as ICollection<T>;\n            if (c != null)\n            {    // if collection is ICollection<T>\n                int count = c.Count;\n                if (count > 0)\n                {\n                    EnsureCapacity(_size + count);\n                    if (index < _size)\n                    {\n                        Array.Copy(_items, index, _items, index + count, _size - index);\n                    }\n\n                    // If we're inserting a UncheckedList into itself, we want to be able to deal with that.\n                    if (this == c)\n                    {\n                        // Copy first part of _items to insert location\n                        Array.Copy(_items, 0, _items, index, index);\n                        // Copy last part of _items back to inserted location\n                        Array.Copy(_items, index + count, _items, index * 2, _size - index);\n                    }\n                    else\n                    {\n                        c.CopyTo(_items, index);\n                    }\n                    _size += count;\n                }\n            }\n            else if (index < _size)\n            {\n                // We're inserting a lazy enumerable. Call Insert on each of the constituent items.\n                using (IEnumerator<T> en = collection.GetEnumerator())\n                {\n                    while (en.MoveNext())\n                    {\n                        Insert(index++, en.Current);\n                    }\n                }\n            }\n            else\n            {\n                // We're adding a lazy enumerable because the index is at the end of this list.\n                AddEnumerable(collection);\n            }\n            _version++;\n        }\n\n        // Returns the index of the last occurrence of a given value in a range of\n        // this list. The list is searched backwards, starting at the end \n        // and ending at the first element in the list. The elements of the list \n        // are compared to the given value using the Object.Equals method.\n        // \n        // This method uses the Array.LastIndexOf method to perform the\n        // search.\n        // \n        public int LastIndexOf(T item)\n        {\n            if (_size == 0)\n            {  // Special case for empty list\n                return -1;\n            }\n            else\n            {\n                return LastIndexOf(item, _size - 1, _size);\n            }\n        }\n\n        // Returns the index of the last occurrence of a given value in a range of\n        // this list. The list is searched backwards, starting at index\n        // index and ending at the first element in the list. The \n        // elements of the list are compared to the given value using the \n        // Object.Equals method.\n        // \n        // This method uses the Array.LastIndexOf method to perform the\n        // search.\n        // \n        public int LastIndexOf(T item, int index)\n        {\n            return LastIndexOf(item, index, index + 1);\n        }\n\n        // Returns the index of the last occurrence of a given value in a range of\n        // this list. The list is searched backwards, starting at index\n        // index and upto count elements. The elements of\n        // the list are compared to the given value using the Object.Equals\n        // method.\n        // \n        // This method uses the Array.LastIndexOf method to perform the\n        // search.\n        // \n        public int LastIndexOf(T item, int index, int count)\n        {\n            if (_size == 0)\n            {  // Special case for empty list\n                return -1;\n            }\n\n            return Array.LastIndexOf(_items, item, index, count);\n        }\n\n        // Removes the element at the given index. The size of the list is\n        // decreased by one.\n        // \n        public bool Remove(T item)\n        {\n            int index = IndexOf(item);\n            if (index >= 0)\n            {\n                RemoveAt(index);\n                return true;\n            }\n\n            return false;\n        }\n\n        void System.Collections.IList.Remove(Object item)\n        {\n            if (IsCompatibleObject(item))\n            {\n                Remove((T)item);\n            }\n        }\n\n        // This method removes all items which matches the predicate.\n        // The complexity is O(n).   \n        public int RemoveAll(Predicate<T> match)\n        {\n            int freeIndex = 0;   // the first free slot in items array\n\n            // Find the first item which needs to be removed.\n            while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++;\n            if (freeIndex >= _size) return 0;\n\n            int current = freeIndex + 1;\n            while (current < _size)\n            {\n                // Find the first item which needs to be kept.\n                while (current < _size && match(_items[current])) current++;\n\n                if (current < _size)\n                {\n                    // copy item to the free slot.\n                    _items[freeIndex++] = _items[current++];\n                }\n            }\n\n            if (!typeof(T).IsValueType)\n            {\n                Array.Clear(_items, freeIndex, _size - freeIndex); // Clear the elements so that the gc can reclaim the references.\n            }\n\n            int result = _size - freeIndex;\n            _size = freeIndex;\n            _version++;\n            return result;\n        }\n\n        // Removes the element at the given index. The size of the list is\n        // decreased by one.\n        // \n        public void RemoveAt(int index)\n        {\n            _size--;\n            if (index < _size)\n            {\n                Array.Copy(_items, index + 1, _items, index, _size - index);\n            }\n            if (!typeof(T).IsValueType)\n            {\n                _items[_size] = default(T);\n            }\n            _version++;\n        }\n\n        // Removes a range of elements from this list.\n        // \n        public void RemoveRange(int index, int count)\n        {\n            if (count > 0)\n            {\n                int i = _size;\n                _size -= count;\n                if (index < _size)\n                {\n                    Array.Copy(_items, index + count, _items, index, _size - index);\n                }\n\n                _version++;\n                if (!typeof(T).IsValueType)\n                {\n                    Array.Clear(_items, _size, count);\n                }\n            }\n        }\n\n        // Reverses the elements in this list.\n        public void Reverse()\n        {\n            Reverse(0, Count);\n        }\n\n        // Reverses the elements in a range of this list. Following a call to this\n        // method, an element in the range given by index and count\n        // which was previously located at index i will now be located at\n        // index index + (index + count - i - 1).\n        // \n        public void Reverse(int index, int count)\n        {\n            if (count > 1)\n            {\n                Array.Reverse(_items, index, count);\n            }\n            _version++;\n        }\n\n        // Sorts the elements in this list.  Uses the default comparer and \n        // Array.Sort.\n        public void Sort()\n        {\n            Sort(0, Count, null);\n        }\n\n        // Sorts the elements in this list.  Uses Array.Sort with the\n        // provided comparer.\n        public void Sort(IComparer<T> comparer)\n        {\n            Sort(0, Count, comparer);\n        }\n\n        // Sorts the elements in a section of this list. The sort compares the\n        // elements to each other using the given IComparer interface. If\n        // comparer is null, the elements are compared to each other using\n        // the IComparable interface, which in that case must be implemented by all\n        // elements of the list.\n        // \n        // This method uses the Array.Sort method to sort the elements.\n        // \n        public void Sort(int index, int count, IComparer<T> comparer)\n        {\n            if (count > 1)\n            {\n                Array.Sort<T>(_items, index, count, comparer);\n            }\n            _version++;\n        }\n\n        public void Sort(Comparison<T> comparison)\n        {\n            throw new NotImplementedException();\n            /*if (_size > 1)\n            {\n                ArraySortHelper<T>.Sort(_items, 0, _size, comparison);\n            }\n            _version++;*/\n        }\n\n        // ToArray returns an array containing the contents of the UncheckedList.\n        // This requires copying the UncheckedList, which is an O(n) operation.\n        public T[] ToArray()\n        {\n            if (_size == 0)\n            {\n                return _emptyArray;\n            }\n\n            T[] array = new T[_size];\n            Array.Copy(_items, 0, array, 0, _size);\n            return array;\n        }\n\n        // Sets the capacity of this list to the size of the list. This method can\n        // be used to minimize a list's memory overhead once it is known that no\n        // new elements will be added to the list. To completely clear a list and\n        // release all memory referenced by the list, execute the following\n        // statements:\n        // \n        // list.Clear();\n        // list.TrimExcess();\n        // \n        public void TrimExcess()\n        {\n            int threshold = (int)(((double)_items.Length) * 0.9);\n            if (_size < threshold)\n            {\n                Capacity = _size;\n            }\n        }\n\n        public bool TrueForAll(Predicate<T> match)\n        {\n            for (int i = 0; i < _size; i++)\n            {\n                if (!match(_items[i]))\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        private void AddEnumerable(IEnumerable<T> enumerable)\n        {\n            Debug.Assert(enumerable != null);\n            Debug.Assert(!(enumerable is ICollection<T>), \"We should have optimized for this beforehand.\");\n\n            using (IEnumerator<T> en = enumerable.GetEnumerator())\n            {\n                _version++; // Even if the enumerable has no items, we can update _version.\n\n                while (en.MoveNext())\n                {\n                    // Capture Current before doing anything else. If this throws\n                    // an exception, we want to make a clean break.\n                    T current = en.Current;\n\n                    if (_size == _items.Length)\n                    {\n                        EnsureCapacity(_size + 1);\n                    }\n\n                    _items[_size++] = current;\n                }\n            }\n        }\n\n        public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator\n        {\n            private UncheckedList<T> list;\n            private int index;\n            private int version;\n            private T current;\n\n            internal Enumerator(UncheckedList<T> list)\n            {\n                this.list = list;\n                index = 0;\n                version = list._version;\n                current = default(T);\n            }\n\n            public void Dispose()\n            {\n            }\n\n            public bool MoveNext()\n            {\n                UncheckedList<T> localUncheckedList = list;\n\n                if (version == localUncheckedList._version && ((uint)index < (uint)localUncheckedList._size))\n                {\n                    current = localUncheckedList._items[index];\n                    index++;\n                    return true;\n                }\n                return MoveNextRare();\n            }\n\n            private bool MoveNextRare()\n            {\n                index = list._size + 1;\n                current = default(T);\n                return false;\n            }\n\n            public T Current\n            {\n                get\n                {\n                    return current;\n                }\n            }\n\n            Object System.Collections.IEnumerator.Current\n            {\n                get\n                {\n                    return Current;\n                }\n            }\n\n            void System.Collections.IEnumerator.Reset()\n            {\n                index = 0;\n                current = default(T);\n            }\n        }\n    }\n}"
  },
  {
    "path": "ILRuntime/ILRuntime/Reflection/Extensions.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing Mono.Cecil;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\n\nnamespace ILRuntime.Reflection\n{\n    static class Extensions\n    {\n        public static object CreateInstance(this CustomAttribute attribute, IType at, Runtime.Enviorment.AppDomain appdomain)\n        {\n            object ins;\n            List<IType> param = null;\n            if (at is ILType)\n            {\n                var it = (ILType)at;\n                if (!attribute.HasConstructorArguments)\n                    ins = it.Instantiate(true);\n                else\n                {\n                    ins = it.Instantiate(false);\n                    if (param == null)\n                        param = new List<IType>();\n                    param.Clear();\n                    object[] p = new object[attribute.ConstructorArguments.Count];\n                    for (int j = 0; j < attribute.ConstructorArguments.Count; j++)\n                    {\n                        var ca = attribute.ConstructorArguments[j];\n                        param.Add(appdomain.GetType(ca.Type, null, null));\n                        p[j] = ca.Value;\n                    }\n                    var ctor = it.GetConstructor(param);\n                    appdomain.Invoke(ctor, ins, p);\n                }\n\n                if (attribute.HasProperties)\n                {\n                    object[] p = new object[1];\n                    foreach (var j in attribute.Properties)\n                    {\n                        p[0] = j.Argument.Value;\n                        var setter = it.GetMethod(\"set_\" + j.Name, 1);\n                        appdomain.Invoke(setter, ins, p);\n                    }\n                }\n            }\n            else\n            {\n                param = new List<IType>();\n                object[] p = null;\n                if (attribute.HasConstructorArguments)\n                {\n                    p = new object[attribute.ConstructorArguments.Count];\n                    for (int j = 0; j < attribute.ConstructorArguments.Count; j++)\n                    {\n                        var ca = attribute.ConstructorArguments[j];\n                        param.Add(appdomain.GetType(ca.Type, null, null));\n                        p[j] = ca.Value;\n                    }\n                }\n                ins = ((CLRMethod)at.GetConstructor(param)).ConstructorInfo.Invoke(p);\n                if (attribute.HasProperties)\n                {\n                    foreach (var j in attribute.Properties)\n                    {\n                        var prop = at.TypeForCLR.GetProperty(j.Name);\n                        prop.SetValue(ins, j.Argument.Value, null);\n                    }\n                }\n            }\n\n            return ins;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Reflection/ILRuntimeConstructorInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Globalization;\n\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeConstructorInfo : ConstructorInfo\n    {\n        ILMethod method;\n        ILRuntimeParameterInfo[] parameters;\n        public ILRuntimeConstructorInfo(ILMethod m)\n        {\n            method = m;\n            parameters = new ILRuntimeParameterInfo[m.ParameterCount];\n            for(int i = 0; i < m.ParameterCount; i++)\n            {\n                parameters[i] = new ILRuntimeParameterInfo(m.Parameters[i]);\n            }\n        }\n\n        internal ILMethod ILMethod { get { return method; } }\n        public override MethodAttributes Attributes\n        {\n            get\n            {\n                return MethodAttributes.Public;\n            }\n        }\n\n        public override Type DeclaringType\n        {\n            get\n            {\n                return method.DeclearingType.ReflectionType;\n            }\n        }\n\n        public override RuntimeMethodHandle MethodHandle\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return method.Name;\n            }\n        }\n\n        public override Type ReflectedType\n        {\n            get\n            {\n                return method.DeclearingType.ReflectionType;\n            }\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override MethodImplAttributes GetMethodImplementationFlags()\n        {\n            throw new NotImplementedException();\n        }\n\n        public override ParameterInfo[] GetParameters()\n        {\n            return parameters;\n        }\n\n        public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)\n        {\n            var res = ((ILType)method.DeclearingType).Instantiate(false);\n            method.DeclearingType.AppDomain.Invoke(method, res, parameters);\n            return res;\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)\n        {\n            var res = ((ILType)method.DeclearingType).Instantiate(false);\n            method.DeclearingType.AppDomain.Invoke(method, res, parameters);\n            return res;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Reflection/ILRuntimeFieldInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Globalization;\n\nusing Mono.Cecil;\nusing ILRuntime.CLR.Utils;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeFieldInfo : FieldInfo\n    {\n        System.Reflection.FieldAttributes attr;\n        ILRuntimeType dType;\n        ILType ilType;\n        IType fieldType;\n        bool isStatic;\n        int fieldIdx;\n        string name;\n        FieldDefinition definition;\n        Runtime.Enviorment.AppDomain appdomain;\n        object[] customAttributes;\n        Type[] attributeTypes;\n\n        public IType ILFieldType { get { return fieldType; } }\n\n        public ILRuntimeFieldInfo(FieldDefinition def, ILRuntimeType declaredType, bool isStatic, int fieldIdx)\n        {\n            definition = def;\n            this.name = def.Name;\n            dType = declaredType;\n            ilType = dType.ILType;\n            appdomain = ilType.AppDomain;\n            this.isStatic = isStatic;\n            this.fieldIdx = fieldIdx; \n            if (isStatic)\n                attr |= System.Reflection.FieldAttributes.Static;\n            if (def.IsPublic)\n            {\n                attr |= System.Reflection.FieldAttributes.Public;\n            }\n            else\n                attr |= System.Reflection.FieldAttributes.Private;\n            fieldType = isStatic ? ilType.StaticFieldTypes[fieldIdx] : ilType.FieldTypes[fieldIdx];\n        }\n\n        public ILRuntimeFieldInfo(FieldDefinition def, ILRuntimeType declaredType, int fieldIdx, IType fieldType)\n        {\n            definition = def;\n            this.name = def.Name;\n            dType = declaredType;\n            ilType = dType.ILType;\n            appdomain = ilType.AppDomain;\n            this.isStatic = false;\n            this.fieldIdx = fieldIdx;\n            if (isStatic)\n                attr |= System.Reflection.FieldAttributes.Static;\n            if (def.IsPublic)\n            {\n                attr |= System.Reflection.FieldAttributes.Public;\n            }\n            else\n                attr |= System.Reflection.FieldAttributes.Private;\n            this.fieldType = fieldType;\n        }\n\n        void InitializeCustomAttribute()\n        {\n            customAttributes = new object[definition.CustomAttributes.Count];\n            attributeTypes = new Type[customAttributes.Length];\n            for (int i = 0; i < definition.CustomAttributes.Count; i++)\n            {\n                var attribute = definition.CustomAttributes[i];\n                var at = appdomain.GetType(attribute.AttributeType, null, null);\n                try\n                {\n                    object ins = attribute.CreateInstance(at, appdomain);\n\n                    attributeTypes[i] = at.ReflectionType;\n                    customAttributes[i] = ins;\n                }\n                catch\n                {\n                    attributeTypes[i] = typeof(Attribute);\n                }\n            }\n        }\n\n        public override System.Reflection.FieldAttributes Attributes\n        {\n            get\n            {\n                return attr;\n            }\n        }\n\n        public override Type DeclaringType\n        {\n            get\n            {\n                return dType;\n            }\n        }\n\n        public override RuntimeFieldHandle FieldHandle\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override Type FieldType\n        {\n            get\n            {\n                return fieldType.ReflectionType;\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return name;\n            }\n        }\n\n        public override Type ReflectedType\n        {\n            get\n            {\n                return fieldType.ReflectionType;\n            }\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n\n            return customAttributes;\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            List<object> res = new List<object>();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    res.Add(customAttributes[i]);\n            }\n            return res.ToArray();\n        }\n\n        public override object GetValue(object obj)\n        {\n            unsafe\n            {\n                StackObject esp;\n                ILTypeInstance ins;\n                if (isStatic)\n                {\n                    ins = ilType.StaticInstance;\n                }\n                else\n                {\n                    if (obj is ILTypeInstance)\n                        ins = (ILTypeInstance)obj;\n                    else\n                        ins = ((CrossBindingAdaptorType)obj).ILInstance;\n                }\n                return fieldType.TypeForCLR.CheckCLRTypes(ins[fieldIdx]);\n            }\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    return true;\n            }\n            return false;\n        }\n\n        public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)\n        {\n            unsafe\n            {\n                StackObject esp;\n                if (value is CrossBindingAdaptorType)\n                    value = ((CrossBindingAdaptorType)value).ILInstance;\n                ILTypeInstance ins;\n                if (isStatic)\n                {\n                    ins = ilType.StaticInstance;\n                }\n                else\n                {\n                    if (obj is ILTypeInstance)\n                        ins = (ILTypeInstance)obj;\n                    else\n                        ins = ((CrossBindingAdaptorType)obj).ILInstance;\n                }\n                ins[fieldIdx] = value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Reflection/ILRuntimeMethodInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Globalization;\n\nusing ILRuntime.CLR.Method;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeMethodInfo : MethodInfo\n    {\n        ILMethod method;\n        ILRuntimeParameterInfo[] parameters;\n        Mono.Cecil.MethodDefinition definition;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n\n        object[] customAttributes;\n        Type[] attributeTypes;\n        public ILRuntimeMethodInfo(ILMethod m)\n        {\n            method = m;\n            definition = m.Definition;\n            appdomain = m.DeclearingType.AppDomain;\n            parameters = new ILRuntimeParameterInfo[m.ParameterCount];\n            for (int i = 0; i < m.ParameterCount; i++)\n            {\n                parameters[i] = new ILRuntimeParameterInfo(m.Parameters[i]);\n            }\n        }\n\n        void InitializeCustomAttribute()\n        {\n            customAttributes = new object[definition.CustomAttributes.Count];\n            attributeTypes = new Type[customAttributes.Length];\n            for (int i = 0; i < definition.CustomAttributes.Count; i++)\n            {\n                var attribute = definition.CustomAttributes[i];\n                var at = appdomain.GetType(attribute.AttributeType, null, null);\n                try\n                {\n                    object ins = attribute.CreateInstance(at, appdomain);\n\n                    attributeTypes[i] = at.ReflectionType;\n                    customAttributes[i] = ins;\n                }\n                catch\n                {\n                    attributeTypes[i] = typeof(Attribute);\n                }\n            }\n        }\n\n        internal ILMethod ILMethod { get { return method; } }\n        public override MethodAttributes Attributes\n        {\n            get\n            {\n                return MethodAttributes.Public;\n            }\n        }\n\n        public override Type DeclaringType\n        {\n            get\n            {\n                return method.DeclearingType.ReflectionType;\n            }\n        }\n\n        public override RuntimeMethodHandle MethodHandle\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return method.Name;\n            }\n        }\n\n        public override Type ReflectedType\n        {\n            get\n            {\n                return method.DeclearingType.ReflectionType;\n            }\n        }\n\n        public override ICustomAttributeProvider ReturnTypeCustomAttributes\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override MethodInfo GetBaseDefinition()\n        {\n            return this;\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n\n            return customAttributes;\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            List<object> res = new List<object>();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    res.Add(customAttributes[i]);\n            }\n            return res.ToArray();\n        }\n\n        public override MethodImplAttributes GetMethodImplementationFlags()\n        {\n            throw new NotImplementedException();\n        }\n\n        public override ParameterInfo[] GetParameters()\n        {\n            throw new NotImplementedException();\n        }\n\n        public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)\n        {\n            if (method.HasThis)\n            {\n                var res = appdomain.Invoke(method, obj, parameters);\n                return res;\n            }\n            else\n                return appdomain.Invoke(method, null, parameters);\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    return true;\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Reflection/ILRuntimeParameterInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Globalization;\n\nusing ILRuntime.CLR.TypeSystem;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeParameterInfo : ParameterInfo\n    {\n        IType type;\n\n        public ILRuntimeParameterInfo(IType type)\n        {\n            this.type = type;\n        }\n        public override Type ParameterType\n        {\n            get\n            {\n                return type.ReflectionType;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Reflection/ILRuntimePropertyInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Globalization;\n\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimePropertyInfo : PropertyInfo\n    {\n        ILMethod getter, setter;\n        ILType dType;\n        Mono.Cecil.PropertyDefinition definition;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n\n        object[] customAttributes;\n        Type[] attributeTypes;\n        static object[] param = new object[1];\n\n        public ILMethod Getter\n        {\n            get { return getter; }\n            set\n            {\n                getter = value;\n            }\n        }\n\n        public ILMethod Setter\n        {\n            get { return setter; }\n            set\n            {\n                setter = value;\n            }\n        }\n\n        public bool IsPublic\n        {\n            get\n            {\n                if (getter != null)\n                    return getter.Definition.IsPublic;\n                else\n                    return setter.Definition.IsPublic;\n            }\n        }\n\n        public bool IsStatic\n        {\n            get\n            {\n                if (getter != null)\n                    return getter.IsStatic;\n                else\n                    return setter.IsStatic;\n            }\n        }\n        public ILRuntimePropertyInfo(Mono.Cecil.PropertyDefinition definition, ILType dType)\n        {\n            this.definition = definition;\n            this.dType = dType;\n            appdomain = dType.AppDomain;\n        }\n\n        void InitializeCustomAttribute()\n        {\n            customAttributes = new object[definition.CustomAttributes.Count];\n            attributeTypes = new Type[customAttributes.Length];\n            for (int i = 0; i < definition.CustomAttributes.Count; i++)\n            {\n                var attribute = definition.CustomAttributes[i];\n                var at = appdomain.GetType(attribute.AttributeType, null, null);\n                try\n                {\n                    object ins = attribute.CreateInstance(at, appdomain);\n\n                    attributeTypes[i] = at.ReflectionType;\n                    customAttributes[i] = ins;\n                }\n                catch\n                {\n                    attributeTypes[i] = typeof(Attribute);\n                }\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return definition.Name;\n            }\n        }\n\n        public override Type ReflectedType\n        {\n            get\n            {\n                return dType.ReflectionType;\n            }\n        }\n\n        public override PropertyAttributes Attributes\n        {\n            get\n            {\n                return PropertyAttributes.None;\n            }\n        }\n\n        public override bool CanRead\n        {\n            get\n            {\n                return getter != null;\n            }\n        }\n\n        public override bool CanWrite\n        {\n            get\n            {\n                return setter != null;\n            }\n        }\n\n        public override Type PropertyType\n        {\n            get\n            {\n                if (getter != null)\n                    return getter.ReturnType.ReflectionType;\n                else\n                {\n                    return setter.Parameters[0].ReflectionType;\n                }\n            }\n        }\n\n        public override Type DeclaringType\n        {\n            get\n            {\n                return dType.ReflectionType;\n            }\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n\n            return customAttributes;\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            List<object> res = new List<object>();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    res.Add(customAttributes[i]);\n            }\n            return res.ToArray();\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    return true;\n            }\n            return false;\n        }\n\n        public override MethodInfo[] GetAccessors(bool nonPublic)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override MethodInfo GetGetMethod(bool nonPublic)\n        {\n            if (getter != null)\n                return getter.ReflectionMethodInfo;\n            return null;\n        }\n\n        public override ParameterInfo[] GetIndexParameters()\n        {\n            throw new NotImplementedException();\n        }\n\n        public override MethodInfo GetSetMethod(bool nonPublic)\n        {\n            if (setter != null)\n                return setter.ReflectionMethodInfo;\n            return null;\n        }\n\n        public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)\n        {\n            return appdomain.Invoke(getter, obj, null);\n        }\n\n        public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)\n        {\n            param[0] = value;\n            appdomain.Invoke(setter, obj, param);\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Reflection/ILRuntimeType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeType : Type\n    {\n        ILType type;\n        Runtime.Enviorment.AppDomain appdomain;\n        object[] customAttributes;\n        Type[] attributeTypes;\n        ILRuntimeFieldInfo[] fields;\n        ILRuntimePropertyInfo[] properties;\n        ILRuntimeMethodInfo[] methods;\n\n        public ILType ILType { get { return type; } }\n        \n        public ILRuntimeType(ILType t)\n        {\n            type = t;\n            appdomain = t.AppDomain;\n        }\n\n        void InitializeCustomAttribute()\n        {\n            customAttributes = new object[type.TypeDefinition.CustomAttributes.Count];\n            attributeTypes = new Type[customAttributes.Length];\n            for (int i = 0; i < type.TypeDefinition.CustomAttributes.Count; i++)\n            {\n                var attribute = type.TypeDefinition.CustomAttributes[i];\n                var at = appdomain.GetType(attribute.AttributeType, type, null);\n                try\n                {\n                    object ins = attribute.CreateInstance(at, appdomain);\n\n                    attributeTypes[i] = at.ReflectionType is ILRuntimeWrapperType ? at.TypeForCLR : at.ReflectionType;\n                    customAttributes[i] = ins;\n                }\n                catch\n                {\n                    attributeTypes[i] = typeof(Attribute);\n                }               \n            }\n\n        }\n\n        void InitializeProperties()\n        {\n            int cnt = type.TypeDefinition.HasProperties ? type.TypeDefinition.Properties.Count : 0;\n            properties = new ILRuntimePropertyInfo[cnt];\n            for (int i = 0; i < cnt; i++)\n            {\n                Mono.Cecil.PropertyDefinition pd = type.TypeDefinition.Properties[i];\n                ILRuntimePropertyInfo pi = new ILRuntimePropertyInfo(pd, type);\n                properties[i] = pi;\n                if (pd.GetMethod != null)\n                    pi.Getter = type.GetMethod(pd.GetMethod.Name, 0) as ILMethod;\n                if (pd.SetMethod != null)\n                    pi.Setter = type.GetMethod(pd.SetMethod.Name, 1) as ILMethod;\n            }\n        }\n\n        void InitializeMethods()\n        {\n            var methods = type.GetMethods();\n            this.methods = new ILRuntimeMethodInfo[methods.Count];\n            for(int i = 0; i < methods.Count; i++)\n            {\n                this.methods[i] = (ILRuntimeMethodInfo)((ILMethod)methods[i]).ReflectionMethodInfo;\n            }\n        }\n\n        void InitializeFields()\n        {\n            int staticCnt = type.StaticFieldTypes != null ? type.StaticFieldTypes.Length : 0;\n            fields = new ILRuntimeFieldInfo[type.TotalFieldCount + staticCnt];\n            for (int i = 0; i < type.TotalFieldCount; i++)\n            {\n                Mono.Cecil.FieldDefinition fd;\n                var t = type.GetField(i, out fd);\n                fields[i] = new ILRuntimeFieldInfo(fd, this, i, t);\n            }\n            for (int i = type.TotalFieldCount; i < type.TotalFieldCount + staticCnt; i++)\n            {\n                fields[i] = new ILRuntimeFieldInfo(type.StaticFieldDefinitions[i - type.TotalFieldCount], this, true, i - type.TotalFieldCount);\n            }\n        }\n\n        public override Assembly Assembly\n        {\n            get\n            {\n                return typeof(ILRuntimeType).Assembly;\n            }\n        }\n\n        public override string AssemblyQualifiedName\n        {\n            get\n            {\n                return type.FullName;\n            }\n        }\n\n        public override Type BaseType\n        {\n            get\n            {\n                return type.BaseType != null ? type.BaseType.ReflectionType : null;\n            }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                return type.FullName;\n            }\n        }\n\n        public override Guid GUID\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override Module Module\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return type.Name;\n            }\n        }\n\n        public override string Namespace\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override Type UnderlyingSystemType\n        {\n            get\n            {\n                return typeof(ILTypeInstance);\n            }\n        }\n\n        public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)\n        {\n            var ctors = type.GetConstructors();\n            ConstructorInfo[] res = new ConstructorInfo[ctors.Count];\n            for(int i = 0; i < res.Length; i++)\n            {\n                res[i] = ctors[i].ReflectionConstructorInfo;\n            }\n            return res;\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n\n            return customAttributes;\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            List<object> res = new List<object>();\n            for(int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    res.Add(customAttributes[i]);\n            }\n            return res.ToArray();\n        }\n\n        public override Type GetElementType()\n        {\n            if (type.IsArray)\n            {\n                return type.ElementType.ReflectionType;\n            }\n            else\n                throw new NotImplementedException();\n        }\n\n        public override EventInfo GetEvent(string name, BindingFlags bindingAttr)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override EventInfo[] GetEvents(BindingFlags bindingAttr)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override FieldInfo GetField(string name, BindingFlags bindingAttr)\n        {\n            if (fields == null)\n                InitializeFields();\n            foreach(var i in fields)\n            {\n                if (i.Name == name)\n                    return i;\n            }\n            return null;\n        }\n\n        public override FieldInfo[] GetFields(BindingFlags bindingAttr)\n        {\n            if (fields == null)\n                InitializeFields();\n            bool isPublic = (bindingAttr & BindingFlags.Public) == BindingFlags.Public;\n            bool isPrivate = (bindingAttr & BindingFlags.NonPublic) == BindingFlags.NonPublic;\n            bool isStatic = (bindingAttr & BindingFlags.Static) == BindingFlags.Static;\n            bool isInstance = (bindingAttr & BindingFlags.Instance) == BindingFlags.Instance;\n            List<FieldInfo> res = new List<FieldInfo>();\n            foreach(var i in fields)\n            {\n                if (isPublic != i.IsPublic && isPrivate != !i.IsPublic)\n                    continue;\n                if ((isStatic != i.IsStatic) && (isInstance != !i.IsStatic))\n                    continue;\n                res.Add(i);\n            }\n            return res.ToArray();\n        }\n\n        public override Type GetInterface(string name, bool ignoreCase)\n        {\n            if (type.FirstCLRInterface != null)\n            {\n                if (type.FirstCLRInterface.Name == name)\n                    return type.FirstCLRInterface.TypeForCLR;\n                else\n                    return null;\n            }\n            else\n                return null;\n        }\n\n        public override Type[] GetInterfaces()\n        {\n            if (type.FirstCLRInterface != null)\n                return new Type[] { type.FirstCLRInterface.TypeForCLR };\n            else\n                return new Type[0];\n        }\n\n        public override MemberInfo[] GetMembers(BindingFlags bindingAttr)\n        {\n            if (methods == null)\n                InitializeMethods();\n            if (fields == null)\n                InitializeFields();\n            if (properties == null)\n                InitializeProperties();\n            MemberInfo[] res = new MemberInfo[methods.Length + fields.Length + properties.Length];\n            for (int i = 0; i < methods.Length; i++)\n            {\n                res[i] = methods[i];\n            }\n            for (int i = methods.Length; i < methods.Length + fields.Length; i++)\n            {\n                res[i] = fields[i - methods.Length];\n            }\n            for (int i = methods.Length + fields.Length; i < res.Length; i++)\n            {\n                res[i] = properties[i- methods.Length - fields.Length];\n            }\n\n            return res;\n        }\n\n        public override MethodInfo[] GetMethods(BindingFlags bindingAttr)\n        {\n            if (methods == null)\n                InitializeMethods();\n            return methods;\n        }\n\n        public override Type GetNestedType(string name, BindingFlags bindingAttr)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override Type[] GetNestedTypes(BindingFlags bindingAttr)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)\n        {\n            if (properties == null)\n                InitializeProperties();\n            bool isPublic = (bindingAttr & BindingFlags.Public) == BindingFlags.Public;\n            bool isPrivate = (bindingAttr & BindingFlags.NonPublic) == BindingFlags.NonPublic;\n            bool isStatic = (bindingAttr & BindingFlags.Static) == BindingFlags.Static;\n            bool isInstance = (bindingAttr & BindingFlags.Instance) == BindingFlags.Instance;\n            List<PropertyInfo> res = new List<PropertyInfo>();\n            foreach (var i in properties)\n            {\n                if (isPublic != i.IsPublic && isPrivate != !i.IsPublic)\n                    continue;\n                if ((isStatic != i.IsStatic) && (isInstance != !i.IsStatic))\n                    continue;\n                res.Add(i);\n            }\n            return res.ToArray();\n        }\n\n        public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    return true;\n            }\n            return false;\n        }\n\n        protected override TypeAttributes GetAttributeFlagsImpl()\n        {\n            TypeAttributes res = TypeAttributes.Public;\n            if (type.TypeDefinition.IsAbstract)\n                res |= TypeAttributes.Abstract;\n            if (!type.IsValueType)\n                res |= TypeAttributes.Class;\n            if (type.TypeDefinition.IsSealed)\n                res |= TypeAttributes.Sealed;\n            return res;\n        }\n\n        protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)\n        {\n            List<IType> param = new List<IType>();\n            for (int i = 0; i < types.Length; i++)\n            {\n                if (types[i] is ILRuntimeType)\n                    param.Add(((ILRuntimeType)types[i]).type);\n                else\n                {\n                    var t = appdomain.GetType(types[i]);\n                    if (t == null)\n                        t = appdomain.GetType(types[i].AssemblyQualifiedName);\n                    if (t == null)\n                        throw new TypeLoadException();\n                    param.Add(t);\n                }\n            }\n\n            var res = type.GetConstructor(param);\n\n            if (res != null)\n                return ((ILMethod)res).ReflectionConstructorInfo;\n            else\n                return null;\n        }\n\n        protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)\n        {\n            IMethod res;\n            if (types == null)\n                res = type.GetMethod(name);\n            else\n            {\n                List<IType> param = new List<IType>();\n                for (int i = 0; i < types.Length; i++)\n                {\n                    if (types[i] is ILRuntimeType)\n                        param.Add(((ILRuntimeType)types[i]).type);\n                    else\n                    {\n                        var t = appdomain.GetType(types[i]);\n                        if (t == null)\n                            t = appdomain.GetType(types[i].AssemblyQualifiedName);\n                        if (t == null)\n                            throw new TypeLoadException();\n                        param.Add(t);\n                    }\n                }\n                bool declearedOnly = (bindingAttr & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly;\n                res = type.GetMethod(name, param, null, null, declearedOnly);\n            }\n            if (res != null)\n                return ((ILMethod)res).ReflectionMethodInfo;\n            else\n                return null;\n        }\n\n        protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)\n        {\n            if (properties == null)\n                InitializeProperties();\n\n            foreach(var i in properties)\n            {\n                if (i.Name == name)\n                    return i;\n            }\n            return null;\n        }\n\n        protected override bool HasElementTypeImpl()\n        {\n            return false;\n        }\n\n        protected override bool IsArrayImpl()\n        {\n            return type.IsArray;\n        }\n\n        protected override bool IsByRefImpl()\n        {\n            return false;\n        }\n\n        protected override bool IsCOMObjectImpl()\n        {\n            return false;\n        }\n\n        protected override bool IsPointerImpl()\n        {\n            return false;\n        }\n\n        protected override bool IsPrimitiveImpl()\n        {\n            return false;\n        }\n        public override int GetHashCode()\n        {\n            return type.GetHashCode();\n        }\n        public override bool Equals(object o)\n        {\n            return o is ILRuntimeType ? ((ILRuntimeType)o).type == type : false;\n        }\n        public override bool IsGenericType\n        {\n            get\n            {\n                return type.HasGenericParameter;\n            }\n        }\n\n        public override bool IsGenericTypeDefinition\n        {\n            get\n            {\n                return type.HasGenericParameter;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Reflection/ILRuntimeWrapperType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeWrapperType : Type\n    {\n        CLRType type;\n        Type et;\n\n        public CLRType CLRType { get { return type; } }\n\n        public Type RealType { get { return et; } }\n\n        public override Guid GUID\n        {\n            get\n            {\n                return et.GUID;\n            }\n        }\n\n        public override Module Module\n        {\n            get\n            {\n                return et.Module;\n            }\n        }\n\n        public override Assembly Assembly\n        {\n            get\n            {\n                return et.Assembly;\n            }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                return et.FullName;\n            }\n        }\n\n        public override string Namespace\n        {\n            get\n            {\n                return et.Namespace;\n            }\n        }\n\n        public override string AssemblyQualifiedName\n        {\n            get\n            {\n                return et.AssemblyQualifiedName;\n            }\n        }\n\n        public override Type BaseType\n        {\n            get\n            {\n                return et.BaseType;\n            }\n        }\n\n        public override Type UnderlyingSystemType\n        {\n            get\n            {\n                return et.UnderlyingSystemType;\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return et.Name;\n            }\n        }\n\n        public ILRuntimeWrapperType(CLRType t)\n        {\n            type = t;\n            et = t.TypeForCLR;\n        }\n\n        public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)\n        {\n            return et.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);\n        }\n\n        protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)\n        {\n            return et.GetConstructor(bindingAttr, binder, callConvention, types, modifiers);\n        }\n\n        public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)\n        {\n            return et.GetConstructors(bindingAttr);\n        }\n\n        protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)\n        {\n            return et.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);\n        }\n\n        public override MethodInfo[] GetMethods(BindingFlags bindingAttr)\n        {\n            return et.GetMethods(bindingAttr);\n        }\n\n        public override FieldInfo GetField(string name, BindingFlags bindingAttr)\n        {\n            return et.GetField(name, bindingAttr);\n        }\n\n        public override FieldInfo[] GetFields(BindingFlags bindingAttr)\n        {\n            return et.GetFields(bindingAttr);\n        }\n\n        public override Type GetInterface(string name, bool ignoreCase)\n        {\n            return et.GetInterface(name, ignoreCase);\n        }\n\n        public override Type[] GetInterfaces()\n        {\n            return et.GetInterfaces();\n        }\n\n        public override EventInfo GetEvent(string name, BindingFlags bindingAttr)\n        {\n            return et.GetEvent(name, bindingAttr);\n        }\n\n        public override EventInfo[] GetEvents(BindingFlags bindingAttr)\n        {\n            return et.GetEvents(bindingAttr);\n        }\n\n        protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)\n        {\n            return et.GetProperty(name, bindingAttr, binder, returnType, types, modifiers);\n        }\n\n        public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)\n        {\n            return et.GetProperties(bindingAttr);\n        }\n\n        public override Type[] GetNestedTypes(BindingFlags bindingAttr)\n        {\n            return et.GetNestedTypes(bindingAttr);\n        }\n\n        public override int GetHashCode()\n        {\n            return type.GetHashCode();\n        }\n\n        public override Type GetNestedType(string name, BindingFlags bindingAttr)\n        {\n            return et.GetNestedType(name, bindingAttr);\n        }\n\n        public override MemberInfo[] GetMembers(BindingFlags bindingAttr)\n        {\n            return et.GetMembers(bindingAttr);\n        }\n\n        protected override TypeAttributes GetAttributeFlagsImpl()\n        {\n            return et.Attributes;\n        }\n\n        protected override bool IsArrayImpl()\n        {\n            return et.IsArray;\n        }\n\n        protected override bool IsByRefImpl()\n        {\n            return et.IsByRef;\n        }\n\n        protected override bool IsPointerImpl()\n        {\n            return et.IsPointer;\n        }\n\n        protected override bool IsPrimitiveImpl()\n        {\n            return et.IsPrimitive;\n        }\n\n        protected override bool IsCOMObjectImpl()\n        {\n            return et.IsCOMObject;\n        }\n\n        public override Type GetElementType()\n        {\n            return et.GetElementType();\n        }\n\n        protected override bool HasElementTypeImpl()\n        {\n            return et.HasElementType;\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            return et.GetCustomAttributes(inherit);\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            return et.GetCustomAttributes(attributeType, inherit);\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            return et.IsDefined(attributeType, inherit);\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Adaptors/CLRCrossBindingAdaptors.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Runtime.Adaptors\n{\n    class AttributeAdaptor : CrossBindingAdaptor\n    {\n        public override Type AdaptorType\n        {\n            get\n            {\n                return typeof(Adaptor);\n            }\n        }\n\n        public override Type BaseCLRType\n        {\n            get\n            {\n                return typeof(Attribute);\n            }\n        }\n\n        public override object CreateCLRInstance(Enviorment.AppDomain appdomain, ILTypeInstance instance)\n        {\n            return new Adaptor(appdomain, instance);\n        }\n\n        class Adaptor : Attribute, CrossBindingAdaptorType\n        {\n            ILTypeInstance instance;\n            ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n\n            bool isToStringGot;\n            IMethod toString;\n\n            public Adaptor(ILRuntime.Runtime.Enviorment.AppDomain appdomain, ILTypeInstance instance)\n            {\n                this.appdomain = appdomain;\n                this.instance = instance;\n            }\n            public ILTypeInstance ILInstance\n            {\n                get\n                {\n                    return instance;\n                }\n            }\n\n            public override string ToString()\n            {\n                if (!isToStringGot)\n                {\n                    isToStringGot = true;\n                    IMethod m = appdomain.ObjectType.GetMethod(\"ToString\", 0);\n                    toString = instance.Type.GetVirtualMethod(m);\n                }\n                if (toString == null || toString is ILMethod)\n                {\n                    return instance.ToString();\n                }\n                else\n                    return instance.Type.FullName;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/CLRBinding/BindingCodeGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Other;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    public class BindingCodeGenerator\n    {\n        public static void GenerateBindingCode(List<Type> types, string outputPath, HashSet<MethodBase> excludeMethods = null, HashSet<FieldInfo> excludeFields = null)\n        {\n            if (!System.IO.Directory.Exists(outputPath))\n                System.IO.Directory.CreateDirectory(outputPath);\n            string[] oldFiles = System.IO.Directory.GetFiles(outputPath, \"*.cs\");\n            foreach (var i in oldFiles)\n            {\n                System.IO.File.Delete(i);\n            }\n            List<string> clsNames = new List<string>();\n            foreach (var i in types)\n            {\n                string clsName, realClsName;\n                bool isByRef;\n                if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)\n                    continue;\n                i.GetClassName(out clsName, out realClsName, out isByRef);\n                clsNames.Add(clsName);\n                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + \"/\" + clsName + \".cs\", false, Encoding.UTF8))\n                {\n                    sw.Write(@\"using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Reflection;\nusing ILRuntime.CLR.Utils;\n\nnamespace ILRuntime.Runtime.Generated\n{\n    unsafe class \");\n                    sw.WriteLine(clsName);\n                    sw.Write(@\"    {\n        public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)\n        {\n            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;\n            MethodBase method;\n            FieldInfo field;\n            Type[] args;\n            Type type = typeof(\");\n                    sw.Write(realClsName);\n                    sw.WriteLine(\");\");\n                    MethodInfo[] methods = i.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);\n                    FieldInfo[] fields = i.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);\n                    string registerMethodCode = i.GenerateMethodRegisterCode(methods, excludeMethods);\n                    string registerFieldCode = i.GenerateFieldRegisterCode(fields, excludeFields);\n                    string registerValueTypeCode = i.GenerateValueTypeRegisterCode(realClsName);\n                    string registerMiscCode = i.GenerateMiscRegisterCode(realClsName, true, true);\n                    string commonCode = i.GenerateCommonCode(realClsName);\n                    ConstructorInfo[] ctors = i.GetConstructors(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);\n                    string ctorRegisterCode = i.GenerateConstructorRegisterCode(ctors, excludeMethods);\n                    string methodWraperCode = i.GenerateMethodWraperCode(methods, realClsName, excludeMethods);\n                    string fieldWraperCode = i.GenerateFieldWraperCode(fields, realClsName, excludeFields);\n                    string cloneWraperCode = i.GenerateCloneWraperCode(fields, realClsName);\n                    string ctorWraperCode = i.GenerateConstructorWraperCode(ctors, realClsName, excludeMethods);\n                    sw.WriteLine(registerMethodCode);\n                    sw.WriteLine(registerFieldCode);\n                    sw.WriteLine(registerValueTypeCode);\n                    sw.WriteLine(registerMiscCode);\n                    sw.WriteLine(ctorRegisterCode);\n                    sw.WriteLine(\"        }\");\n                    sw.WriteLine();\n                    sw.WriteLine(commonCode);\n                    sw.WriteLine(methodWraperCode);\n                    sw.WriteLine(fieldWraperCode);\n                    sw.WriteLine(cloneWraperCode);\n                    sw.WriteLine(ctorWraperCode);\n                    sw.WriteLine(\"    }\");\n                    sw.WriteLine(\"}\");\n                    sw.Flush();\n                }\n            }\n\n            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + \"/CLRBindings.cs\", false, Encoding.UTF8))\n            {\n                sw.WriteLine(@\"using System;\nusing System.Collections.Generic;\nusing System.Reflection;\n\nnamespace ILRuntime.Runtime.Generated\n{\n    class CLRBindings\n    {\n        /// <summary>\n        /// Initialize the CLR binding, please invoke this AFTER CLR Redirection registration\n        /// </summary>\n        public static void Initialize(ILRuntime.Runtime.Enviorment.AppDomain app)\n        {\");\n                foreach (var i in clsNames)\n                {\n                    sw.Write(\"            \");\n                    sw.Write(i);\n                    sw.WriteLine(\".Register(app);\");\n                }\n\n                sw.WriteLine(@\"        }\n    }\n}\");\n            }\n        }\n\n        class CLRBindingGenerateInfo\n        {\n            public Type Type { get; set; }\n            public HashSet<MethodInfo> Methods { get; set; }\n            public HashSet<FieldInfo> Fields { get; set; }\n            public HashSet<ConstructorInfo> Constructors { get; set; }\n            public bool ArrayNeeded { get; set; }\n            public bool DefaultInstanceNeeded { get; set; }\n            public bool ValueTypeNeeded { get; set; }\n\n            public bool NeedGenerate\n            {\n                get\n                {\n                    if (Methods.Count == 0 && Constructors.Count == 0 && Fields.Count == 0 && !ArrayNeeded && !DefaultInstanceNeeded && !ValueTypeNeeded)\n                        return false;\n                    else\n                    {\n                        //Making CLRBinding for such types makes no sense\n                        if (Type == typeof(Delegate) || Type == typeof(System.Runtime.CompilerServices.RuntimeHelpers))\n                            return false;\n                        return true;\n                    }\n                }\n            }\n        }\n\n        public static void GenerateBindingCode(ILRuntime.Runtime.Enviorment.AppDomain domain, string outputPath)\n        {\n            if (domain == null)\n                return;\n            if (!System.IO.Directory.Exists(outputPath))\n                System.IO.Directory.CreateDirectory(outputPath);\n            Dictionary<Type, CLRBindingGenerateInfo> infos = new Dictionary<Type, CLRBindingGenerateInfo>(new ByReferenceKeyComparer<Type>());\n            CrawlAppdomain(domain, infos);\n            string[] oldFiles = System.IO.Directory.GetFiles(outputPath, \"*.cs\");\n            foreach (var i in oldFiles)\n            {\n                System.IO.File.Delete(i);\n            }\n\n            HashSet<MethodBase> excludeMethods = null;\n            HashSet<FieldInfo> excludeFields = null;\n            List<string> clsNames = new List<string>();\n            foreach (var info in infos)\n            {\n                if (!info.Value.NeedGenerate)\n                    continue;\n                Type i = info.Value.Type;\n                string clsName, realClsName;\n                bool isByRef;\n                if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)\n                    continue;\n                i.GetClassName(out clsName, out realClsName, out isByRef);\n                clsNames.Add(clsName);\n                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + \"/\" + clsName + \".cs\", false, Encoding.UTF8))\n                {\n                    sw.Write(@\"using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Reflection;\nusing ILRuntime.CLR.Utils;\n\nnamespace ILRuntime.Runtime.Generated\n{\n    unsafe class \");\n                    sw.WriteLine(clsName);\n                    sw.Write(@\"    {\n        public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)\n        {\n            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;\n            MethodBase method;\n            FieldInfo field;\n            Type[] args;\n            Type type = typeof(\");\n                    sw.Write(realClsName);\n                    sw.WriteLine(\");\");\n                    MethodInfo[] methods = info.Value.Methods.ToArray();\n                    FieldInfo[] fields = info.Value.Fields.ToArray();\n                    string registerMethodCode = i.GenerateMethodRegisterCode(methods, excludeMethods);\n                    string registerFieldCode = fields.Length > 0 ? i.GenerateFieldRegisterCode(fields, excludeFields) : null;\n                    string registerValueTypeCode = info.Value.ValueTypeNeeded ? i.GenerateValueTypeRegisterCode(realClsName) : null;\n                    string registerMiscCode = i.GenerateMiscRegisterCode(realClsName, info.Value.DefaultInstanceNeeded, info.Value.ArrayNeeded);\n                    string commonCode = i.GenerateCommonCode(realClsName);\n                    ConstructorInfo[] ctors = info.Value.Constructors.ToArray();\n                    string ctorRegisterCode = i.GenerateConstructorRegisterCode(ctors, excludeMethods);\n                    string methodWraperCode = i.GenerateMethodWraperCode(methods, realClsName, excludeMethods);\n                    string fieldWraperCode = fields.Length > 0 ? i.GenerateFieldWraperCode(fields, realClsName, excludeFields) : null;\n                    string cloneWraperCode = null;\n                    if (info.Value.ValueTypeNeeded)\n                    {\n                        //Memberwise clone should copy all fields\n                        var fs = i.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);\n                        cloneWraperCode = i.GenerateCloneWraperCode(fs, realClsName);\n                    }\n                    string ctorWraperCode = i.GenerateConstructorWraperCode(ctors, realClsName, excludeMethods);\n                    sw.WriteLine(registerMethodCode);\n                    if (fields.Length > 0)\n                        sw.WriteLine(registerFieldCode);\n                    if (info.Value.ValueTypeNeeded)\n                        sw.WriteLine(registerValueTypeCode);\n                    if (!string.IsNullOrEmpty(registerMiscCode))\n                        sw.WriteLine(registerMiscCode);\n                    sw.WriteLine(ctorRegisterCode);\n                    sw.WriteLine(\"        }\");\n                    sw.WriteLine();\n                    sw.WriteLine(commonCode);\n                    sw.WriteLine(methodWraperCode);\n                    if (fields.Length > 0)\n                        sw.WriteLine(fieldWraperCode);\n                    if (info.Value.ValueTypeNeeded)\n                        sw.WriteLine(cloneWraperCode);\n                    sw.WriteLine(ctorWraperCode);\n                    sw.WriteLine(\"    }\");\n                    sw.WriteLine(\"}\");\n                    sw.Flush();\n                }\n            }\n\n            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + \"/CLRBindings.cs\", false, Encoding.UTF8))\n            {\n                sw.WriteLine(@\"using System;\nusing System.Collections.Generic;\nusing System.Reflection;\n\nnamespace ILRuntime.Runtime.Generated\n{\n    class CLRBindings\n    {\n        /// <summary>\n        /// Initialize the CLR binding, please invoke this AFTER CLR Redirection registration\n        /// </summary>\n        public static void Initialize(ILRuntime.Runtime.Enviorment.AppDomain app)\n        {\");\n                foreach (var i in clsNames)\n                {\n                    sw.Write(\"            \");\n                    sw.Write(i);\n                    sw.WriteLine(\".Register(app);\");\n                }\n\n                sw.WriteLine(@\"        }\n    }\n}\");\n            }\n        }\n\n        static void CrawlAppdomain(ILRuntime.Runtime.Enviorment.AppDomain domain, Dictionary<Type, CLRBindingGenerateInfo> infos)\n        {\n            var arr = domain.LoadedTypes.Values.ToArray();\n            //Prewarm\n            foreach (var type in arr)\n            {\n                if (type is CLR.TypeSystem.ILType)\n                {\n                    if (type.HasGenericParameter)\n                        continue;\n                    var methods = type.GetMethods().ToList();\n                    foreach (var i in ((CLR.TypeSystem.ILType)type).GetConstructors())\n                        methods.Add(i);\n                    if (((CLR.TypeSystem.ILType)type).GetStaticConstroctor() != null)\n                        methods.Add(((CLR.TypeSystem.ILType)type).GetStaticConstroctor());\n                    foreach (var j in methods)\n                    {\n                        CLR.Method.ILMethod method = j as CLR.Method.ILMethod;\n                        if (method != null)\n                        {\n                            if (method.GenericParameterCount > 0 && !method.IsGenericInstance)\n                                continue;\n                            var body = method.Body;\n                        }\n                    }\n                }\n            }\n            arr = domain.LoadedTypes.Values.ToArray();\n            foreach (var type in arr)\n            {\n                if (type is CLR.TypeSystem.ILType)\n                {\n                    if (type.HasGenericParameter)\n                        continue;\n                    var methods = type.GetMethods().ToList();\n                    foreach (var i in ((CLR.TypeSystem.ILType)type).GetConstructors())\n                        methods.Add(i);\n\n                    foreach (var j in methods)\n                    {\n                        CLR.Method.ILMethod method = j as CLR.Method.ILMethod;\n                        if (method != null)\n                        {\n                            if (method.GenericParameterCount > 0 && !method.IsGenericInstance)\n                                continue;\n                            var body = method.Body;\n                            foreach (var ins in body)\n                            {\n                                switch (ins.Code)\n                                {\n                                    case Intepreter.OpCodes.OpCodeEnum.Newobj:\n                                        {\n                                            CLR.Method.CLRMethod m = domain.GetMethod(ins.TokenInteger) as CLR.Method.CLRMethod;\n                                            if (m != null)\n                                            {\n                                                if (m.DeclearingType.IsDelegate)\n                                                    continue;\n                                                Type t = m.DeclearingType.TypeForCLR;\n                                                CLRBindingGenerateInfo info;\n                                                if (!infos.TryGetValue(t, out info))\n                                                {\n                                                    info = CreateNewBindingInfo(t);\n                                                    infos[t] = info;\n                                                }\n                                                if (m.IsConstructor)\n                                                    info.Constructors.Add(m.ConstructorInfo);\n                                                else\n                                                    info.Methods.Add(m.MethodInfo);\n                                            }\n                                        }\n                                        break;\n                                    case Intepreter.OpCodes.OpCodeEnum.Ldfld:\n                                    case Intepreter.OpCodes.OpCodeEnum.Stfld:\n                                    case Intepreter.OpCodes.OpCodeEnum.Ldflda:\n                                    case Intepreter.OpCodes.OpCodeEnum.Ldsfld:\n                                    case Intepreter.OpCodes.OpCodeEnum.Ldsflda:\n                                    case Intepreter.OpCodes.OpCodeEnum.Stsfld:\n                                        {\n                                            var t = domain.GetType((int)(ins.TokenLong >> 32)) as CLR.TypeSystem.CLRType;\n                                            if(t != null)\n                                            {\n                                                var fi = t.GetField((int)ins.TokenLong);\n                                                if (fi != null && fi.IsPublic)\n                                                {\n                                                    CLRBindingGenerateInfo info;\n                                                    if (!infos.TryGetValue(t.TypeForCLR, out info))\n                                                    {\n                                                        info = CreateNewBindingInfo(t.TypeForCLR);\n                                                        infos[t.TypeForCLR] = info;\n                                                    }\n                                                    if(ins.Code == Intepreter.OpCodes.OpCodeEnum.Stfld || ins.Code == Intepreter.OpCodes.OpCodeEnum.Stsfld)\n                                                    {\n                                                        if (t.IsValueType)\n                                                        {\n                                                            info.ValueTypeNeeded = true;\n                                                            info.DefaultInstanceNeeded = true;\n                                                        }\n                                                    }\n                                                    if (t.TypeForCLR.CheckCanPinn() || !t.IsValueType)\n                                                        info.Fields.Add(fi);\n                                                }\n                                            }\n                                        }\n                                        break;\n                                    case Intepreter.OpCodes.OpCodeEnum.Ldtoken:\n                                        {\n                                            if (ins.TokenInteger == 0)\n                                            {\n                                                var t = domain.GetType((int)(ins.TokenLong >> 32)) as CLR.TypeSystem.CLRType;\n                                                if (t != null)\n                                                {\n                                                    var fi = t.GetField((int)ins.TokenLong);\n                                                    if (fi != null)\n                                                    {\n                                                        CLRBindingGenerateInfo info;\n                                                        if (!infos.TryGetValue(t.TypeForCLR, out info))\n                                                        {\n                                                            info = CreateNewBindingInfo(t.TypeForCLR);\n                                                            infos[t.TypeForCLR] = info;\n                                                        }\n                                                        info.Fields.Add(fi);\n                                                    }\n                                                }\n                                            }\n                                        }\n                                        break;\n                                    case Intepreter.OpCodes.OpCodeEnum.Newarr:\n                                        {\n                                            var t = domain.GetType(ins.TokenInteger) as CLR.TypeSystem.CLRType;\n                                            if(t != null)\n                                            {\n                                                CLRBindingGenerateInfo info;\n                                                if (!infos.TryGetValue(t.TypeForCLR, out info))\n                                                {\n                                                    info = CreateNewBindingInfo(t.TypeForCLR);\n                                                    infos[t.TypeForCLR] = info;\n                                                }\n                                                info.ArrayNeeded = true;\n                                            }\n                                        }\n                                        break;\n                                    case Intepreter.OpCodes.OpCodeEnum.Call:\n                                    case Intepreter.OpCodes.OpCodeEnum.Callvirt:\n                                        {\n                                            CLR.Method.CLRMethod m = domain.GetMethod(ins.TokenInteger) as CLR.Method.CLRMethod;\n                                            if (m != null)\n                                            {\n                                                //Cannot explicit call base class's constructor directly\n                                                if (m.IsConstructor)\n                                                    continue;\n                                                if (!m.MethodInfo.IsPublic)\n                                                    continue;\n                                                Type t = m.DeclearingType.TypeForCLR;\n                                                CLRBindingGenerateInfo info;\n                                                if (!infos.TryGetValue(t, out info))\n                                                {\n                                                    info = CreateNewBindingInfo(t);\n                                                    infos[t] = info;\n                                                }\n\n                                                info.Methods.Add(m.MethodInfo);\n                                            }\n                                        }\n                                        break;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        static CLRBindingGenerateInfo CreateNewBindingInfo(Type t)\n        {\n            CLRBindingGenerateInfo info = new CLRBindingGenerateInfo();\n            info.Type = t;\n            info.Methods = new HashSet<MethodInfo>();\n            info.Fields = new HashSet<FieldInfo>();\n            info.Constructors = new HashSet<ConstructorInfo>();\n\n            return info;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/CLRBinding/BindingGeneratorExtensions.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class BindingGeneratorExtensions\n    {\n        internal static bool ShouldSkipField(this Type type, FieldInfo i)\n        {\n            if (i.IsPrivate)\n                return true;\n            //EventHandler is currently not supported\n            if (i.IsSpecialName)\n            {\n                return true;\n            }\n            if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)\n                return true;\n            return false;\n        }\n\n        internal static bool ShouldSkipMethod(this Type type, MethodBase i)\n        {\n            if (i.IsPrivate)\n                return true;\n            if (i.IsGenericMethod)\n                return true;\n            //EventHandler is currently not supported\n            var param = i.GetParameters();\n            if (i.IsSpecialName)\n            {\n                string[] t = i.Name.Split('_');\n                if (t[0] == \"add\" || t[0] == \"remove\")\n                    return true;\n                if (t[0] == \"get\" || t[0] == \"set\")\n                {\n                    Type[] ts;\n                    if (t[1] == \"Item\")\n                    {\n                        var cnt = t[0] == \"set\" ? param.Length - 1 : param.Length;\n                        ts = new Type[cnt];\n                        for (int j = 0; j < cnt; j++)\n                        {\n                            ts[j] = param[j].ParameterType;\n                        }\n                    }\n                    else\n                        ts = new Type[0];\n                    var prop = type.GetProperty(t[1], ts);\n                    if (prop == null)\n                    {\n                        return true;\n                    }\n                    if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)\n                        return true;\n                }\n            }\n            if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)\n                return true;\n            foreach (var j in param)\n            {\n                if (j.ParameterType.IsPointer)\n                    return true;\n            }\n            return false;\n        }\n\n        internal static void AppendParameters(this ParameterInfo[] param, StringBuilder sb)\n        {\n            bool first = true;\n            foreach (var j in param)\n            {\n                if (first)\n                    first = false;\n                else\n                    sb.Append(\", \");\n                if (j.IsOut && j.ParameterType.IsByRef)\n                    sb.Append(\"out \");\n                else if (j.ParameterType.IsByRef)\n                    sb.Append(\"ref \");\n                sb.Append(j.Name);\n            }\n        }\n\n        internal static string GetRetrieveValueCode(this Type type, string realClsName)\n        {\n            if (type.IsByRef)\n                type = type.GetElementType();\n            if (type.IsPrimitive)\n            {\n                if (type == typeof(int))\n                {\n                    return \"ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(long))\n                {\n                    return \"*(long*)&ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(short))\n                {\n                    return \"(short)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(bool))\n                {\n                    return \"ptr_of_this_method->Value == 1\";\n                }\n                else if (type == typeof(ushort))\n                {\n                    return \"(ushort)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(float))\n                {\n                    return \"*(float*)&ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(double))\n                {\n                    return \"*(double*)&ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(byte))\n                {\n                    return \"(byte)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(sbyte))\n                {\n                    return \"(sbyte)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(uint))\n                {\n                    return \"(uint)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(char))\n                {\n                    return \"(char)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(ulong))\n                {\n                    return \"*(ulong*)&ptr_of_this_method->Value\";\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                return string.Format(\"({0})typeof({0}).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack))\", realClsName);\n            }\n        }\n\n        internal static void GetRefWriteBackValueCode(this Type type, StringBuilder sb, string paramName)\n        {\n            if (type.IsPrimitive)\n            {\n                if (type == typeof(int))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(long))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Long;\");\n                    sb.Append(\"                        *(long*)&___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(short))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(bool))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName + \" ? 1 : 0;\");\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(ushort))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(float))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Float;\");\n                    sb.Append(\"                        *(float*)&___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(double))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Double;\");\n                    sb.Append(\"                        *(double*)&___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(byte))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(sbyte))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(uint))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = (int)\" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(char))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = (int)\" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(ulong))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Long;\");\n                    sb.Append(\"                        *(ulong*)&___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                if (!type.IsValueType)\n                {\n                    sb.Append(@\"                        object ___obj = \");\n                    sb.Append(paramName);\n                    sb.AppendLine(\";\");\n\n                    sb.AppendLine(@\"                        if (___obj is CrossBindingAdaptorType)\n                            ___obj = ((CrossBindingAdaptorType)___obj).ILInstance;\n                        __mStack[___dst->Value] = ___obj; \");\n                }\n                else\n                {\n                    sb.Append(\"                        __mStack[___dst->Value] = \");\n                    sb.Append(paramName);\n                    sb.AppendLine(\";\");\n                }\n            }\n        }\n\n        internal static void GetReturnValueCode(this Type type, StringBuilder sb)\n        {\n            if (type.IsPrimitive)\n            {\n                if (type == typeof(int))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(long))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Long;\");\n                    sb.AppendLine(\"            *(long*)&__ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(short))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(bool))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method ? 1 : 0;\");\n                }\n                else if (type == typeof(ushort))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(float))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Float;\");\n                    sb.AppendLine(\"            *(float*)&__ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(double))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Double;\");\n                    sb.AppendLine(\"            *(double*)&__ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(byte))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(sbyte))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(uint))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = (int)result_of_this_method;\");\n                }\n                else if (type == typeof(char))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = (int)result_of_this_method;\");\n                }\n                else if (type == typeof(ulong))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Long;\");\n                    sb.AppendLine(\"            *(ulong*)&__ret->Value = result_of_this_method;\");\n                }\n                else\n                    throw new NotImplementedException();\n                sb.AppendLine(\"            return __ret + 1;\");\n\n            }\n            else\n            {\n                if (!type.IsSealed && type != typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance))\n                {\n                    sb.AppendLine(@\"            object obj_result_of_this_method = result_of_this_method;\n            if(obj_result_of_this_method is CrossBindingAdaptorType)\n            {    \n                return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance);\n            }\");\n                }\n                sb.AppendLine(\"            return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);\");\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/CLRBinding/CommonBindingGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class CommonBindingGenerator\n    {\n        internal static string GenerateMiscRegisterCode(this Type type, string typeClsName, bool defaultCtor, bool newArr)\n        {\n            StringBuilder sb = new StringBuilder();\n\n            if (defaultCtor && !type.IsPrimitive && !type.IsAbstract)\n            {\n                var constructorFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;\n                var hasDefaultConstructor = type.GetConstructor(constructorFlags, null, new Type[0], null) != null;\n\n                if (hasDefaultConstructor || type.IsValueType)\n                {\n                    sb.AppendLine(string.Format(\"            app.RegisterCLRCreateDefaultInstance(type, () => new {0}());\", typeClsName));\n                }\n            }\n\n            if (newArr)\n            {\n                if (!type.IsAbstract || !type.IsSealed)\n                {\n                    sb.AppendLine(string.Format(\"            app.RegisterCLRCreateArrayInstance(type, s => new {0}[s]);\", typeClsName));\n                }\n            }\n\n            return sb.ToString();\n        }\n        internal static string GenerateCommonCode(this Type type, string typeClsName)\n        {\n            if (!type.IsValueType)\n                return \"\";\n            StringBuilder sb = new StringBuilder();\n            if (type.IsPrimitive)\n            {\n                sb.AppendLine(string.Format(\"        static {0} GetInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack)\", typeClsName));\n                sb.AppendLine(\"        {\");\n                if (type.IsPrimitive || type.IsValueType)\n                    sb.AppendLine(\"            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);\");\n                sb.AppendLine(string.Format(\"            {0} instance_of_this_method;\", typeClsName));\n                sb.Append(@\"            switch(ptr_of_this_method->ObjectType)\n            {\n                case ObjectTypes.FieldReference:\n                    {\n                        var instance_of_fieldReference = __mStack[ptr_of_this_method->Value];\n                        if(instance_of_fieldReference is ILTypeInstance)\n                        {\n                            instance_of_this_method = (\");\n                sb.Append(typeClsName);\n                sb.Append(\")\");\n                if(type == typeof(bool))\n                {\n                    sb.Append(\"((int)\");\n                }\n                sb.Append(\"((ILTypeInstance)instance_of_fieldReference)[ptr_of_this_method->ValueLow]\");\n                if (type == typeof(bool))\n                {\n                    sb.Append(\" == 1);\");\n                }\n                else\n                    sb.Append(\";\");\n                sb.Append(@\"\n                        }\n                        else\n                        {\n                            var t = __domain.GetType(instance_of_fieldReference.GetType()) as CLRType;\n                            instance_of_this_method = (\");\n                sb.Append(typeClsName);\n                sb.Append(\")t.GetFieldValue(ptr_of_this_method->ValueLow, instance_of_fieldReference);\");\n                sb.Append(@\"\n                        }\n                    }\n                    break;\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = __domain.GetType(ptr_of_this_method->Value);\n                        if(t is ILType)\n                        {\n                            instance_of_this_method = (\");\n                sb.Append(typeClsName);\n                sb.Append(\")\");\n                if (type == typeof(bool))\n                {\n                    sb.Append(\"((int)\");\n                }\n                sb.Append(\"((ILType)t).StaticInstance[ptr_of_this_method->ValueLow]\");\n                if (type == typeof(bool))\n                {\n                    sb.Append(\" == 1);\");\n                }\n                else\n                    sb.Append(\";\");\n                sb.Append(@\"\n                        }\n                        else\n                        {\n                            instance_of_this_method = (\");\n                sb.Append(typeClsName);\n                sb.Append(@\")((CLRType)t).GetFieldValue(ptr_of_this_method->ValueLow, null);\n                        }\n                    }\n                    break;\n                case ObjectTypes.ArrayReference:\n                    {\n                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as \");\n                sb.Append(typeClsName);\n                sb.AppendLine(@\"[];\n                        instance_of_this_method = instance_of_arrayReference[ptr_of_this_method->ValueLow];                        \n                    }\n                    break;\n                default:\");\n                sb.AppendLine(string.Format(\"                    instance_of_this_method = {0};\", type.GetRetrieveValueCode(typeClsName)));\n                sb.AppendLine(@\"                    break;\n            }\n            return instance_of_this_method;\");\n                sb.AppendLine(\"        }\");\n            }\n            if (!type.IsPrimitive && !type.IsAbstract)\n            {\n                sb.AppendLine(string.Format(\"        static void WriteBackInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack, ref {0} instance_of_this_method)\", typeClsName));\n                sb.AppendLine(\"        {\");\n                sb.AppendLine(@\"            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);\n            switch(ptr_of_this_method->ObjectType)\n            {\n                case ObjectTypes.Object:\n                    {\n                        __mStack[ptr_of_this_method->Value] = instance_of_this_method;\");\n                sb.Append(@\"                    }\n                    break;\n                case ObjectTypes.FieldReference:\n                    {\n                        var ___obj = __mStack[ptr_of_this_method->Value];\n                        if(___obj is ILTypeInstance)\n                        {\n                            ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method\");\n                sb.Append(@\";\n                        }\n                        else\n                        {\n                            var t = __domain.GetType(___obj.GetType()) as CLRType;\n                            t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, instance_of_this_method\");\n                sb.Append(@\");\n                        }\n                    }\n                    break;\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = __domain.GetType(ptr_of_this_method->Value);\n                        if(t is ILType)\n                        {\n                            ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method\");\n                sb.Append(@\";\n                        }\n                        else\n                        {\n                            ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, instance_of_this_method\");\n                sb.Append(@\");\n                        }\n                    }\n                    break;\n                 case ObjectTypes.ArrayReference:\n                    {\n                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as \");\n                sb.Append(typeClsName);\n                sb.AppendLine(@\"[];\n                        instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method;\n                    }\n                    break;\n            }\");\n                sb.AppendLine(@\"        }\");\n            }\n            return sb.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/CLRBinding/ConstructorBindingGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class ConstructorBindingGenerator\n    {\n        internal static string GenerateConstructorRegisterCode(this Type type, ConstructorInfo[] methods, HashSet<MethodBase> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n            int idx = 0;\n            foreach (var i in methods)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipMethod(i))\n                    continue;\n                var param = i.GetParameters();\n                StringBuilder sb2 = new StringBuilder();\n                sb2.Append(\"{\");\n                bool first = true;\n                foreach (var j in param)\n                {\n                    if (first)\n                        first = false;\n                    else\n                        sb2.Append(\", \");\n                    sb2.Append(\"typeof(\");\n                    string tmp, clsName;\n                    bool isByRef;\n                    j.ParameterType.GetClassName(out tmp, out clsName, out isByRef);\n                    sb2.Append(clsName);\n                    sb2.Append(\")\");\n                    if (isByRef)\n                        sb2.Append(\".MakeByRefType()\");\n                }\n                sb2.Append(\"}\");\n                sb.AppendLine(string.Format(\"            args = new Type[]{0};\", sb2));\n                sb.AppendLine(\"            method = type.GetConstructor(flag, null, args, null);\");\n                sb.AppendLine(string.Format(\"            app.RegisterCLRMethodRedirection(method, Ctor_{0});\",idx));\n\n                idx++;\n            }\n            return sb.ToString();\n        }\n\n        internal static string GenerateConstructorWraperCode(this Type type, ConstructorInfo[] methods, string typeClsName, HashSet<MethodBase> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n\n            int idx = 0;\n            foreach (var i in methods)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipMethod(i) || i.IsStatic)\n                    continue;\n                var param = i.GetParameters();\n                int paramCnt = param.Length;\n                sb.AppendLine(string.Format(\"        static StackObject* Ctor_{0}(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\", idx));\n                sb.AppendLine(\"        {\");\n                sb.AppendLine(\"            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\");\n                sb.AppendLine(\"            StackObject* ptr_of_this_method;\");\n                sb.AppendLine(string.Format(\"            StackObject* __ret = ILIntepreter.Minus(__esp, {0});\", paramCnt));\n                for (int j = param.Length; j > 0; j--)\n                {\n                    var p = param[j - 1];\n                    sb.AppendLine(string.Format(\"            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});\", param.Length - j + 1));\n                    string tmp, clsName;\n                    bool isByRef;\n                    p.ParameterType.GetClassName(out tmp, out clsName, out isByRef);\n                    if (isByRef)\n                        sb.AppendLine(\"            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);\");\n                    sb.AppendLine(string.Format(\"            {0} {1} = {2};\", clsName, p.Name, p.ParameterType.GetRetrieveValueCode(clsName)));\n                    if (!isByRef && !p.ParameterType.IsPrimitive)\n                        sb.AppendLine(\"            __intp.Free(ptr_of_this_method);\");\n                }\n                sb.AppendLine();\n                sb.Append(\"            var result_of_this_method = \");\n                {\n                    string tmp, clsName;\n                    bool isByRef;\n                    type.GetClassName(out tmp, out clsName, out isByRef);\n                    sb.Append(string.Format(\"new {0}(\", clsName));\n                    param.AppendParameters(sb);\n                    sb.AppendLine(\");\");\n\n                }\n                sb.AppendLine();\n                if (type.IsValueType)\n                {\n                    sb.AppendLine(@\"            if(!isNewObj)\n            {\n                __ret--;\n                WriteBackInstance(__domain, __ret, __mStack, ref result_of_this_method);\n                return __ret;\n            }\");\n                }\n\n                //Ref/Out\n                for (int j = param.Length; j > 0; j--)\n                {\n                    var p = param[j - 1];\n                    if (!p.ParameterType.IsByRef)\n                        continue;\n                    string tmp, clsName;\n                    bool isByRef;\n                    p.ParameterType.GetElementType().GetClassName(out tmp, out clsName, out isByRef);\n                    sb.AppendLine(string.Format(\"            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});\", param.Length - j + 1));\n                    sb.AppendLine(@\"            switch(ptr_of_this_method->ObjectType)\n            {\n                case ObjectTypes.StackObjectReference:\n                    {\n                        var ___dst = *(StackObject**)&ptr_of_this_method->Value;\");\n                    p.ParameterType.GetElementType().GetRefWriteBackValueCode(sb, p.Name);\n                    sb.Append(@\"                    }\n                    break;\n                case ObjectTypes.FieldReference:\n                    {\n                        var ___obj = __mStack[ptr_of_this_method->Value];\n                        if(___obj is ILTypeInstance)\n                        {\n                            ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.Append(@\";\n                        }\n                        else\n                        {\n                            var t = __domain.GetType(___obj.GetType()) as CLRType;\n                            t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, \");\n                    sb.Append(p.Name);\n                    sb.Append(@\");\n                        }\n                    }\n                    break;\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = __domain.GetType(ptr_of_this_method->Value);\n                        if(t is ILType)\n                        {\n                            ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.Append(@\";\n                        }\n                        else\n                        {\n                            ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, \");\n                    sb.Append(p.Name);\n                    sb.Append(@\");\n                        }\n                    }\n                    break;\n                 case ObjectTypes.ArrayReference:\n                    {\n                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as \");\n                    sb.Append(clsName);\n                    sb.Append(@\"[];\n                        instance_of_arrayReference[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.AppendLine(@\";\n                    }\n                    break;\n            }\");\n                    sb.AppendLine();\n                }\n                sb.AppendLine(\"            return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);\");\n\n                sb.AppendLine(\"        }\");\n                sb.AppendLine();\n                idx++;\n            }\n\n            return sb.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/CLRBinding/FieldBindingGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class FieldBindingGenerator\n    {\n        internal static string GenerateFieldRegisterCode(this Type type, FieldInfo[] fields, HashSet<FieldInfo> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n            int idx = 0;\n            foreach (var i in fields)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipField(i))\n                    continue;\n                if (i.IsSpecialName)\n                    continue;\n\n                sb.AppendLine(string.Format(\"            field = type.GetField(\\\"{0}\\\", flag);\", i.Name));\n                sb.AppendLine(string.Format(\"            app.RegisterCLRFieldGetter(field, get_{0}_{1});\", i.Name, idx));\n                if (!i.IsInitOnly && !i.IsLiteral)\n                {\n                    sb.AppendLine(string.Format(\"            app.RegisterCLRFieldSetter(field, set_{0}_{1});\", i.Name, idx));\n                }\n\n                idx++;\n            }\n            return sb.ToString();\n        }\n\n        internal static string GenerateFieldWraperCode(this Type type, FieldInfo[] fields, string typeClsName, HashSet<FieldInfo> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n\n            int idx = 0;\n            foreach (var i in fields)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipField(i))\n                    continue;\n                sb.AppendLine(string.Format(\"        static object get_{0}_{1}(ref object o)\", i.Name, idx));\n                sb.AppendLine(\"        {\");\n                if (i.IsStatic)\n                {\n                    sb.AppendLine(string.Format(\"            return {0}.{1};\", typeClsName, i.Name));\n                }\n                else\n                {\n                    sb.AppendLine(string.Format(\"            return (({0})o).{1};\", typeClsName, i.Name));\n                }\n                sb.AppendLine(\"        }\");\n\n                if (!i.IsInitOnly && !i.IsLiteral)\n                {\n                    sb.AppendLine(string.Format(\"        static void set_{0}_{1}(ref object o, object v)\", i.Name, idx));\n                    sb.AppendLine(\"        {\");\n                    string clsName, realClsName;\n                    bool isByRef;\n                    i.FieldType.GetClassName(out clsName, out realClsName, out isByRef);\n                    if (i.IsStatic)\n                    {\n                        sb.AppendLine(string.Format(\"            {0}.{1} = ({2})v;\", typeClsName, i.Name, realClsName));\n                    }\n                    else\n                    {\n                        if (CheckCanPinn(type))\n                        {\n                            sb.AppendLine(\"            var h = GCHandle.Alloc(o, GCHandleType.Pinned);\");\n                            sb.AppendLine(string.Format(\"            {0}* p = ({0} *)(void *)h.AddrOfPinnedObject();\", typeClsName));\n                            sb.AppendLine(string.Format(\"            p->{0} = ({1})v;\", i.Name, realClsName));\n                            sb.AppendLine(\"            h.Free();\");\n                        }\n                        else\n                        {\n                            sb.AppendLine(string.Format(\"            (({0})o).{1} = ({2})v;\", typeClsName, i.Name, realClsName));\n                        }\n                    }\n                    sb.AppendLine(\"        }\");\n                }\n                idx++;\n            }\n\n            return sb.ToString();\n        }\n\n        internal static bool CheckCanPinn(this Type type)\n        {\n            if (type.IsValueType)\n            {\n                FieldInfo[] fi = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n                bool res = true;\n                foreach(var i in fi)\n                {\n                    if(!i.FieldType.IsPrimitive)\n                    {\n                        res = false;\n                        break;\n                    }\n                }\n\n                return res;\n            }\n            else\n                return false;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/CLRBinding/MethodBindingGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class MethodBindingGenerator\n    {\n        internal static string GenerateMethodRegisterCode(this Type type, MethodInfo[] methods, HashSet<MethodBase> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n            int idx = 0;\n            foreach (var i in methods)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipMethod(i))\n                    continue;\n                bool isProperty = i.IsSpecialName;\n                var param = i.GetParameters();\n                StringBuilder sb2 = new StringBuilder();\n                sb2.Append(\"{\");\n                bool first = true;\n                foreach (var j in param)\n                {\n                    if (first)\n                        first = false;\n                    else\n                        sb2.Append(\", \");\n                    sb2.Append(\"typeof(\");\n                    string tmp, clsName;\n                    bool isByRef;\n                    j.ParameterType.GetClassName(out tmp, out clsName, out isByRef);\n                    sb2.Append(clsName);\n                    sb2.Append(\")\");\n                    if (isByRef)\n                        sb2.Append(\".MakeByRefType()\");\n                }\n                sb2.Append(\"}\");\n                sb.AppendLine(string.Format(\"            args = new Type[]{0};\", sb2));\n                sb.AppendLine(string.Format(\"            method = type.GetMethod(\\\"{0}\\\", flag, null, args, null);\", i.Name));\n                sb.AppendLine(string.Format(\"            app.RegisterCLRMethodRedirection(method, {0}_{1});\", i.Name, idx));\n\n                idx++;\n            }\n            return sb.ToString();\n        }\n\n        internal static string GenerateMethodWraperCode(this Type type, MethodInfo[] methods, string typeClsName, HashSet<MethodBase> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n\n            int idx = 0;\n            foreach (var i in methods)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipMethod(i))\n                    continue;\n                bool isProperty = i.IsSpecialName;\n                var param = i.GetParameters();\n                int paramCnt = param.Length;\n                if (!i.IsStatic)\n                    paramCnt++;\n                sb.AppendLine(string.Format(\"        static StackObject* {0}_{1}(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\", i.Name, idx));\n                sb.AppendLine(\"        {\");\n                sb.AppendLine(\"            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\");\n                sb.AppendLine(\"            StackObject* ptr_of_this_method;\");\n                sb.AppendLine(string.Format(\"            StackObject* __ret = ILIntepreter.Minus(__esp, {0});\", paramCnt));\n                for (int j = param.Length; j > 0; j--)\n                {\n                    var p = param[j - 1];\n                    sb.AppendLine(string.Format(\"            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});\", param.Length - j + 1));\n                    string tmp, clsName;\n                    bool isByRef;\n                    p.ParameterType.GetClassName(out tmp, out clsName, out isByRef);\n                    if (isByRef)\n                        sb.AppendLine(\"            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);\");\n                    sb.AppendLine(string.Format(\"            {0} {1} = {2};\", clsName, p.Name, p.ParameterType.GetRetrieveValueCode(clsName)));\n                    if (!isByRef && !p.ParameterType.IsPrimitive)\n                        sb.AppendLine(\"            __intp.Free(ptr_of_this_method);\");\n                }\n                if (!i.IsStatic)\n                {\n                    sb.AppendLine(string.Format(\"            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});\", paramCnt));\n                    if (type.IsPrimitive)\n                        sb.AppendLine(string.Format(\"            {0} instance_of_this_method = GetInstance(__domain, ptr_of_this_method, __mStack);\", typeClsName));\n                    else\n                    {\n                        if (type.IsValueType)\n                            sb.AppendLine(\"            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);\");\n                        sb.AppendLine(string.Format(\"            {0} instance_of_this_method;\", typeClsName));\n                        sb.AppendLine(string.Format(\"            instance_of_this_method = {0};\", type.GetRetrieveValueCode(typeClsName)));\n                        if (!type.IsValueType)\n                            sb.AppendLine(\"            __intp.Free(ptr_of_this_method);\");\n                    }\n                }\n                sb.AppendLine();\n                if (i.ReturnType != typeof(void))\n                {\n                    sb.Append(\"            var result_of_this_method = \");\n                }\n                else\n                    sb.Append(\"            \");\n                if (i.IsStatic)\n                {\n                    if (isProperty)\n                    {\n                        string[] t = i.Name.Split('_');\n                        string propType = t[0];\n\n                        if (propType == \"get\")\n                        {\n                            bool isIndexer = param.Length > 0;\n                            if (isIndexer)\n                            {\n                                sb.AppendLine(string.Format(\"{1}[{0}];\", param[0].Name, typeClsName));\n                            }\n                            else\n                                sb.AppendLine(string.Format(\"{1}.{0};\", t[1], typeClsName));\n                        }\n                        else if (propType == \"set\")\n                        {\n                            bool isIndexer = param.Length > 1;\n                            if (isIndexer)\n                            {\n                                sb.AppendLine(string.Format(\"{2}[{0}] = {1};\", param[0].Name, param[1].Name, typeClsName));\n                            }\n                            else\n                                sb.AppendLine(string.Format(\"{2}.{0} = {1};\", t[1], param[0].Name, typeClsName));\n                        }\n                        else if (propType == \"op\")\n                        {\n                            switch (t[1])\n                            {\n                                case \"Equality\":\n                                    sb.AppendLine(string.Format(\"{0} == {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"Inequality\":\n                                    sb.AppendLine(string.Format(\"{0} != {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"Addition\":\n                                    sb.AppendLine(string.Format(\"{0} + {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"Subtraction\":\n                                    sb.AppendLine(string.Format(\"{0} - {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"Multiply\":\n                                    sb.AppendLine(string.Format(\"{0} * {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"Division\":\n                                    sb.AppendLine(string.Format(\"{0} / {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"GreaterThan\":\n                                    sb.AppendLine(string.Format(\"{0} > {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"GreaterThanOrEqual\":\n                                    sb.AppendLine(string.Format(\"{0} >= {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"LessThan\":\n                                    sb.AppendLine(string.Format(\"{0} < {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"LessThanOrEqual\":\n                                    sb.AppendLine(string.Format(\"{0} <= {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"UnaryNegation\":\n                                    sb.AppendLine(string.Format(\"-{0};\", param[0].Name));\n                                    break;\n                                case \"Implicit\":\n                                case \"Explicit\":\n                                    {\n                                        string tmp, clsName;\n                                        bool isByRef;\n                                        i.ReturnType.GetClassName(out tmp, out clsName, out isByRef);\n                                        sb.AppendLine(string.Format(\"({1}){0};\", param[0].Name, clsName));\n                                    }\n                                    break;\n                                default:\n                                    throw new NotImplementedException(i.Name);\n                            }\n                        }\n                        else\n                            throw new NotImplementedException();\n                    }\n                    else\n                    {\n                        sb.Append(string.Format(\"{0}.{1}(\", typeClsName, i.Name));\n                        param.AppendParameters(sb);\n                        sb.AppendLine(\");\");\n                    }\n                }\n                else\n                {\n                    if (isProperty)\n                    {\n                        string[] t = i.Name.Split('_');\n                        string propType = t[0];\n\n                        if (propType == \"get\")\n                        {\n                            bool isIndexer = param.Length > 0;\n                            if (isIndexer)\n                            {\n                                sb.AppendLine(string.Format(\"instance_of_this_method[{0}];\", param[0].Name));\n                            }\n                            else\n                                sb.AppendLine(string.Format(\"instance_of_this_method.{0};\", t[1]));\n                        }\n                        else if (propType == \"set\")\n                        {\n                            bool isIndexer = param.Length > 1;\n                            if (isIndexer)\n                            {\n                                sb.AppendLine(string.Format(\"instance_of_this_method[{0}] = {1};\", param[0].Name, param[1].Name));\n                            }\n                            else\n                                sb.AppendLine(string.Format(\"instance_of_this_method.{0} = {1};\", t[1], param[0].Name));\n                        }\n                        else\n                            throw new NotImplementedException();\n                    }\n                    else\n                    {\n                        sb.Append(string.Format(\"instance_of_this_method.{0}(\", i.Name));\n                        param.AppendParameters(sb);\n                        sb.AppendLine(\");\");\n                    }\n                }\n                sb.AppendLine();\n\n\n                if (!i.IsStatic && type.IsValueType && !type.IsPrimitive)//need to write back value type instance\n                {\n                    sb.AppendLine(\"            WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);\");\n                    sb.AppendLine();\n                }\n                //Ref/Out\n                for (int j = param.Length; j > 0; j--)\n                {\n                    var p = param[j - 1];\n                    if (!p.ParameterType.IsByRef)\n                        continue;\n                    string tmp, clsName;\n                    bool isByRef;\n                    p.ParameterType.GetElementType().GetClassName(out tmp, out clsName, out isByRef);\n                    sb.AppendLine(string.Format(\"            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});\", param.Length - j + 1));\n                    sb.AppendLine(@\"            switch(ptr_of_this_method->ObjectType)\n            {\n                case ObjectTypes.StackObjectReference:\n                    {\n                        var ___dst = *(StackObject**)&ptr_of_this_method->Value;\");\n                    p.ParameterType.GetElementType().GetRefWriteBackValueCode(sb, p.Name);\n                    sb.Append(@\"                    }\n                    break;\n                case ObjectTypes.FieldReference:\n                    {\n                        var ___obj = __mStack[ptr_of_this_method->Value];\n                        if(___obj is ILTypeInstance)\n                        {\n                            ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.Append(@\";\n                        }\n                        else\n                        {\n                            var t = __domain.GetType(___obj.GetType()) as CLRType;\n                            t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, \");\n                    sb.Append(p.Name);\n                    sb.Append(@\");\n                        }\n                    }\n                    break;\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = __domain.GetType(ptr_of_this_method->Value);\n                        if(t is ILType)\n                        {\n                            ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.Append(@\";\n                        }\n                        else\n                        {\n                            ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, \");\n                    sb.Append(p.Name);\n                    sb.Append(@\");\n                        }\n                    }\n                    break;\n                 case ObjectTypes.ArrayReference:\n                    {\n                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as \");\n                    sb.Append(clsName);\n                    sb.Append(@\"[];\n                        instance_of_arrayReference[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.AppendLine(@\";\n                    }\n                    break;\n            }\");\n                    sb.AppendLine();\n                }\n                if (i.ReturnType != typeof(void))\n                {\n                    i.ReturnType.GetReturnValueCode(sb);\n                }\n                else\n                    sb.AppendLine(\"            return __ret;\");\n                sb.AppendLine(\"        }\");\n                sb.AppendLine();\n                idx++;\n            }\n\n            return sb.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/CLRBinding/ValueTypeBindingGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class ValueTypeBindingGenerator\n    {\n        internal static string GenerateValueTypeRegisterCode(this Type type, string typeClsName)\n        {\n            StringBuilder sb = new StringBuilder();\n\n            if (type.IsValueType && !type.IsPrimitive && !type.IsEnum)\n            {\n                sb.AppendLine(\"            app.RegisterCLRMemberwiseClone(type, PerformMemberwiseClone);\");\n            }\n            return sb.ToString();\n        }\n\n        internal static string GenerateCloneWraperCode(this Type type, FieldInfo[] fields, string typeClsName)\n        {\n            if (!type.IsValueType || type.IsPrimitive) return string.Empty;\n            StringBuilder sb = new StringBuilder();\n\n            sb.AppendLine(\"        static object PerformMemberwiseClone(ref object o)\");\n            sb.AppendLine(\"        {\");\n            sb.AppendLine(string.Format(\"            return new {0}\", typeClsName));\n            sb.AppendLine(\"            {\");\n\n            foreach (var i in fields)\n            {\n                if (i.IsStatic || i.IsInitOnly || i.IsLiteral) continue;\n                sb.AppendLine(string.Format(\"                {0} = (({1}) o).{0},\", i.Name, typeClsName));\n            }\n\n            sb.AppendLine(\"            };\");\n            sb.AppendLine(\"        }\");\n\n            return sb.ToString();\n\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/BreakPointContext.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nnamespace ILRuntime.Runtime.Debugger\n{\n    unsafe class BreakPointContext\n    {\n        public ILIntepreter Interpreter { get; set; }\n        public Exception Exception { get; set; }\n\n        public string DumpContext()\n        {\n            /*StringBuilder sb = new StringBuilder();\n            if (Exception != null)\n                sb.AppendLine(Exception.Message);\n            StackFrame[] frames = Interpreter.Stack.Frames.ToArray();\n            StackFrame topFrame = frames[0];\n            var m = topFrame.Method;\n            if (m.HasThis)\n            {\n                sb.AppendLine(\"this:\");\n                sb.AppendLine(DebugService.Instance.GetThisInfo(Interpreter));\n            }\n            sb.AppendLine(\"->\" + topFrame.Method.Definition.Body.Instructions[topFrame.Address.Value]);\n            sb.AppendLine(\"Local Variables:\");\n            sb.AppendLine(DebugService.Instance.GetLocalVariableInfo(Interpreter));\n\n            sb.Append(DebugService.Instance.GetStackTrance(Interpreter));\n            return sb.ToString();*/\n            return null;\n        }\n\n        string GetStackObjectValue(StackObject val, IList<object> mStack)\n        {\n            string v;\n            switch (val.ObjectType)\n            {\n                case ObjectTypes.Null:\n                    v = \"null\";\n                    break;\n                case ObjectTypes.Integer:\n                    v = val.Value.ToString();\n                    break;\n                case ObjectTypes.Object:\n                    {\n                        object obj = Interpreter.Stack.ManagedStack[val.Value];\n                        v = obj.ToString();\n                    }\n                    break;\n                default:\n                    v = \"Unknown type\";\n                    break;\n            }\n            return v;\n        }        \n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/BreakpointInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    class BreakpointInfo\n    {\n        public int BreakpointHashCode { get; set; }\n        public int MethodHashCode { get; set; }\n        public int StartLine { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/DebugMessageType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public enum DebugMessageType\n    {\n        CSAttach,\n        SCAttachResult,\n        CSBindBreakpoint,\n        SCBindBreakpointResult,\n        SCModuleLoaded,\n        SCThreadStarted,\n        SCThreadEnded,\n        SCBreakpointHit,\n        CSDeleteBreakpoint,\n        CSExecute,\n        CSStep,\n        SCStepComplete,\n        CSResolveVariable,\n        SCResolveVariableResult\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/DebugService.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\n\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.CLR.Utils;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public class DebugService\n    {\n        BreakPointContext curBreakpoint;\n        DebuggerServer server;\n        Runtime.Enviorment.AppDomain domain;\n        Dictionary<int, LinkedList<BreakpointInfo>> activeBreakpoints = new Dictionary<int, LinkedList<BreakpointInfo>>();\n        Dictionary<int, BreakpointInfo> breakpointMapping = new Dictionary<int, BreakpointInfo>();\n        AutoResetEvent evt = new AutoResetEvent(false);\n        \n        public Action<string> OnBreakPoint;\n\n        public Enviorment.AppDomain AppDomain { get { return domain; } }\n\n        public AutoResetEvent BlockEvent { get { return evt; } }\n\n        public bool IsDebuggerAttached\n        {\n            get\n            {\n#if DEBUG\n                return (server != null && server.IsAttached);\n#else\n                return false;\n#endif\n            }\n        }\n\n        public DebugService(Runtime.Enviorment.AppDomain domain)\n        {\n            this.domain = domain;\n        }\n\n        /// <summary>\n        /// Start Debugger Server\n        /// </summary>\n        /// <param name=\"port\">Port to listen on</param>\n        public void StartDebugService(int port)\n        {\n#if DEBUG\n            server = new Debugger.DebuggerServer(this);\n            server.Port = port;\n            server.Start();\n#endif\n        }\n\n        /// <summary>\n        /// Stop Debugger Server\n        /// </summary>\n        public void StopDebugService()\n        {\n#if DEBUG\n            server.Stop();\n            server = null;\n#endif\n        }\n\n        /// <summary>\n        /// 中断运行\n        /// </summary>\n        /// <param name=\"intpreter\"></param>\n        /// <param name=\"ex\"></param>\n        /// <returns>如果挂的有调试器则返回true</returns>\n        internal bool Break(ILIntepreter intpreter, Exception ex = null)\n        {\n            BreakPointContext ctx = new BreakPointContext();\n            ctx.Interpreter = intpreter;\n            ctx.Exception = ex;\n\n            curBreakpoint = ctx;\n\n            if (OnBreakPoint != null)\n            {\n                OnBreakPoint(ctx.DumpContext());\n                return true;\n            }\n            return false;\n        }\n\n        public string GetStackTrance(ILIntepreter intepreper)\n        {\n            StringBuilder sb = new StringBuilder();\n            ILRuntime.CLR.Method.ILMethod m;\n            StackFrame[] frames = intepreper.Stack.Frames.ToArray();\n            Mono.Cecil.Cil.Instruction ins = null;\n            if (frames[0].Address != null)\n            {\n                ins = frames[0].Method.Definition.Body.Instructions[frames[0].Address.Value];\n                sb.AppendLine(ins.ToString());\n            }\n            for (int i = 0; i < frames.Length; i++)\n            {\n                var f = frames[i];\n                m = f.Method;\n                string document = \"\";\n                if (f.Address != null)\n                {\n                    ins = m.Definition.Body.Instructions[f.Address.Value];\n                    var seq = FindSequencePoint(ins);\n                    if (seq != null)\n                    {\n                        document = string.Format(\"{0}:Line {1}\", seq.Document.Url, seq.StartLine);\n                    }\n                }\n                sb.AppendFormat(\"at {0} {1}\\r\\n\", m, document);\n            }\n\n            return sb.ToString();\n        }\n\n        public unsafe string GetThisInfo(ILIntepreter intepreter)\n        {\n            var topFrame = intepreter.Stack.Frames.Peek();\n            var arg = Minus(topFrame.LocalVarPointer, topFrame.Method.ParameterCount);\n            if (topFrame.Method.HasThis)\n                arg--;\n            if (arg->ObjectType == ObjectTypes.StackObjectReference)\n            {\n                arg = *(StackObject**)&arg->Value;\n            }\n            ILTypeInstance instance = arg->ObjectType != ObjectTypes.Null ? intepreter.Stack.ManagedStack[arg->Value] as ILTypeInstance : null;\n            if (instance == null)\n                return \"null\";\n            var fields = instance.Type.TypeDefinition.Fields;\n            int idx = 0;\n            StringBuilder sb = new StringBuilder();\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var f = fields[i];\n                if (f.IsStatic)\n                    continue;\n                var field = instance.Fields[idx];\n                var v = StackObject.ToObject(&field, intepreter.AppDomain, instance.ManagedObjects);\n                if (v == null)\n                    v = \"null\";\n                string name = f.Name;\n                sb.AppendFormat(\"{0} {1} = {2}\", f.FieldType.Name, name, v);\n                if ((idx % 3 == 0 && idx != 0) || idx == instance.Fields.Length - 1)\n                    sb.AppendLine();\n                else\n                    sb.Append(\", \");\n                idx++;\n            }\n            return sb.ToString();\n        }\n\n        public unsafe string GetLocalVariableInfo(ILIntepreter intepreter)\n        {\n            StackFrame topFrame = intepreter.Stack.Frames.Peek();\n            var m = topFrame.Method;\n            StringBuilder sb = new StringBuilder();\n            for (int i = 0; i < m.LocalVariableCount; i++)\n            {\n                var lv = m.Definition.Body.Variables[i];\n                var val = Add(topFrame.LocalVarPointer, i);\n                var v = StackObject.ToObject(val, intepreter.AppDomain, intepreter.Stack.ManagedStack);\n                if (v == null)\n                    v = \"null\";\n                string name = string.IsNullOrEmpty(lv.Name) ? \"v\" + lv.Index : lv.Name;\n                sb.AppendFormat(\"{0} {1} = {2}\", lv.VariableType.Name, name, v);\n                if ((i % 3 == 0 && i != 0) || i == m.LocalVariableCount - 1)\n                    sb.AppendLine();\n                else\n                    sb.Append(\", \");\n            }\n            return sb.ToString();\n        }\n\n        internal static Mono.Cecil.Cil.SequencePoint FindSequencePoint(Mono.Cecil.Cil.Instruction ins)\n        {\n            Mono.Cecil.Cil.Instruction cur = ins;\n            while (cur.SequencePoint == null && cur.Previous != null)\n                cur = cur.Previous;\n\n            return cur.SequencePoint;\n        }\n\n        unsafe StackObject* Add(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a + sizeof(StackObject) * b);\n        }\n\n        unsafe StackObject* Minus(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a - sizeof(StackObject) * b);\n        }\n\n        internal void NotifyModuleLoaded(string moduleName)\n        {\n            if (server != null && server.IsAttached)\n                server.NotifyModuleLoaded(moduleName);\n        }\n\n        internal void SetBreakPoint(int methodHash, int bpHash, int startLine)\n        {\n            lock (activeBreakpoints)\n            {\n                LinkedList<BreakpointInfo> lst;\n                if(!activeBreakpoints.TryGetValue(methodHash, out lst))\n                {\n                    lst = new LinkedList<Debugger.BreakpointInfo>();\n                    activeBreakpoints[methodHash] = lst;\n                }\n\n                BreakpointInfo bpInfo = new BreakpointInfo();\n                bpInfo.BreakpointHashCode = bpHash;\n                bpInfo.MethodHashCode = methodHash;\n                bpInfo.StartLine = startLine;\n\n                lst.AddLast(bpInfo);\n                breakpointMapping[bpHash] = bpInfo;\n            }\n        }\n\n        internal void DeleteBreakpoint(int bpHash)\n        {\n            lock (activeBreakpoints)\n            {\n                BreakpointInfo bpInfo;\n                if (breakpointMapping.TryGetValue(bpHash, out bpInfo))\n                {\n                    LinkedList<BreakpointInfo> lst;\n                    if(activeBreakpoints.TryGetValue(bpInfo.MethodHashCode, out lst))\n                    {\n                        lst.Remove(bpInfo);                        \n                    }\n                    breakpointMapping.Remove(bpHash);\n                }\n            }\n        }\n\n        internal void ExecuteThread(int threadHash)\n        {\n            lock (AppDomain.FreeIntepreters)\n            {\n                foreach(var i in AppDomain.Intepreters)\n                {\n                    //We should resume all threads on execute\n                    i.Value.ClearDebugState();\n                    i.Value.Resume();\n                }\n            }\n        }\n\n        internal unsafe void StepThread(int threadHash, StepTypes type)\n        {\n            lock (AppDomain.FreeIntepreters)\n            {\n                ILIntepreter intp;\n                if(AppDomain.Intepreters.TryGetValue(threadHash, out intp))\n                {\n                    intp.ClearDebugState();\n                    intp.CurrentStepType = type;\n                    intp.LastStepFrameBase = intp.Stack.Frames.Count > 0 ? intp.Stack.Frames.Peek().BasePointer : (StackObject*)0;\n                    intp.LastStepInstructionIndex = intp.Stack.Frames.Count > 0 ? intp.Stack.Frames.Peek().Address.Value : 0;\n\n                    intp.Resume();\n                }\n            }\n        }\n\n        unsafe internal void CheckShouldBreak(ILMethod method, ILIntepreter intp, int ip)\n        {\n            if (server != null && server.IsAttached)\n            {\n                int methodHash = method.GetHashCode();\n                lock (activeBreakpoints)\n                {\n                    LinkedList<BreakpointInfo> lst;\n                    bool bpHit = false;\n\n                    if (activeBreakpoints.TryGetValue(methodHash, out lst))\n                    {\n                        var sp = method.Definition.Body.Instructions[ip].SequencePoint;\n                        if (sp != null)\n                        {\n                            foreach (var i in lst)\n                            {\n                                if ((i.StartLine + 1) == sp.StartLine)\n                                {\n                                    DoBreak(intp, i.BreakpointHashCode, false);\n                                    bpHit = true;\n                                    break;\n                                }\n                            }\n                        }\n                    }\n\n                    if (!bpHit)\n                    {\n                        var sp = method.Definition.Body.Instructions[ip].SequencePoint;\n                        if (sp != null && IsSequenceValid(sp))\n                        {                            \n                            switch (intp.CurrentStepType)\n                            {\n                                case StepTypes.Into:\n                                    DoBreak(intp, 0, true);\n                                    break;\n                                case StepTypes.Over:\n                                    if (intp.Stack.Frames.Peek().BasePointer <= intp.LastStepFrameBase && ip != intp.LastStepInstructionIndex)\n                                    {\n                                        DoBreak(intp, 0, true);\n                                    }\n                                    break;\n                                case StepTypes.Out:\n                                    {\n                                        if (intp.Stack.Frames.Count > 0 && intp.Stack.Frames.Peek().BasePointer < intp.LastStepFrameBase)\n                                        {\n                                            DoBreak(intp, 0, true);\n                                        }\n                                    }\n                                    break;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        bool IsSequenceValid(Mono.Cecil.Cil.SequencePoint sp)\n        {\n            return sp.StartLine != sp.EndLine || sp.StartColumn != sp.EndColumn;\n        }\n\n        void DoBreak(ILIntepreter intp, int bpHash, bool isStep)\n        {\n            KeyValuePair<int, StackFrameInfo[]>[] frames = new KeyValuePair<int, StackFrameInfo[]>[AppDomain.Intepreters.Count];\n            frames[0] = new KeyValuePair<int, StackFrameInfo[]>(intp.GetHashCode(), GetStackFrameInfo(intp));\n            int idx = 1;\n            foreach (var j in AppDomain.Intepreters)\n            {\n                if (j.Value != intp)\n                {\n                    j.Value.ShouldBreak = true;\n                    frames[idx++] = new KeyValuePair<int, Debugger.StackFrameInfo[]>(j.Value.GetHashCode(), GetStackFrameInfo(j.Value));\n                }\n            }\n            if (!isStep)\n                server.SendSCBreakpointHit(intp.GetHashCode(), bpHash, frames);\n            else\n                server.SendSCStepComplete(intp.GetHashCode(), frames);\n            //Breakpoint hit\n            intp.Break();\n        }\n\n        unsafe StackFrameInfo[] GetStackFrameInfo(ILIntepreter intp)\n        {\n            StackFrame[] frames = intp.Stack.Frames.ToArray();\n            Mono.Cecil.Cil.Instruction ins = null;\n            ILMethod m;\n            StackFrameInfo[] frameInfos = new StackFrameInfo[frames.Length];\n\n            for (int j = 0; j < frames.Length; j++)\n            {\n                StackFrameInfo info = new Debugger.StackFrameInfo();\n                var f = frames[j];\n                m = f.Method;\n                info.MethodName = m.ToString();\n\n                if (f.Address != null)\n                {\n                    ins = m.Definition.Body.Instructions[f.Address.Value];\n                    var seq = FindSequencePoint(ins);\n                    if (seq != null)\n                    {\n                        info.DocumentName = seq.Document.Url;\n                        info.StartLine = seq.StartLine - 1;\n                        info.StartColumn = seq.StartColumn - 1;\n                        info.EndLine = seq.EndLine - 1;\n                        info.EndColumn = seq.EndColumn - 1;\n                    }\n                }\n                StackFrame topFrame = f;\n                m = topFrame.Method;\n                int argumentCount = m.ParameterCount;\n                if (m.HasThis)\n                    argumentCount++;\n                info.LocalVariables = new VariableInfo[argumentCount + m.LocalVariableCount];\n                for(int i = 0; i < argumentCount; i++)\n                {\n                    int argIdx = m.HasThis ? i - 1 : i;\n                    var arg = Minus(topFrame.LocalVarPointer, argumentCount);\n                    string name = null;\n                    object v = null;\n                    string typeName = null;\n                    var val = Add(arg, i);\n                    v =  StackObject.ToObject(val, intp.AppDomain, intp.Stack.ManagedStack);\n                    if (v == null)\n                        v = \"null\";\n                    if (argIdx >= 0)\n                    {\n                        var lv = m.Definition.Parameters[argIdx];\n                        name = string.IsNullOrEmpty(lv.Name) ? \"arg\" + lv.Index : lv.Name;\n                        typeName = lv.ParameterType.FullName;\n                        if (v != null)\n                            v = m.Parameters[argIdx].TypeForCLR.CheckCLRTypes(v);\n                    }\n                    else\n                    {\n                        name = \"this\";\n                        typeName = m.DeclearingType.FullName;\n                    }\n\n                    VariableInfo vinfo = new Debugger.VariableInfo();\n                    vinfo.Address = (long)val;\n                    vinfo.Name = name;\n                    vinfo.Value = v.ToString();\n                    vinfo.TypeName = typeName;\n                    vinfo.Expandable = GetValueExpandable(val, intp.Stack.ManagedStack);\n\n                    info.LocalVariables[i] = vinfo;\n                }\n                for (int i = argumentCount; i < info.LocalVariables.Length; i++)\n                {\n                    var locIdx = i - argumentCount;\n                    var lv = m.Definition.Body.Variables[locIdx];\n                    var val = Add(topFrame.LocalVarPointer, locIdx);\n                    var v = StackObject.ToObject(val, intp.AppDomain, intp.Stack.ManagedStack);\n                    if (v == null)\n                        v = \"null\";\n                    else\n                        v = intp.AppDomain.GetType(lv.VariableType, m.DeclearingType, m).TypeForCLR.CheckCLRTypes(v);\n                    string name = string.IsNullOrEmpty(lv.Name) ? \"v\" + lv.Index : lv.Name;\n                    VariableInfo vinfo = new Debugger.VariableInfo();\n                    vinfo.Address = (long)val;\n                    vinfo.Name = name;\n                    vinfo.Value = v.ToString();\n                    vinfo.TypeName = lv.VariableType.FullName;\n                    vinfo.Expandable = GetValueExpandable(val, intp.Stack.ManagedStack);\n                    info.LocalVariables[i] = vinfo;\n                }\n                frameInfos[j] = info;\n            }\n            return frameInfos;\n        }\n\n        internal VariableInfo ResolveVariable(VariableReference parent, string name)\n        {\n            return null;\n        }\n\n        unsafe bool GetValueExpandable(StackObject* esp, IList<object> mStack)\n        {\n            if (esp->ObjectType < ObjectTypes.Object)\n                return false;\n            else\n            {\n                var obj = mStack[esp->Value];\n                if (obj == null)\n                    return false;\n                if (obj is ILTypeInstance)\n                    return true;\n                else if (obj.GetType().IsPrimitive)\n                    return false;\n                else\n                    return true;\n\n            }\n        }\n\n        internal void ThreadStarted(ILIntepreter intp)\n        {\n            if (server != null && server.IsAttached)\n            {\n                server.SendSCThreadStarted(intp.GetHashCode());\n            }\n        }\n\n        internal void ThreadEnded(ILIntepreter intp)\n        {\n            if (server != null && server.IsAttached)\n            {\n                server.SendSCThreadEnded(intp.GetHashCode());\n            }\n        }\n\n        internal void Detach()\n        {\n            activeBreakpoints.Clear();\n            breakpointMapping.Clear();\n            foreach (var j in AppDomain.Intepreters)\n            {\n                j.Value.ClearDebugState();\n                j.Value.Resume();\n            }\n        }\n\n        internal unsafe void DumpStack(StackObject* esp, RuntimeStack stack)\n        {\n#if !UNITY_5 && !UNITY_2017 && !UNITY_4\n            var start = stack.StackBase;\n            var end = esp + 10;\n            var frames = stack.Frames;\n            var mStack = stack.ManagedStack;\n            var valuePointerEnd = stack.ValueTypeStackPointer;\n            HashSet<long> leakVObj = new HashSet<long>();\n            for (var i = stack.ValueTypeStackBase; i > stack.ValueTypeStackPointer;)\n            {\n                leakVObj.Add((long)i);\n                i = Minus(i, i->ValueLow + 1);\n            }\n            for (var i = start; i <= end; i++)\n            {\n                StringBuilder sb = new StringBuilder();\n                ILMethod localMethod = null, baseMethod = null;\n                bool isLocal = false;\n                bool isBase = false;\n                int localIdx = 0;\n                if (i == esp)\n                    sb.Append(\"->\");\n                foreach (var j in frames)\n                {\n                    if (i >= j.LocalVarPointer && i < j.BasePointer)\n                    {\n                        isLocal = true;\n                        localIdx = (int)(i - j.LocalVarPointer);\n                        localMethod = j.Method;\n                    }\n                    else if (i == j.BasePointer)\n                    {\n                        isBase = true;\n                        baseMethod = j.Method;\n                    }\n                }\n                sb.Append(string.Format(\"(0x{0:X8}) Type:{1} \", (long)i, i->ObjectType));\n                GetStackObjectText(sb, i, mStack, valuePointerEnd);\n                if (i < esp)\n                {\n                    if (i->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                        VisitValueTypeReference(*(StackObject**)&i->Value, leakVObj);\n                }\n                if (isLocal)\n                {\n                    sb.Append(string.Format(\"|Loc:{0}\", localIdx));\n                    if (localIdx == 0)\n                    {\n                        sb.Append(\" Method:\");\n                        sb.Append(localMethod.ToString());\n                    }\n                }\n                if (isBase)\n                {\n                    sb.Append(\"|Base\");\n                    sb.Append(\" Method:\");\n                    sb.Append(baseMethod.ToString());\n                }\n\n                System.Diagnostics.Debug.Print(sb.ToString());\n            }\n\n            for (var i = stack.ValueTypeStackBase; i > stack.ValueTypeStackPointer;)\n            {\n                var vt = domain.GetType(i->Value);\n                var cnt = i->ValueLow;\n                bool leak = leakVObj.Contains((long)i);\n                System.Diagnostics.Debug.Print(\"----------------------------------------------\");\n                System.Diagnostics.Debug.Print(string.Format(\"{2}(0x{0:X8}){1}\", (long)i, vt, leak ? \"*\" : \"\"));\n                for (int j = 0; j < cnt; j++)\n                {\n                    StringBuilder sb = new StringBuilder();\n                    var ptr = Minus(i, j + 1);\n                    sb.Append(string.Format(\"(0x{0:X8}) Type:{1} \", (long)ptr, ptr->ObjectType));\n                    GetStackObjectText(sb, ptr, mStack, valuePointerEnd);\n                    System.Diagnostics.Debug.Print(sb.ToString());\n                }\n                i = Minus(i, i->ValueLow + 1);\n            }\n            System.Diagnostics.Debug.Print(\"Managed Objects:\");\n            for (int i = 0; i < mStack.Count; i++)\n            {\n                System.Diagnostics.Debug.Print(string.Format(\"({0}){1}\", i, mStack[i]));\n            }\n#endif\n        }\n\n        unsafe void GetStackObjectText(StringBuilder sb, StackObject* esp, IList<object> mStack, StackObject* valueTypeEnd)\n        {\n            string text = \"null\";\n            switch (esp->ObjectType)\n            {\n                case ObjectTypes.StackObjectReference:\n                    {\n                        sb.Append(string.Format(\"Value:0x{0:X8}\", (long)*(StackObject**)&esp->Value));\n                    }\n                    break;\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        object obj = null;\n                        var dst = *(StackObject**)&esp->Value;\n                        if (dst > valueTypeEnd)\n                            obj = StackObject.ToObject(esp, domain, mStack);\n                        if (obj != null)\n                            text = obj.ToString();\n\n                        text += string.Format(\"({0})\", domain.GetType(dst->Value));\n                    }\n                    sb.Append(string.Format(\"Value:0x{0:X8} Text:{1} \", (long)*(StackObject**)&esp->Value, text));\n                    break;\n                default:\n                    {\n                        if (esp->ObjectType >= ObjectTypes.Null && esp->ObjectType <= ObjectTypes.ArrayReference)\n                        {\n                            if (esp->ObjectType < ObjectTypes.Object || esp->Value < mStack.Count)\n                            {\n                                var obj = StackObject.ToObject(esp, domain, mStack);\n                                if (obj != null)\n                                    text = obj.ToString();\n                            }\n                        }\n\n                        sb.Append(string.Format(\"Value:{0} ValueLow:{1} Text:{2} \", esp->Value, esp->ValueLow, text));\n                    }\n                    break;\n\n            }\n        }\n\n        unsafe void VisitValueTypeReference(StackObject* esp, HashSet<long> leak)\n        {\n            leak.Remove((long)esp);\n            for (int i = 0; i < esp->ValueLow; i++)\n            {\n                var ptr = Minus(esp, i + 1);\n                if (ptr->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                {\n                    VisitValueTypeReference(*(StackObject**)&ptr->Value, leak);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/DebugSocket.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\nusing System.Net.Sockets;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public class DebugSocket\n    {\n        private Socket _socket = null;\n        private bool _ready = false;\n        bool connectFailed = false;\n        private const int MAX_BUFF_SIZE = 256 * 1024;\n        private const int HEAD_SIZE = 8;\n        private byte[] _headBuffer = new byte[HEAD_SIZE];\n        private byte[] _sendBuffer = new byte[64 * 1024];\n        //private MemoryPoolSafe<Package> _packagePool = new MemoryPoolSafe<Package>();\n        //private Package _currPackage = null;\n        private System.IO.MemoryStream _sendStream = null;\n        BinaryWriter bw;\n        const int RECV_BUFFER_SIZE = 1024;\n        private MemoryStream recvBuffer = new MemoryStream();\n        private int lastMsgLength = -1;\n\n        private byte[] socketAsyncBuffer = new byte[RECV_BUFFER_SIZE];\n        private SocketAsyncEventArgs saeArgs;\n        private object socketLockObj = new object();\n        private byte[] _sendHeaderBuffer = new byte[HEAD_SIZE];\n\n        public bool Disconnected { get { return _socket == null || !_socket.Connected; } }\n        public Action OnConnect { get; set; }\n\n        public Action OnConnectFailed { get; set; }\n        public Action OnClose { get; set; }\n\n        public Action<DebugMessageType, byte[]> OnReciveMessage { get; set; }\n\n\n        public DebugSocket()\n        {\n            _sendStream = new System.IO.MemoryStream(_sendBuffer);\n            bw = new BinaryWriter(_sendStream);\n        }\n        public DebugSocket(Socket _socket)\n            : this()\n        {\n            this._socket = _socket;\n            BeginReceive();\n            _ready = true;\n        }\n        public void Connect(string ip, int port)\n        {\n            Close();\n            Socket socket;\n            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n            socket.BeginConnect(ip, port, new AsyncCallback(onConnected), this);\n            _socket = socket;\n            _ready = false;\n        }\n\n        private void AsyncRecv_Completed(object sender, SocketAsyncEventArgs e)\n        {\n            if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)\n            {\n                try\n                {\n                    ReceivePayload(e.Buffer, e.BytesTransferred);\n                }\n                catch (Exception ex)\n                {\n                    Close();\n                    return;\n                }\n            }\n            else\n            {\n                Close();\n                return;\n            }\n\n            try\n            {\n                //继续接受数据\n                if (!_socket.ReceiveAsync(saeArgs))\n                {\n                    AsyncRecv_Completed(null, saeArgs);\n                }\n            }\n            catch (Exception ex)\n            {\n                Close();\n                throw ex;\n            }\n        }\n\n        private void ReceivePayload(byte[] data, int length)\n        {\n            if (_socket == null)\n                return;\n            if (!_socket.Connected)\n            {\n                Close();\n                return;\n            }\n            //接受数据并拼接成message\n            byte[] msgBuff;\n            //写入缓存\n            recvBuffer.Position = recvBuffer.Length;\n            recvBuffer.Write(data, 0, length);\n            //如果长度有错，返回\n            if (lastMsgLength < 0 && recvBuffer.Length < 4)\n            {\n                msgBuff = null;\n                return;\n            }\n\n            recvBuffer.Position = 0;\n            BinaryReader br = new BinaryReader(recvBuffer);\n            //读取消息长度\n            if (lastMsgLength < 0)\n            {\n                lastMsgLength = br.ReadInt32() - 4;\n                if (lastMsgLength > MAX_BUFF_SIZE)\n                {\n                    Close();\n                    throw new Exception(\"Too long package length!\");\n                }\n            }\n            int remaining = (int)(recvBuffer.Length - recvBuffer.Position);\n            //消息已经完整\n            while (remaining >= lastMsgLength && lastMsgLength > 0)\n            {\n\n                //读取一条消息\n                int type = br.ReadInt32();\n                msgBuff = br.ReadBytes(lastMsgLength - 4);\n\n                if (OnReciveMessage != null)\n                    OnReciveMessage((DebugMessageType)type, msgBuff);\n\n                lastMsgLength = -1;\n                remaining = (int)(recvBuffer.Length - recvBuffer.Position);\n                //保留剩余数据\n                if (remaining >= 4)\n                {\n                    lastMsgLength = br.ReadInt32() - 4;\n                    remaining -= 4;\n                    if (lastMsgLength > MAX_BUFF_SIZE)\n                    {\n                        Close();\n                        throw new Exception(\"Too long package length!\");\n                    }\n                }\n            }\n\n            remaining = (int)(recvBuffer.Length - recvBuffer.Position);\n            if (remaining > 0)\n            {\n                byte[] buffer = recvBuffer.GetBuffer();\n                Array.Copy(buffer, recvBuffer.Position, buffer, 0, remaining);\n            }\n            recvBuffer.Position = 0;\n            recvBuffer.SetLength(remaining);\n        }\n        private void onConnected(IAsyncResult result)\n        {\n            if (_socket.Connected)\n            {\n                _socket.EndConnect(result);\n\n                BeginReceive();\n                if (OnConnect != null)\n                    OnConnect();\n                //ReceiveOnce();\n            }\n            else\n            {\n                if (OnConnectFailed != null)\n                    OnConnectFailed();\n            }\n        }\n\n        void BeginReceive()\n        {\n            saeArgs = new SocketAsyncEventArgs();\n            saeArgs.Completed += AsyncRecv_Completed;\n            saeArgs.SetBuffer(socketAsyncBuffer, 0, socketAsyncBuffer.Length);\n            _socket.ReceiveAsync(saeArgs);\n            _ready = true;\n        }\n\n        //len type msg\n        public void Send(DebugMessageType type, byte[] buffer, int len)\n        {\n            if (!_ready)\n                return;\n\n            //timeStamp = UnityEngine.Time.realtimeSinceStartup;\n            _sendStream.Position = 0;\n            bw.Write(len + HEAD_SIZE);\n            bw.Write((int)type);\n            bw.Write(buffer, 0, len);\n            int totalLen = (int)_sendStream.Position;\n\n            RawSend(_socket, _sendBuffer, totalLen);\n            //_socket.Send(_sendBuffer, len, SocketFlags.None);\n        }\n\n        private void RawSend(Socket sock, byte[] buf, int end)\n        {\n            if (sock == null)\n                return;\n            if (end < 0)\n                end = buf.Length;\n            sock.Send(buf, end, SocketFlags.None);\n        }\n\n        public void Close()\n        {\n            if (_socket == null || !_ready)\n                return;\n            if (saeArgs != null)\n                saeArgs.Dispose();\n            _socket.Close();\n            _socket = null;\n            _ready = false;\n            if (OnClose != null)\n            {\n                OnClose();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/DebuggerServer/DebuggerServer.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Net.Sockets;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Debugger.Protocol;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public class DebuggerServer\n    {\n        public const int Version = 1;\n        TcpListener listener;\n        //HashSet<Session<T>> clients = new HashSet<Session<T>>();\n        bool isUp = false;\n        int maxNewConnections = 1;\n        int port;\n        Thread mainLoop;\n        DebugSocket clientSocket;\n        System.IO.MemoryStream sendStream = new System.IO.MemoryStream(64 * 1024);\n        System.IO.BinaryWriter bw;\n        DebugService ds;\n\n        /// <summary>\n        /// 服务器监听的端口\n        /// </summary>\n        public int Port { get { return port; } set { this.port = value; } }\n\n        public DebugSocket Client { get { return clientSocket; } }\n\n        public bool IsAttached { get { return clientSocket != null && !clientSocket.Disconnected; } }\n\n        public DebuggerServer(DebugService ds)\n        {\n            this.ds = ds;\n            bw = new System.IO.BinaryWriter(sendStream);\n        }\n\n        public virtual bool Start()\n        {\n            mainLoop = new Thread(new ThreadStart(this.NetworkLoop));\n            mainLoop.Start();\n\n            this.listener = new TcpListener(port);\n            try { listener.Start(); }\n            catch\n            {\n                return false;\n            }\n            isUp = true;\n            return true;\n        }\n\n        public virtual void Stop()\n        {\n            isUp = false;\n            if (this.listener != null)\n                this.listener.Stop();\n            mainLoop.Abort();\n            mainLoop = null;\n        }\n\n        void NetworkLoop()\n        {\n            while (true)\n            {\n                try\n                {\n                    // let new clients (max 10) connect\n                    if (isUp && clientSocket == null)\n                    {\n                        for (int i = 0; listener.Pending() && i < maxNewConnections; i++)\n                        {\n                            CreateNewSession(listener);\n                        }\n                    }\n                    System.Threading.Thread.Sleep(1);\n                }\n                catch (ThreadAbortException)\n                {\n                }\n                catch (Exception)\n                {\n                    \n                }\n            }\n        }\n\n        void CreateNewSession(TcpListener listener)\n        {\n            Socket sock = listener.AcceptSocket();\n            clientSocket = new DebugSocket(sock);           \n            clientSocket.OnReciveMessage = OnReceive;\n            clientSocket.OnClose = OnClose;\n            ClientConnected();\n        }\n\n        void ClientConnected()\n        {\n\n        }\n\n        void OnClose()\n        {\n            ds.Detach();\n            clientSocket = null;\n        }\n\n        void OnReceive(DebugMessageType type, byte[] buffer)\n        {\n            if (clientSocket == null || clientSocket.Disconnected)\n                return;\n            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);\n            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);\n\n            switch (type)\n            {\n                case DebugMessageType.CSAttach:\n                    {\n                        SendAttachResult();\n                    }\n                    break;\n                case DebugMessageType.CSBindBreakpoint:\n                    {\n                        CSBindBreakpoint msg = new Protocol.CSBindBreakpoint();\n                        msg.BreakpointHashCode = br.ReadInt32();\n                        msg.TypeName = br.ReadString();\n                        msg.MethodName = br.ReadString();\n                        msg.StartLine = br.ReadInt32();\n                        msg.EndLine = br.ReadInt32();\n                        TryBindBreakpoint(msg);\n                    }\n                    break;\n                case DebugMessageType.CSDeleteBreakpoint:\n                    {\n                        CSDeleteBreakpoint msg = new Protocol.CSDeleteBreakpoint();\n                        msg.BreakpointHashCode = br.ReadInt32();\n                        ds.DeleteBreakpoint(msg.BreakpointHashCode);\n                    }\n                    break;\n                case DebugMessageType.CSExecute:\n                    {\n                        CSExecute msg = new Protocol.CSExecute();\n                        msg.ThreadHashCode = br.ReadInt32();\n                        ds.ExecuteThread(msg.ThreadHashCode);\n                    }\n                    break;\n                case DebugMessageType.CSStep:\n                    {\n                        CSStep msg = new CSStep();\n                        msg.ThreadHashCode = br.ReadInt32();\n                        msg.StepType = (StepTypes)br.ReadByte();\n                        ds.StepThread(msg.ThreadHashCode, msg.StepType);\n                    }\n                    break;\n                case DebugMessageType.CSResolveVariable:\n                    {\n                        CSResolveVariable msg = new CSResolveVariable();\n                        msg.Name = br.ReadString();\n                        msg.Parent = ReadVariableReference(br);\n                        var info = ds.ResolveVariable(msg.Parent, msg.Name);\n                    }\n                    break;\n            }\n\n        }\n\n        VariableReference ReadVariableReference(System.IO.BinaryReader br)\n        {\n            VariableReference res = null;\n            if (br.ReadBoolean())\n            {\n                res = new Debugger.VariableReference();\n                res.Address = br.ReadInt64();\n                res.Type = (VariableTypes)br.ReadByte();\n                res.Offset = br.ReadInt32();\n                res.Parent = ReadVariableReference(br);\n            }\n            return res;\n        }\n\n        void SendAttachResult()\n        {\n            sendStream.Position = 0;\n            bw.Write((byte)AttachResults.OK);\n            bw.Write(Version);\n            DoSend(DebugMessageType.SCAttachResult);\n            lock (ds.AppDomain.FreeIntepreters)\n            {\n                foreach (var i in ds.AppDomain.Intepreters)\n                {\n                    SendSCThreadStarted(i.Key);\n                }\n            }\n        }\n\n        void DoSend(DebugMessageType type)\n        {\n            if (clientSocket != null && !clientSocket.Disconnected)\n                clientSocket.Send(type, sendStream.GetBuffer(), (int)sendStream.Position);\n        }\n\n        void TryBindBreakpoint(CSBindBreakpoint msg)\n        {\n            var domain = ds.AppDomain;\n            SCBindBreakpointResult res = new Protocol.SCBindBreakpointResult();\n            res.BreakpointHashCode = msg.BreakpointHashCode;\n            IType type;\n            if (domain.LoadedTypes.TryGetValue(msg.TypeName, out type))\n            {\n                if(type is ILType)\n                {\n                    ILType it = (ILType)type;\n                    ILMethod found = null;\n                    foreach(var i in it.GetMethods())\n                    {\n                        if(i.Name == msg.MethodName)\n                        {\n                            ILMethod ilm = (ILMethod)i;\n                            if (ilm.StartLine <= (msg.StartLine + 1) && ilm.EndLine >= (msg.StartLine + 1))\n                            {\n                                found = ilm;\n                                break;\n                            }\n                        }\n                    }\n                    if(found != null)\n                    {\n                        ds.SetBreakPoint(found.GetHashCode(), msg.BreakpointHashCode, msg.StartLine);\n                        res.Result = BindBreakpointResults.OK;\n                    }\n                    else\n                    {\n                        res.Result = BindBreakpointResults.CodeNotFound;\n                    }\n                }\n                else\n                {\n                    res.Result = BindBreakpointResults.TypeNotFound;\n                }\n            }\n            else\n            {\n                res.Result = BindBreakpointResults.TypeNotFound;\n            }\n            SendSCBindBreakpointResult(res);\n        }\n\n        void SendSCBindBreakpointResult(SCBindBreakpointResult msg)\n        {\n            sendStream.Position = 0;\n            bw.Write(msg.BreakpointHashCode);\n            bw.Write((byte)msg.Result);\n            DoSend(DebugMessageType.SCBindBreakpointResult);\n        }\n\n        internal void SendSCBreakpointHit(int intpHash, int bpHash, KeyValuePair<int, StackFrameInfo[]>[] info)\n        {\n            sendStream.Position = 0;\n            bw.Write(bpHash);\n            bw.Write(intpHash);\n            WriteStackFrames(info);\n            DoSend(DebugMessageType.SCBreakpointHit);\n        }\n\n        internal void SendSCStepComplete(int intpHash, KeyValuePair<int, StackFrameInfo[]>[] info)\n        {\n            sendStream.Position = 0;\n            bw.Write(intpHash);\n            WriteStackFrames(info);\n            DoSend(DebugMessageType.SCStepComplete);\n        }\n\n        void SendSCResolveVariableResult(VariableInfo info)\n        {\n            sendStream.Position = 0;\n            WriteVariableInfo(info);\n            DoSend(DebugMessageType.SCResolveVariableResult);\n        }\n\n        void WriteStackFrames(KeyValuePair<int, StackFrameInfo[]>[] info)\n        {\n            bw.Write(info.Length);\n            foreach (var i in info)\n            {\n                bw.Write(i.Key);\n                bw.Write(i.Value.Length);\n                foreach (var j in i.Value)\n                {\n                    bw.Write(j.MethodName);\n                    bw.Write(j.DocumentName);\n                    bw.Write(j.StartLine);\n                    bw.Write(j.StartColumn);\n                    bw.Write(j.EndLine);\n                    bw.Write(j.EndColumn);\n                    bw.Write(j.LocalVariables.Length);\n                    foreach (var k in j.LocalVariables)\n                    {\n                        WriteVariableInfo(k);\n                    }\n                }\n            }\n        }\n\n        void WriteVariableInfo(VariableInfo k)\n        {\n            bw.Write(k.Address);\n            bw.Write((byte)k.Type);\n            bw.Write(k.Offset);\n            bw.Write(k.Name);\n            bw.Write(k.Value);\n            bw.Write(k.TypeName);\n            bw.Write(k.Expandable);\n        }\n\n        internal void SendSCThreadStarted(int threadHash)\n        {\n            sendStream.Position = 0;\n            bw.Write(threadHash);\n            DoSend(DebugMessageType.SCThreadStarted);\n        }\n\n        internal void SendSCThreadEnded(int threadHash)\n        {\n            sendStream.Position = 0;\n            bw.Write(threadHash);\n            DoSend(DebugMessageType.SCThreadEnded);\n        }\n\n        public void NotifyModuleLoaded(string modulename)\n        {\n            sendStream.Position = 0;\n            bw.Write(modulename);\n            DoSend(DebugMessageType.SCModuleLoaded);\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSBindBreakpoint.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class CSBindBreakpoint\n    {\n        public int BreakpointHashCode { get; set; }\n        public string TypeName { get; set; }\n        public string MethodName { get; set; }\n        public int StartLine { get; set; }\n        public int EndLine { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSDeleteBreakpoint.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class CSDeleteBreakpoint\n    {\n        public int BreakpointHashCode { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSExecute.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class CSExecute\n    {\n        public int ThreadHashCode { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSResolveVariable.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class CSResolveVariable\n    {\n        public string Name { get; set; }\n        public VariableReference Parent { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSStep.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class CSStep\n    {\n        public int ThreadHashCode { get; set; }\n        public StepTypes StepType { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/SCAttachResult.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public enum AttachResults\n    {\n        OK,\n        AlreadyAttached,\n    }\n    public class SCAttachResult\n    {\n        public AttachResults Result { get; set; }\n        public int DebugServerVersion { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/SCBindBreakpointResult.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public enum BindBreakpointResults\n    {\n        OK,\n        TypeNotFound,\n        CodeNotFound,\n    }\n    public class SCBindBreakpointResult\n    {\n        public int BreakpointHashCode { get; set; }\n        public BindBreakpointResults Result { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/SCBreakpointHit.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class SCBreakpointHit\n    {\n        public int BreakpointHashCode { get; set; }\n        public int ThreadHashCode { get; set; }\n        public KeyValuePair<int, StackFrameInfo[]>[] StackFrame { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/SCModuleLoaded.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class SCModuleLoaded\n    {\n        public string ModuleName { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/SCResolveVariableResult.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class SCResolveVariableResult\n    {\n        public VariableInfo Info { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/SCStepComplete.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class SCStepComplete\n    {\n        public int ThreadHashCode { get; set; }\n        public KeyValuePair<int, StackFrameInfo[]>[] StackFrame { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/Protocol/SCThreadStarted.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class SCThreadStarted\n    {\n        public int ThreadHashCode { get; set; }\n    }\n    public class SCThreadEnded\n    {\n        public int ThreadHashCode { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/StackFrameInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public class StackFrameInfo\n    {\n        public string MethodName { get; set; }\n        public string DocumentName { get; set; }\n        public int StartLine { get; set; }\n        public int StartColumn { get; set; }\n        public int EndLine { get; set; }\n        public int EndColumn { get; set; }\n        public VariableInfo[] LocalVariables { get; set; }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/StepTypes.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public enum StepTypes\n    {\n        None,\n        Into,\n        Over,\n        Out,\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Debugger/VariableInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public enum VariableTypes\n    {\n        Normal,\n        FieldReference,\n        Error,\n    }\n\n    public class VariableReference\n    {\n        public long Address { get; set; }\n        public VariableTypes Type { get; set; }\n        public int Offset { get; set; }\n        public VariableReference Parent { get; set; }\n    }\n\n    public class VariableInfo\n    {\n        public long Address { get; set; }\n        public VariableTypes Type { get; set; }\n        public string Name { get; set; }\n        public string TypeName { get; set; }\n        public string Value { get; set; }\n        public bool Expandable { get; set; }\n        public int Offset { get; set;}\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Enviorment/AppDomain.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\nusing Mono.Cecil;\nusing System.Reflection;\nusing Mono.Cecil.Cil;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.Utils;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Debugger;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Other;\nnamespace ILRuntime.Runtime.Enviorment\n{\n    public unsafe delegate StackObject* CLRRedirectionDelegate(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj);\n    public delegate object CLRFieldGetterDelegate(ref object target);\n    public delegate void CLRFieldSetterDelegate(ref object target, object value);\n    public delegate object CLRMemberwiseCloneDelegate(ref object target);\n    public delegate object CLRCreateDefaultInstanceDelegate();\n    public delegate object CLRCreateArrayInstanceDelegate(int size);\n\n    public class AppDomain\n    {\n        Queue<ILIntepreter> freeIntepreters = new Queue<ILIntepreter>();\n        Dictionary<int, ILIntepreter> intepreters = new Dictionary<int, ILIntepreter>();\n        Dictionary<Type, CrossBindingAdaptor> crossAdaptors = new Dictionary<Type, CrossBindingAdaptor>(new ByReferenceKeyComparer<Type>());\n        Dictionary<Type, ValueTypeBinder> valueTypeBinders = new Dictionary<Type, ValueTypeBinder>();\n        ThreadSafeDictionary<string, IType> mapType = new ThreadSafeDictionary<string, IType>();\n        Dictionary<Type, IType> clrTypeMapping = new Dictionary<Type, IType>(new ByReferenceKeyComparer<Type>());\n        ThreadSafeDictionary<int, IType> mapTypeToken = new ThreadSafeDictionary<int, IType>();\n        ThreadSafeDictionary<int, IMethod> mapMethod = new ThreadSafeDictionary<int, IMethod>();\n        ThreadSafeDictionary<long, string> mapString = new ThreadSafeDictionary<long, string>();\n        Dictionary<System.Reflection.MethodBase, CLRRedirectionDelegate> redirectMap = new Dictionary<System.Reflection.MethodBase, CLRRedirectionDelegate>();\n        Dictionary<System.Reflection.FieldInfo, CLRFieldGetterDelegate> fieldGetterMap = new Dictionary<System.Reflection.FieldInfo, CLRFieldGetterDelegate>();\n        Dictionary<System.Reflection.FieldInfo, CLRFieldSetterDelegate> fieldSetterMap = new Dictionary<System.Reflection.FieldInfo, CLRFieldSetterDelegate>();\n        Dictionary<Type, CLRMemberwiseCloneDelegate> memberwiseCloneMap = new Dictionary<Type, CLRMemberwiseCloneDelegate>(new ByReferenceKeyComparer<Type>());\n        Dictionary<Type, CLRCreateDefaultInstanceDelegate> createDefaultInstanceMap = new Dictionary<Type, CLRCreateDefaultInstanceDelegate>(new ByReferenceKeyComparer<Type>());\n        Dictionary<Type, CLRCreateArrayInstanceDelegate> createArrayInstanceMap = new Dictionary<Type, CLRCreateArrayInstanceDelegate>(new ByReferenceKeyComparer<Type>());\n        IType voidType, intType, longType, boolType, floatType, doubleType, objectType;\n        DelegateManager dMgr;\n        Assembly[] loadedAssemblies;\n        Dictionary<string, byte[]> references = new Dictionary<string, byte[]>();\n        DebugService debugService;\n\n        /// <summary>\n        /// Determine if invoking unbinded CLR method(using reflection) is allowed\n        /// </summary>\n        public bool AllowUnboundCLRMethod { get; set; }\n\n#if UNITY_EDITOR\n        public int UnityMainThreadID { get; set; }\n#endif\n        public unsafe AppDomain()\n        {\n            AllowUnboundCLRMethod = true;\n            loadedAssemblies = System.AppDomain.CurrentDomain.GetAssemblies();\n            var mi = typeof(System.Runtime.CompilerServices.RuntimeHelpers).GetMethod(\"InitializeArray\");\n            RegisterCLRMethodRedirection(mi, CLRRedirections.InitializeArray);\n            foreach (var i in typeof(System.Activator).GetMethods())\n            {\n                if (i.Name == \"CreateInstance\" && i.IsGenericMethodDefinition)\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.CreateInstance);\n                }\n                else if(i.Name == \"CreateInstance\" && i.GetParameters().Length == 1)\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.CreateInstance2);\n                }\n            }\n            foreach (var i in typeof(System.Type).GetMethods())\n            {\n                if (i.Name == \"GetType\" && i.IsStatic)\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.GetType);\n                }\n                if(i.Name==\"Equals\" && i.GetParameters()[0].ParameterType == typeof(Type))\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.TypeEquals);\n                }\n            }\n            foreach (var i in typeof(System.Delegate).GetMethods())\n            {\n                if (i.Name == \"Combine\" && i.GetParameters().Length == 2)\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.DelegateCombine);\n                }\n                if(i.Name == \"Remove\")\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.DelegateRemove);\n                }\n                if(i.Name == \"op_Equality\")\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.DelegateEqulity);\n                }\n                if(i.Name == \"op_Inequality\")\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.DelegateInequlity);\n                }\n            }\n            foreach(var i in typeof(MethodBase).GetMethods())\n            {\n                if(i.Name == \"Invoke\" && i.GetParameters().Length == 2)\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.MethodInfoInvoke);\n                }\n            }\n            mi = typeof(System.Type).GetMethod(\"GetTypeFromHandle\");\n            RegisterCLRMethodRedirection(mi, CLRRedirections.GetTypeFromHandle);\n            mi = typeof(object).GetMethod(\"GetType\");\n            RegisterCLRMethodRedirection(mi, CLRRedirections.ObjectGetType);\n            dMgr = new DelegateManager(this);\n            dMgr.RegisterDelegateConvertor<Action>((dele) =>\n            {\n                return dele;\n            });\n\n            RegisterCrossBindingAdaptor(new Adaptors.AttributeAdaptor());\n\n            debugService = new Debugger.DebugService(this);\n        }\n\n        public IType VoidType { get { return voidType; } }\n        public IType IntType { get { return intType; } }\n        public IType LongType { get { return longType; } }\n        public IType BoolType { get { return boolType; } }\n        public IType FloatType { get { return floatType; } }\n        public IType DoubleType { get { return doubleType; } }\n        public IType ObjectType { get { return objectType; } }\n\n        /// <summary>\n        /// Attention, this property isn't thread safe\n        /// </summary>\n        public Dictionary<string, IType> LoadedTypes { get { return mapType.InnerDictionary; } }\n        internal Dictionary<MethodBase, CLRRedirectionDelegate> RedirectMap { get { return redirectMap; } }\n        internal Dictionary<FieldInfo, CLRFieldGetterDelegate> FieldGetterMap { get { return fieldGetterMap; } }\n        internal Dictionary<FieldInfo, CLRFieldSetterDelegate> FieldSetterMap { get { return fieldSetterMap; } }\n        internal Dictionary<Type, CLRMemberwiseCloneDelegate> MemberwiseCloneMap { get { return memberwiseCloneMap; } }\n        internal Dictionary<Type, CLRCreateDefaultInstanceDelegate> CreateDefaultInstanceMap { get { return createDefaultInstanceMap; } }\n        internal Dictionary<Type, CLRCreateArrayInstanceDelegate> CreateArrayInstanceMap { get { return createArrayInstanceMap; } }\n        internal Dictionary<Type, CrossBindingAdaptor> CrossBindingAdaptors { get { return crossAdaptors; } }\n        internal Dictionary<Type, ValueTypeBinder> ValueTypeBinders { get { return valueTypeBinders; } }\n        public DebugService DebugService { get { return debugService; } }\n        internal Dictionary<int, ILIntepreter> Intepreters { get { return intepreters; } }\n        internal Queue<ILIntepreter> FreeIntepreters { get { return freeIntepreters; } }\n\n        public DelegateManager DelegateManager { get { return dMgr; } }\n\n        \n        /// <summary>\n        /// 加载Assembly 文件，从指定的路径\n        /// </summary>\n        /// <param name=\"path\">路径</param>\n        public void LoadAssemblyFile(string path)\n        {\n            FileInfo file = new FileInfo(path);\n\n            if (!file.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"Assembly File not find!:\\r\\n{0}\", path));\n            }\n            else\n            {\n                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))\n                {\n                    LoadAssembly(fs);\n\n                    fs.Dispose();\n                }\n            }\n        }\n\n#if USE_MDB || USE_PDB\n        /// <summary>\n        /// 加载Assembly 文件和PDB文件或MDB文件，从指定的路径（PDB和MDB文件按默认命名方式，并且和Assembly文件处于同一目录中\n        /// </summary>\n        /// <param name=\"path\">路径</param>\n        public void LoadAssemblyFileAndSymbol(string path)\n        {\n            FileInfo file = new FileInfo(path);\n\n            if (!file.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"Assembly File not find!:\\r\\n{0}\", path));\n            }\n            else\n            {\n                var dlldir = file.DirectoryName;\n                var assname = Path.GetFileNameWithoutExtension(file.Name);\n                var pdbpath = string.Format(\"{0}/{1}.pdb\",dlldir,assname);\n                var mdbpath = string.Format(\"{0}/{1}.mdb\", dlldir, assname);\n\n                string symbolPath = \"\";\n\n                bool isPDB = true;\n                if (File.Exists(pdbpath))\n                {\n                    symbolPath = pdbpath;\n                }\n                else if (File.Exists(mdbpath))\n                {\n                    symbolPath = mdbpath;\n                    isPDB = false;\n                }\n\n\n                if (string.IsNullOrEmpty(symbolPath))\n                {\n                    throw new FileNotFoundException(string.Format(\"symbol file not find!:\\r\\ncheck:\\r\\n{0}\\r\\n{1}\\r\\n\", pdbpath,mdbpath));\n                }\n\n                using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))\n                {                  \n                    \n                    using (var pdbfs = new System.IO.FileStream(symbolPath, FileMode.Open))\n                    {\n                        if (isPDB)\n                        {\n                            LoadAssemblyPDB(fs, pdbfs);\n                        }\n                        else\n                        {\n                            LoadAssemblyMDB(fs, pdbfs);\n                        }\n                    }\n                }\n            }\n        }\n#endif\n\n#if USE_PDB\n        /// <summary>\n        /// 加载Assembly 文件和PDB文件，两者都从指定的路径\n        /// </summary>\n        /// <param name=\"assemblyFilePath\">Assembly 文件路径</param>\n        /// <param name=\"symbolFilePath\">symbol文件路径</param>\n        public void LoadAssemblyFileAndPDB(string assemblyFilePath,string symbolFilePath)\n        {\n            FileInfo assfile = new FileInfo(assemblyFilePath);\n            FileInfo pdbfile = new FileInfo(symbolFilePath);\n            if (!assfile.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"Assembly File not find!:\\r\\n{0}\", assemblyFilePath));\n            }\n\n            if (!pdbfile.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"symbol file not find!:\\r\\n{0}\", symbolFilePath));\n            }\n\n            using (FileStream fs = new FileStream(assfile.FullName, FileMode.Open, FileAccess.Read))\n            {\n\n                using (var pdbfs = new System.IO.FileStream(pdbfile.FullName, FileMode.Open))\n                {\n                    LoadAssemblyPDB(fs, pdbfs);\n                }\n            }\n\n        }\n\n        /// <summary>\n        ///  从流加载Assembly,以及symbol符号文件(pdb)\n        /// </summary>\n        /// <param name=\"stream\">Assembly Stream</param>\n        /// <param name=\"symbol\">PDB Stream</param>\n        public void LoadAssemblyPDB(System.IO.Stream stream, System.IO.Stream symbol)\n        {\n            LoadAssembly(stream, symbol, new Mono.Cecil.Pdb.PdbReaderProvider());\n        }\n\n#endif\n\n#if USE_MDB\n        /// <summary>\n        /// 加载Assembly 文件和MDB文件，两者都从指定的路径\n        /// </summary>\n        /// <param name=\"assemblyFilePath\">Assembly 文件路径</param>\n        /// <param name=\"symbolFilePath\">symbol文件路径</param>\n        public void LoadAssemblyFileAndMDB(string assemblyFilePath, string symbolFilePath)\n        {\n            FileInfo assfile = new FileInfo(assemblyFilePath);\n            FileInfo pdbfile = new FileInfo(symbolFilePath);\n            if (!assfile.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"Assembly File not find!:\\r\\n{0}\", assemblyFilePath));\n            }\n\n            if (!pdbfile.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"symbol file not find!:\\r\\n{0}\", symbolFilePath));\n            }\n\n            using (FileStream fs = new FileStream(assfile.FullName, FileMode.Open, FileAccess.Read))\n            {\n\n                using (var pdbfs = new System.IO.FileStream(pdbfile.FullName, FileMode.Open))\n                {\n                    LoadAssemblyMDB(fs, pdbfs);\n                }\n            }\n        }\n\n        /// <summary>\n        ///  从流加载Assembly,以及symbol符号文件(Mdb)\n        /// </summary>\n        /// <param name=\"stream\">Assembly Stream</param>\n        /// <param name=\"symbol\">PDB Stream</param>\n        public void LoadAssemblyMDB(System.IO.Stream stream, System.IO.Stream symbol)\n        {\n            LoadAssembly(stream, symbol, new Mono.Cecil.Mdb.MdbReaderProvider());\n        }\n#endif\n        /// <summary>\n        /// 从流加载Assembly 不加载symbol符号文件\n        /// </summary>\n        /// <param name=\"stream\">Dll数据流</param>\n        public void LoadAssembly(System.IO.Stream stream)\n        {\n            LoadAssembly(stream, null, null);\n        }        \n\n        /// <summary>\n        /// 从流加载Assembly,以及symbol符号文件(pdb)\n        /// </summary>\n        /// <param name=\"stream\">Assembly Stream</param>\n        /// <param name=\"symbol\">symbol Stream</param>\n        /// <param name=\"symbolReader\">symbol 读取器</param>\n        public void LoadAssembly(System.IO.Stream stream, System.IO.Stream symbol, ISymbolReaderProvider symbolReader)\n        {\n            var module = ModuleDefinition.ReadModule(stream); //从MONO中加载模块\n\n            if (symbolReader != null && symbol != null) \n            {\n                module.ReadSymbols(symbolReader.GetSymbolReader(module, symbol)); //加载符号表\n            }\n\n            if (module.HasAssemblyReferences) //如果此模块引用了其他模块\n            {\n                foreach (var ar in module.AssemblyReferences)\n                {\n                    /*if (moduleref.Contains(ar.Name) == false)\n                        moduleref.Add(ar.Name);\n                    if (moduleref.Contains(ar.FullName) == false)\n                        moduleref.Add(ar.FullName);*/\n                }\n            }\n\n            if (module.HasTypes)\n            {\n                List<ILType> types = new List<ILType>();\n\n                foreach (var t in module.GetTypes()) //获取所有此模块定义的类型\n                {\n                    ILType type = new ILType(t, this);\n\n                    mapType[t.FullName] = type;\n                    types.Add(type);\n\n                }\n            }\n\n            if (voidType == null)\n            {\n                voidType = GetType(\"System.Void\");\n                intType = GetType(\"System.Int32\");\n                longType = GetType(\"System.Int64\");\n                boolType = GetType(\"System.Boolean\");\n                floatType = GetType(\"System.Single\");\n                doubleType = GetType(\"System.Double\");\n                objectType = GetType(\"System.Object\");\n            }\n            module.AssemblyResolver.ResolveFailure += AssemblyResolver_ResolveFailure;\n#if DEBUG\n            debugService.NotifyModuleLoaded(module.Name);\n#endif\n        }\n\n        /// <summary>\n        /// External reference should be added to the AppDomain by the method\n        /// </summary>\n        /// <param name=\"name\">Assembly name, without .dll</param>\n        /// <param name=\"content\">file content</param>\n        public void AddReferenceBytes(string name, byte[] content)\n        {\n            references[name] = content;\n        }\n\n        private AssemblyDefinition AssemblyResolver_ResolveFailure(object sender, AssemblyNameReference reference)\n        {\n            byte[] content;\n            if (references.TryGetValue(reference.Name, out content))\n            {\n                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(content))\n                {\n                    return AssemblyDefinition.ReadAssembly(ms);\n                }\n            }\n            else\n                return null;\n        }\n\n        public void RegisterCLRMethodRedirection(MethodBase mi, CLRRedirectionDelegate func)\n        {\n            if (!redirectMap.ContainsKey(mi))\n                redirectMap[mi] = func;\n        }\n\n        public void RegisterCLRFieldGetter(FieldInfo f, CLRFieldGetterDelegate getter)\n        {\n            if (!fieldGetterMap.ContainsKey(f))\n                fieldGetterMap[f] = getter;\n        }\n\n        public void RegisterCLRFieldSetter(FieldInfo f, CLRFieldSetterDelegate setter)\n        {\n            if (!fieldSetterMap.ContainsKey(f))\n                fieldSetterMap[f] = setter;\n        }\n\n        public void RegisterCLRMemberwiseClone(Type t, CLRMemberwiseCloneDelegate memberwiseClone)\n        {\n            if (!memberwiseCloneMap.ContainsKey(t))\n                memberwiseCloneMap[t] = memberwiseClone;\n        }\n\n        public void RegisterCLRCreateDefaultInstance(Type t, CLRCreateDefaultInstanceDelegate createDefaultInstance)\n        {\n            if (!createDefaultInstanceMap.ContainsKey(t))\n                createDefaultInstanceMap[t] = createDefaultInstance;\n        }\n\n        public void RegisterCLRCreateArrayInstance(Type t, CLRCreateArrayInstanceDelegate createArray)\n        {\n            if (!createArrayInstanceMap.ContainsKey(t))\n                createArrayInstanceMap[t] = createArray;\n        }\n\n        public void RegisterValueTypeBinder(Type t, ValueTypeBinder binder)\n        {\n            if (!valueTypeBinders.ContainsKey(t))\n            {\n                valueTypeBinders[t] = binder;\n                binder.RegisterCLRRedirection(this);\n            }\n        }\n\n        /// <summary>\n        /// 更近类型名称返回类型\n        /// </summary>\n        /// <param name=\"fullname\">类型全名 命名空间.类型名</param>\n        /// <returns></returns>\n        public IType GetType(string fullname)\n        {\n            IType res;\n            if (fullname == null)\n            {\n                return null;\n            }\n\n            if (mapType.TryGetValue(fullname, out res))\n                return res;\n\n\n            string baseType;\n            List<string> genericParams;\n            bool isArray;\n\n            ParseGenericType(fullname, out baseType, out genericParams, out isArray);\n\n\n            bool isByRef = baseType.EndsWith(\"&\");\n            if (isByRef)\n                baseType = baseType.Substring(0, baseType.Length - 1);\n            if (genericParams != null || isArray || isByRef)\n            {\n                IType bt = GetType(baseType);\n                if (bt == null)\n                {\n                    bt = GetType(baseType.Replace(\"/\", \"+\"));\n                }\n\n                if (bt == null)\n                    return null;\n                if (genericParams != null)\n                {\n                    KeyValuePair<string, IType>[] genericArguments = new KeyValuePair<string, IType>[genericParams.Count];\n                    for (int i = 0; i < genericArguments.Length; i++)\n                    {\n                        string key = \"!\" + i;\n                        IType val = GetType(genericParams[i]);\n                        if (val == null)\n                            return null;\n                        genericArguments[i] = new KeyValuePair<string, IType>(key, val);\n                    }\n                    bt = bt.MakeGenericInstance(genericArguments);\n                    mapType[bt.FullName] = bt;\n                    mapTypeToken[bt.GetHashCode()] = bt;\n                    StringBuilder sb = new StringBuilder();\n                    sb.Append(baseType);\n                    sb.Append('<');\n                    for (int i = 0; i < genericParams.Count; i++)\n                    {\n                        if (i > 0)\n                            sb.Append(\",\");\n                        if (genericParams[i].Contains(\",\"))\n                            sb.Append(genericParams[i].Substring(0, genericParams[i].IndexOf(',')));\n                        else\n                            sb.Append(genericParams[i]);\n                    }\n                    sb.Append('>');\n                    var asmName = sb.ToString();\n                    if (bt.FullName != asmName)\n                        mapType[asmName] = bt;\n                }\n\n                if (isArray)\n                {\n                    bt = bt.MakeArrayType();\n                    mapType[bt.FullName] = bt;\n                    mapTypeToken[bt.GetHashCode()] = bt;\n                    if (!isByRef)\n                    {\n                        mapType[fullname] = bt;\n                        return bt;\n                    }\n                }\n\n                if (isByRef)\n                {\n                    res = bt.MakeByRefType();\n                    mapType[fullname] = res;\n                    mapType[res.FullName] = res;\n                    mapTypeToken[res.GetHashCode()] = res;\n                    return res;\n                }\n                else\n                {\n                    mapType[fullname] = bt;\n                    return bt;\n                }\n            }\n            else\n            {\n                Type t = Type.GetType(fullname);\n                if (t != null)\n                {\n                    if (!clrTypeMapping.TryGetValue(t, out res))\n                    {\n                        res = new CLRType(t, this);\n                        clrTypeMapping[t] = res;\n                    }\n                    mapType[fullname] = res;\n                    mapType[res.FullName] = res;\n                    mapType[t.AssemblyQualifiedName] = res;\n                    mapTypeToken[res.GetHashCode()] = res;\n                    return res;\n                }\n            }\n            return null;\n        }\n\n        internal static void ParseGenericType(string fullname, out string baseType, out List<string> genericParams, out bool isArray)\n        {\n            StringBuilder sb = new StringBuilder();\n            int depth = 0;\n            baseType = \"\";\n            genericParams = null;\n            if (fullname.Length >2 && fullname.Substring(fullname.Length - 2) == \"[]\")\n            {\n                fullname = fullname.Substring(0, fullname.Length - 2);\n                isArray = true;\n            }\n            else\n                isArray = false;\n            if (fullname.Contains('<') || fullname.Contains('['))\n            {\n                foreach (var i in fullname)\n                {\n                    if (i == '<' || i == '[')\n                    {\n                        depth++;\n                        if (depth == 1)\n                        {\n                            baseType = sb.ToString();\n                            sb.Length = 0;\n                            genericParams = new List<string>();\n                            continue;\n                        }\n                    }\n                    if (i == ',' && depth == 1)\n                    {\n                        string name = sb.ToString();\n                        if (name.StartsWith(\"[\"))\n                            name = name.Substring(1, name.Length - 2);\n                        if (!string.IsNullOrEmpty(name))\n                            genericParams.Add(name);\n                        sb.Length = 0;\n                        continue;\n                    }\n                    if (i == '>' || i == ']')\n                    {\n                        depth--;\n                        if (depth == 0)\n                        {\n                            string name = sb.ToString();\n                            if (name.StartsWith(\"[\"))\n                                name = name.Substring(1, name.Length - 2);\n                            if (!string.IsNullOrEmpty(name))\n                                genericParams.Add(name);\n                            else\n                            {\n                                if (!isArray)\n                                {\n                                    isArray = true;\n                                }\n                                else\n                                {\n                                    baseType += \"[]\";\n                                }\n                            }\n                            sb.Length = 0;\n                            continue;\n                        }\n                    }\n                    sb.Append(i);\n                }\n                if (sb.Length > 0)\n                {\n                    baseType += sb.ToString();\n                }\n                if (genericParams != null && genericParams.Count == 0)\n                    genericParams = null;\n            }\n            else\n                baseType = fullname;\n        }\n\n        string GetAssemblyName(IMetadataScope scope)\n        {\n            return scope is AssemblyNameReference ? ((AssemblyNameReference)scope).FullName : null;\n        }\n\n        internal IType GetType(object token, IType contextType, IMethod contextMethod)\n        {\n            int hash = token.GetHashCode();\n            IType res;\n            if (mapTypeToken.TryGetValue(hash, out res))\n                return res;\n            Mono.Cecil.ModuleDefinition module = null;\n            KeyValuePair<string, IType>[] genericArguments = null;\n            string typename = null;\n            string scope = null;\n            bool dummyGenericInstance = false;\n            if (token is Mono.Cecil.TypeDefinition)\n            {\n                Mono.Cecil.TypeDefinition _def = (token as Mono.Cecil.TypeDefinition);\n                module = _def.Module;\n                typename = _def.FullName;\n                scope = GetAssemblyName(_def.Scope);\n            }\n            else if (token is Mono.Cecil.TypeReference)\n            {\n                Mono.Cecil.TypeReference _ref = (token as Mono.Cecil.TypeReference);\n                if (_ref.IsGenericParameter)\n                {\n                    IType t = null;\n                    if (contextType != null)\n                    {\n                        t = contextType.FindGenericArgument(_ref.Name);\n                    }\n                    if (t == null && contextMethod != null && contextMethod is ILMethod)\n                    {\n                        t = ((ILMethod)contextMethod).FindGenericArgument(_ref.Name);\n                    }\n                    return t;\n                }\n                if (_ref.IsByReference)\n                {\n                    var et = _ref.GetElementType();\n                    bool valid = !et.IsGenericParameter;\n                    var t = GetType(et, contextType, contextMethod);\n                    if (t != null)\n                    {\n                        res = t.MakeByRefType();\n                        if (res is ILType && valid)\n                        {\n                            ///Unify the TypeReference\n                            ((ILType)res).TypeReference = _ref;\n                        }\n                        if (valid)\n                            mapTypeToken[hash] = res;\n                        if (!string.IsNullOrEmpty(res.FullName))\n                            mapType[res.FullName] = res;\n                        return res;\n                    }\n                    return null;\n                }\n                if (_ref.IsArray)\n                {\n                    var t = GetType(_ref.GetElementType(), contextType, contextMethod);\n                    if (t != null)\n                    {\n                        res = t.MakeArrayType();\n                        if (res is ILType)\n                        {\n                            ///Unify the TypeReference\n                            ((ILType)res).TypeReference = _ref;\n                        }\n                        mapTypeToken[hash] = res;\n                        if (!string.IsNullOrEmpty(res.FullName))\n                            mapType[res.FullName] = res;\n                        return res;\n                    }\n                    return t;\n                }\n                module = _ref.Module;\n                if (_ref.IsGenericInstance)\n                {\n                    GenericInstanceType gType = (GenericInstanceType)_ref;\n                    typename = gType.ElementType.FullName;\n                    scope = GetAssemblyName(gType.ElementType.Scope);\n                    TypeReference tr = gType.ElementType;\n                    genericArguments = new KeyValuePair<string, IType>[gType.GenericArguments.Count];\n                    for (int i = 0; i < genericArguments.Length; i++)\n                    {\n                        string key = tr.GenericParameters[i].Name;\n                        IType val;\n                        if (gType.GenericArguments[i].IsGenericParameter)\n                        {\n                            val = contextType.FindGenericArgument(gType.GenericArguments[i].Name);\n                            dummyGenericInstance = true;\n                            if (val == null)\n                            {\n                                if (contextMethod != null && contextMethod is ILMethod)\n                                {\n                                    val = ((ILMethod)contextMethod).FindGenericArgument(gType.GenericArguments[i].Name);\n                                }\n                                else\n                                    return null;\n                            }\n                        }\n                        else\n                            val = GetType(gType.GenericArguments[i], contextType, contextMethod);\n                        if (val != null && val.HasGenericParameter)\n                            dummyGenericInstance = true;\n                        if (val != null)\n                            genericArguments[i] = new KeyValuePair<string, IType>(key, val);\n                        else\n                        {\n                            genericArguments = null;\n                            break;\n                        }\n                    }\n                }\n                else\n                {\n                    typename = _ref.FullName;\n                    scope = GetAssemblyName(_ref.Scope);\n                }\n            }\n            else\n            {\n                throw new NotImplementedException();\n            }\n            res = GetType(typename);\n            if (res == null)\n            {\n                typename = typename.Replace(\"/\", \"+\");\n                res = GetType(typename);\n            }\n            if (res == null && scope != null)\n                res = GetType(typename + \", \" + scope);\n            if (res == null)\n            {\n                if (scope != null)\n                {\n                    string aname = scope.Split(',')[0];\n                    foreach (var i in loadedAssemblies)\n                    {\n                        if (aname == i.GetName().Name)\n                        {\n                            res = GetType(typename + \", \" + i.FullName);\n                            if (res != null)\n                                break;\n                        }\n                    }\n                }\n                if (res == null)\n                {\n                    foreach (var j in loadedAssemblies)\n                    {\n                        res = GetType(typename + \", \" + j.FullName);\n                        if (res != null)\n                            break;\n                    }\n                }\n                if (res != null && scope != null)\n                {\n                    mapType[typename + \", \" + scope] = res;\n                }\n            }\n            if (res == null)\n                throw new KeyNotFoundException(\"Cannot find Type:\" + typename);\n            if (genericArguments != null)\n            {\n                res = res.MakeGenericInstance(genericArguments);\n                if (!dummyGenericInstance && res is ILType)\n                {\n                    ((ILType)res).TypeReference = (TypeReference)token;\n                }\n                if (!string.IsNullOrEmpty(res.FullName))\n                {\n                    if (res is CLRType || !((ILType)res).TypeReference.HasGenericParameters)\n                        mapType[res.FullName] = res;\n                }\n            }\n            mapTypeToken[res.GetHashCode()] = res;\n            if (!dummyGenericInstance)\n                mapTypeToken[hash] = res;\n            return res;\n        }\n\n        public IType GetType(int hash)\n        {\n            IType res;\n            if (mapTypeToken.TryGetValue(hash, out res))\n                return res;\n            else\n                return null;\n        }\n\n        /// <summary>\n        /// 根据CLR类型获取 IL类型\n        /// </summary>\n        /// <param name=\"t\"></param>\n        /// <returns></returns>\n        public IType GetType(Type t)\n        {\n            IType res;\n            if (clrTypeMapping.TryGetValue(t, out res))\n                return res;\n            else\n                return GetType(t.AssemblyQualifiedName);\n        }\n\n        /// <summary>\n        /// Create a instance of the specified type, which is inherited from a CLR Type\n        /// </summary>\n        /// <typeparam name=\"T\">CLR Type</typeparam>\n        /// <param name=\"type\">Full Name of the type</param>\n        /// <param name=\"args\">Arguments for the constructor</param>\n        /// <returns></returns>\n        public T Instantiate<T>(string type, object[] args = null)\n        {\n            ILTypeInstance ins = Instantiate(type, args);\n            return (T)ins.CLRInstance;\n        }\n\n        /// <summary>\n        /// Create a instance of the specified type\n        /// </summary>\n        /// <param name=\"type\">Full Name of the type</param>\n        /// <param name=\"args\">Arguments for the constructor</param>\n        /// <returns></returns>\n        public ILTypeInstance Instantiate(string type, object[] args = null)\n        {\n            IType t;\n            if (mapType.TryGetValue(type, out t))\n            {\n                ILType ilType = t as ILType;\n                if(ilType != null)\n                {\n                    bool hasConstructor = args != null && args.Length != 0;\n                    var res = ilType.Instantiate(!hasConstructor);\n                    if (hasConstructor)\n                    {\n                        var ilm = ilType.GetConstructor(args.Length);\n                        Invoke(ilm, res, args);\n                    }\n                    return res;\n                }\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Invoke a method\n        /// </summary>\n        /// <param name=\"type\">Type's fullname</param>\n        /// <param name=\"method\">Method name</param>\n        /// <param name=\"p\">Parameters</param>\n        /// <returns></returns>\n        public object Invoke(string type, string method, object instance, params object[] p)\n        {\n            IType t = GetType(type);\n            if (t == null)\n                return null;\n            var m = t.GetMethod(method, p != null ? p.Length : 0);            \n            if (m != null)\n            {\n                for(int i = 0; i < m.ParameterCount; i++)\n                {\n                    if (p[i] == null)\n                        continue;\n                    if (!m.Parameters[i].TypeForCLR.IsAssignableFrom(p[i].GetType()))\n                    {\n                        throw new ArgumentException(\"Parameter type mismatch\");\n                    }\n                }\n                return Invoke(m, instance, p);\n            }\n            return null;\n        }\n\n        /// <summary>\n        /// Invoke a generic method\n        /// </summary>\n        /// <param name=\"type\">Type's fullname</param>\n        /// <param name=\"method\">Method name</param>\n        /// <param name=\"genericArguments\">Generic Arguments</param>\n        /// <param name=\"instance\">Object Instance of the method</param>\n        /// <param name=\"p\">Parameters</param>\n        /// <returns></returns>\n        public object InvokeGenericMethod(string type, string method, IType[] genericArguments, object instance, params object[] p)\n        {\n            IType t = GetType(type);\n            if (t == null)\n                return null;\n            var m = t.GetMethod(method, p.Length);\n\n            if (m != null)\n            {\n                m = m.MakeGenericMethod(genericArguments);\n                return Invoke(m, instance, p);\n            }\n            return null;\n        }\n\n        /// <summary>\n        /// Invokes a specific method\n        /// </summary>\n        /// <param name=\"m\">Method</param>\n        /// <param name=\"instance\">object instance</param>\n        /// <param name=\"p\">Parameters</param>\n        /// <returns></returns>\n        public object Invoke(IMethod m, object instance, params object[] p)\n        {\n            object res = null;\n            if (m is ILMethod)\n            {\n                ILIntepreter inteptreter = null;\n                lock (freeIntepreters)\n                {\n                    if (freeIntepreters.Count > 0)\n                    {\n                        inteptreter = freeIntepreters.Dequeue();\n                        //Clear debug state, because it may be in ShouldBreak State\n                        inteptreter.ClearDebugState();\n                    }\n                    else\n                    {\n                        inteptreter = new ILIntepreter(this);\n#if DEBUG\n                        intepreters[inteptreter.GetHashCode()] = inteptreter;\n                        debugService.ThreadStarted(inteptreter);\n#endif\n                    }\n                }\n                try\n                {\n                    res = inteptreter.Run((ILMethod)m, instance, p);\n                }\n                finally\n                {\n                    lock (freeIntepreters)\n                    {\n#if DEBUG\n                        if(inteptreter.CurrentStepType!= StepTypes.None)\n                        {\n                            //We should resume all other threads if we are currently doing stepping operation\n                            foreach(var i in intepreters)\n                            {\n                                if(i.Value != inteptreter)\n                                {\n                                    i.Value.ClearDebugState();\n                                    i.Value.Resume();\n                                }\n                            }\n                            inteptreter.ClearDebugState();\n                        }\n#endif\n                        inteptreter.Stack.ManagedStack.Clear();\n                        inteptreter.Stack.Frames.Clear();\n                        freeIntepreters.Enqueue(inteptreter);\n#if DEBUG\n                        //debugService.ThreadEnded(inteptreter);\n#endif\n\n                    }\n                }\n            }\n\n            return res;\n        }\n\n        internal IMethod GetMethod(object token, ILType contextType,ILMethod contextMethod, out bool invalidToken)\n        {\n            string methodname = null;\n            string typename = null;\n            List<IType> paramList = null;\n            int hashCode = token.GetHashCode();\n            IMethod method;\n            IType[] genericArguments = null;\n            IType returnType;\n            invalidToken = false;\n            bool isConstructor = false;\n            if (mapMethod.TryGetValue(hashCode, out method))\n                return method;\n            IType type = null;\n            if (token is Mono.Cecil.MethodReference)\n            {\n                Mono.Cecil.MethodReference _ref = (token as Mono.Cecil.MethodReference);\n                if (_ref.FullName == \"System.Void System.Object::.ctor()\")\n                {\n                    mapMethod[hashCode] = null;\n                    return null;\n                }\n                if (_ref.FullName == \"System.Void System.Attribute::.ctor()\")\n                {\n                    mapMethod[hashCode] = null;\n                    return null;\n                }\n                methodname = _ref.Name;\n                var typeDef = _ref.DeclaringType;\n\n                type = GetType(typeDef, contextType, contextMethod);\n                if (type == null)\n                    throw new KeyNotFoundException(\"Cannot find type:\" + typename);\n\n                if (token is Mono.Cecil.MethodDefinition)\n                {\n                    var def = _ref as MethodDefinition;\n                    isConstructor = def.IsConstructor;\n                }\n                else\n                    isConstructor = methodname == \".ctor\";\n\n                if (_ref.IsGenericInstance)\n                {\n                    GenericInstanceMethod gim = (GenericInstanceMethod)_ref;\n                    genericArguments = new IType[gim.GenericArguments.Count];\n                    for (int i = 0; i < genericArguments.Length; i++)\n                    {\n                        if (gim.GenericArguments[i].IsGenericParameter)\n                            invalidToken = true;\n                        var gt = GetType(gim.GenericArguments[i], contextType, contextMethod);\n                        if (gt == null)\n                        {\n                            gt = contextMethod.FindGenericArgument(gim.GenericArguments[i].Name);\n                            if (gt == null)//This means it contains unresolved generic arguments, which means it's not searching the generic instance\n                            {\n                                genericArguments = null;\n                                break;\n                            }\n                            else\n                                genericArguments[i] = gt;\n                        }\n                        else\n                            genericArguments[i] = gt;\n                    }\n                }\n                if (!invalidToken && typeDef.IsGenericInstance)\n                {\n                    GenericInstanceType gim = (GenericInstanceType)typeDef;\n                    for (int i = 0; i < gim.GenericArguments.Count; i++)\n                    {\n                        if (gim.GenericArguments[0].IsGenericParameter)\n                        {\n                            invalidToken = true;\n                            break;\n                        }\n                    }\n                }\n                paramList = _ref.GetParamList(this, contextType, contextMethod, genericArguments);\n                returnType = GetType(_ref.ReturnType, type, null);\n                if (returnType == null)\n                    returnType = GetType(_ref.ReturnType, contextType, null);\n            }\n            else\n            {\n                throw new NotImplementedException();\n                //Mono.Cecil.GenericInstanceMethod gmethod = _def as Mono.Cecil.GenericInstanceMethod;\n                //genlist = new MethodParamList(environment, gmethod);\n            }\n\n            if (isConstructor)\n                method = type.GetConstructor(paramList);\n            else\n            {\n                method = type.GetMethod(methodname, paramList, genericArguments, returnType, true);\n            }\n\n            if (method == null)\n            {\n                if (isConstructor && contextType.FirstCLRBaseType != null && contextType.FirstCLRBaseType is CrossBindingAdaptor && type.TypeForCLR == ((CrossBindingAdaptor)contextType.FirstCLRBaseType).BaseCLRType)\n                {\n                    method = contextType.BaseType.GetConstructor(paramList);\n                    if (method == null)\n                        throw new KeyNotFoundException(string.Format(\"Cannot find method:{0} in type:{1}, token={2}\", methodname, type.FullName, token));\n                    invalidToken = true;\n                    mapMethod[method.GetHashCode()] = method;\n                }\n                else\n                    throw new KeyNotFoundException(string.Format(\"Cannot find method:{0} in type:{1}, token={2}\", methodname, type.FullName, token));\n            }\n            if (!invalidToken)\n                mapMethod[hashCode] = method;\n            else\n                mapMethod[method.GetHashCode()] = method;\n            return method;\n        }\n\n        internal IMethod GetMethod(int tokenHash)\n        {\n            IMethod res;\n            if (mapMethod.TryGetValue(tokenHash, out res))\n                return res;\n\n            return null;\n        }\n\n        internal long GetStaticFieldIndex(object token, IType contextType, IMethod contextMethod)\n        {\n            FieldReference f = token as FieldReference;\n            var type = GetType(f.DeclaringType, contextType, contextMethod);\n\n            if (type is ILType)\n            {\n                var it = type as ILType;\n                int idx = it.GetFieldIndex(token);\n                long res = 0;\n                if (it.TypeReference.HasGenericParameters)\n                {\n                    mapTypeToken[type.GetHashCode()] = it;\n                    res = ((long)type.GetHashCode() << 32) | (uint)idx;\n                }\n                else\n                {\n                    res = ((long)it.TypeReference.GetHashCode() << 32) | (uint)idx;\n                }\n\n                return res;\n            }\n            else\n            {\n                int idx = type.GetFieldIndex(token);\n                long res = ((long)type.GetHashCode() << 32) | (uint)idx;\n\n                return res;\n            }\n        }\n\n        internal long CacheString(object token)\n        {\n            long oriHash = token.GetHashCode();\n            long hashCode = oriHash;\n            string str = (string)token;\n            lock (mapString)\n            {\n                bool isCollision = CheckStringCollision(hashCode, str);\n                long cnt = 0;\n                while (isCollision)\n                {\n                    cnt++;\n                    hashCode = cnt << 32 | oriHash;\n                    isCollision = CheckStringCollision(hashCode, str);\n                }\n                mapString[hashCode] = (string)token;\n            }\n            return hashCode;\n        }\n\n        bool CheckStringCollision(long hashCode, string newStr)\n        {\n            string oldVal;\n            if (mapString.TryGetValue(hashCode, out oldVal))\n                return oldVal != newStr;\n            return false;\n        }\n\n        internal string GetString(long hashCode)\n        {\n            string res = null;\n            if (mapString.TryGetValue(hashCode, out res))\n                return res;\n            return res;\n        }\n\n        public void RegisterCrossBindingAdaptor(CrossBindingAdaptor adaptor)\n        {\n            var bType = adaptor.BaseCLRType;\n            \n            if (bType != null)\n            {\n                if (!crossAdaptors.ContainsKey(bType))\n                {\n                    var t = adaptor.AdaptorType;\n                    var res = GetType(t);\n                    if (res == null)\n                    {\n                        res = new CLRType(t, this);\n                        mapType[res.FullName] = res;\n                        mapType[t.AssemblyQualifiedName] = res;\n                        clrTypeMapping[t] = res;\n                    }\n                    adaptor.RuntimeType = res;\n                    crossAdaptors[bType] = adaptor;\n                }\n                else\n                    throw new Exception(\"Crossbinding Adapter for \" + bType.FullName + \" is already added.\");\n            }\n            else\n            {\n                var bTypes = adaptor.BaseCLRTypes;\n                var t = adaptor.AdaptorType;\n                var res = GetType(t);\n                if (res == null)\n                {\n                    res = new CLRType(t, this);\n                    mapType[res.FullName] = res;\n                    mapType[t.AssemblyQualifiedName] = res;\n                    clrTypeMapping[t] = res;\n                }\n                adaptor.RuntimeType = res;\n\n                foreach (var i in bTypes)\n                {\n                    if (!crossAdaptors.ContainsKey(i))\n                    {\n                        crossAdaptors[i] = adaptor;\n                    }\n                    else\n                        throw new Exception(\"Crossbinding Adapter for \" + i.FullName + \" is already added.\");\n                }\n            } \n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Enviorment/CLRRedirections.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.Utils;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Reflection;\n\nnamespace ILRuntime.Runtime.Enviorment\n{\n    unsafe static class CLRRedirections\n    {\n        public static StackObject* CreateInstance(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            IType[] genericArguments = method.GenericArguments;\n            if (genericArguments != null && genericArguments.Length == 1)\n            {\n                var t = genericArguments[0];\n                if (t is ILType)\n                {\n                    return ILIntepreter.PushObject(esp, mStack, ((ILType)t).Instantiate());\n                }\n                else\n                    return ILIntepreter.PushObject(esp, mStack, ((CLRType)t).CreateDefaultInstance());\n            }\n            else\n                throw new EntryPointNotFoundException();\n        }\n        /*public static object CreateInstance(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            if (genericArguments != null && genericArguments.Length == 1)\n            {\n                var t = genericArguments[0];\n                if (t is ILType)\n                {\n                    return ((ILType)t).Instantiate();\n                }\n                else\n                    return Activator.CreateInstance(t.TypeForCLR);\n            }\n            else\n                throw new EntryPointNotFoundException();\n        }*/\n\n        public static StackObject* CreateInstance2(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            var p = esp - 1;\n            var t = mStack[p->Value] as Type;\n            intp.Free(p);\n            if (t != null)\n            {\n                if (t is ILRuntimeType)\n                {\n                    return ILIntepreter.PushObject(p, mStack, ((ILRuntimeType)t).ILType.Instantiate());\n                }\n                else\n                    return ILIntepreter.PushObject(p, mStack, Activator.CreateInstance(t));\n            }\n            else\n                return ILIntepreter.PushNull(p);\n        }\n\n        /*public static object CreateInstance2(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var t = param[0] as Type;\n            if (t != null)\n            {\n                if (t is ILRuntimeType)\n                {\n                    return ((ILRuntimeType)t).ILType.Instantiate();\n                }\n                else\n                    return Activator.CreateInstance(t);\n            }\n            else\n                return null;\n        }*/\n\n        public static StackObject* GetType(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            var p = esp - 1;\n            AppDomain dommain = intp.AppDomain;\n            string fullname = (string)StackObject.ToObject(p, dommain, mStack); ;\n            intp.Free(p);\n            var t = intp.AppDomain.GetType(fullname);\n            if (t != null)\n                return ILIntepreter.PushObject(p, mStack, t.ReflectionType);\n            else\n                return ILIntepreter.PushNull(p);\n        }\n\n        public static StackObject* TypeEquals(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            var ret = ILIntepreter.Minus(esp, 2);\n            var p = esp - 1;\n            AppDomain dommain = intp.AppDomain;\n            var other = StackObject.ToObject(p, dommain, mStack);\n            intp.Free(p);\n            p = ILIntepreter.Minus(esp, 2);\n            var instance = StackObject.ToObject(p, dommain, mStack);\n            intp.Free(p);\n            if(instance is ILRuntimeType)\n            {\n                if (other is ILRuntimeType)\n                {\n                    if(((ILRuntimeType)instance).ILType == ((ILRuntimeType)other).ILType)\n                        return ILIntepreter.PushOne(ret);\n                    else\n                        return ILIntepreter.PushZero(ret);\n                }\n                else\n                    return ILIntepreter.PushZero(ret);\n            }\n            else\n            {\n                if(((Type)typeof(Type).CheckCLRTypes(instance)).Equals(((Type)typeof(Type).CheckCLRTypes(other))))\n                    return ILIntepreter.PushOne(ret);\n                else\n                    return ILIntepreter.PushZero(ret);\n            }\n        }\n\n        /*public static object GetType(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var t = ctx.AppDomain.GetType((string)param[0]);\n            if (t != null)\n                return t.ReflectionType;\n            else\n                return null;\n        }*/\n\n        public unsafe static StackObject* InitializeArray(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            var ret = esp - 1 - 1;\n            AppDomain domain = intp.AppDomain;\n            var param = esp - 1;\n            byte[] data = StackObject.ToObject(param, domain, mStack) as byte[];\n            intp.Free(param);\n            param = esp - 1 - 1;\n            object array = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            if (data == null)\n                return ret;\n            fixed (byte* p = data)\n            {\n                if (array is int[])\n                {\n                    int[] arr = array as int[];\n                    int* ptr = (int*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is byte[])\n                {\n                    byte[] arr = array as byte[];\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = p[i];\n                    }\n                }\n                else if (array is sbyte[])\n                {\n                    sbyte[] arr = array as sbyte[];\n                    sbyte* ptr = (sbyte*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is short[])\n                {\n                    short[] arr = array as short[];\n                    short* ptr = (short*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is ushort[])\n                {\n                    ushort[] arr = array as ushort[];\n                    ushort* ptr = (ushort*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is char[])\n                {\n                    char[] arr = array as char[];\n                    char* ptr = (char*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is uint[])\n                {\n                    uint[] arr = array as uint[];\n                    uint* ptr = (uint*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is Int64[])\n                {\n                    long[] arr = array as long[];\n                    long* ptr = (long*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is UInt64[])\n                {\n                    ulong[] arr = array as ulong[];\n                    ulong* ptr = (ulong*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is float[])\n                {\n                    float[] arr = array as float[];\n                    float* ptr = (float*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is double[])\n                {\n                    double[] arr = array as double[];\n                    double* ptr = (double*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is bool[])\n                {\n                    bool[] arr = array as bool[];\n                    bool* ptr = (bool*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else\n                {\n                    throw new NotImplementedException(\"array=\" + array.GetType());\n                }\n            }\n\n            return ret;\n        }\n\n        /*public unsafe static object InitializeArray(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            object array = param[0];\n            byte[] data = param[1] as byte[];\n            if (data == null)\n                return null;\n            fixed (byte* p = data)\n            {\n                if (array is int[])\n                {\n                    int[] arr = array as int[];\n                    int* ptr = (int*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is byte[])\n                {\n                    byte[] arr = array as byte[];\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = p[i];\n                    }\n                }\n                else if (array is sbyte[])\n                {\n                    sbyte[] arr = array as sbyte[];\n                    sbyte* ptr = (sbyte*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is short[])\n                {\n                    short[] arr = array as short[];\n                    short* ptr = (short*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is ushort[])\n                {\n                    ushort[] arr = array as ushort[];\n                    ushort* ptr = (ushort*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is char[])\n                {\n                    char[] arr = array as char[];\n                    char* ptr = (char*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is uint[])\n                {\n                    uint[] arr = array as uint[];\n                    uint* ptr = (uint*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is Int64[])\n                {\n                    long[] arr = array as long[];\n                    long* ptr = (long*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is UInt64[])\n                {\n                    ulong[] arr = array as ulong[];\n                    ulong* ptr = (ulong*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is float[])\n                {\n                    float[] arr = array as float[];\n                    float* ptr = (float*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is double[])\n                {\n                    double[] arr = array as double[];\n                    double* ptr = (double*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is bool[])\n                {\n                    bool[] arr = array as bool[];\n                    bool* ptr = (bool*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else\n                {\n                    throw new NotImplementedException(\"array=\" + array.GetType());\n                }\n            }\n\n            return null;\n        }*/\n\n        public unsafe static StackObject* DelegateCombine(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            //Don't ask me why not esp -2, unity won't return the right result\n            var ret = esp - 1 - 1;\n            AppDomain domain = intp.AppDomain;\n            var param = esp - 1;\n            object dele2 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = esp - 1 - 1;\n            object dele1 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n            \n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            var dele = ((IDelegateAdapter)dele1);\n                            //This means it's the original delegate which should be untouch\n                            if (!dele.IsClone)\n                            {\n                                dele = dele.Clone();\n                            }\n                            if(!((IDelegateAdapter)dele2).IsClone)\n                            {\n                                dele2 = ((IDelegateAdapter)dele2).Clone();\n                            }\n                            dele.Combine((IDelegateAdapter)dele2);\n                            return ILIntepreter.PushObject(ret, mStack, dele);\n                        }\n                        else\n                        {\n                            if (!((IDelegateAdapter)dele1).IsClone)\n                            {\n                                dele1 = ((IDelegateAdapter)dele1).Clone();\n                            }\n                            ((IDelegateAdapter)dele1).Combine((Delegate)dele2);\n                            return ILIntepreter.PushObject(ret, mStack, dele1);\n                        }\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return ILIntepreter.PushObject(ret, mStack, Delegate.Combine((Delegate)dele1, ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType())));\n                        else\n                            return ILIntepreter.PushObject(ret, mStack, Delegate.Combine((Delegate)dele1, (Delegate)dele2));\n                    }\n                }\n                else\n                    return ILIntepreter.PushObject(ret, mStack, dele1);\n            }\n            else\n                return ILIntepreter.PushObject(ret, mStack, dele2);\n        }\n\n        /*public unsafe static object DelegateCombine(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var esp = ctx.ESP;\n            var mStack = ctx.ManagedStack;\n            var domain = ctx.AppDomain;\n\n            //Don't ask me why not esp -2, unity won't return the right result\n            var dele1 = StackObject.ToObject((esp - 1 - 1), domain, mStack);\n            var dele2 = StackObject.ToObject((esp - 1), domain, mStack);\n\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            var dele = ((IDelegateAdapter)dele1);\n                            //This means it's the default delegate which should be singleton to support == operator\n                            if (dele.Next == null)\n                            {\n                                dele = dele.Instantiate(domain, dele.Instance, dele.Method);\n                            }\n                            dele.Combine((IDelegateAdapter)dele2);\n                            return dele;\n                        }\n                        else\n                        {\n                            ((IDelegateAdapter)dele1).Combine((Delegate)dele2);\n                            return dele1;\n                        }\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return Delegate.Combine((Delegate)dele1, ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType()));\n                        else\n                            return Delegate.Combine((Delegate)dele1, (Delegate)dele2);\n                    }\n                }\n                else\n                    return dele1;\n            }\n            else\n                return dele2;\n        }*/\n\n        public unsafe static StackObject* DelegateRemove(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            //Don't ask me why not esp -2, unity won't return the right result\n            var ret = esp - 1 - 1;\n            AppDomain domain = intp.AppDomain;\n            var param = esp - 1;\n            object dele2 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = esp - 1 - 1;\n            object dele1 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            if (((IDelegateAdapter)dele1).Equals((IDelegateAdapter)dele2))\n                                return ILIntepreter.PushObject(ret, mStack, ((IDelegateAdapter)dele1).Next);\n                            else\n                                ((IDelegateAdapter)dele1).Remove((IDelegateAdapter)dele2);\n                        }\n                        else\n                            ((IDelegateAdapter)dele1).Remove((Delegate)dele2);\n                        return ILIntepreter.PushObject(ret, mStack, dele1);\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return ILIntepreter.PushObject(ret, mStack, Delegate.Remove((Delegate)dele1, ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType())));\n                        else\n                            return ILIntepreter.PushObject(ret, mStack, Delegate.Remove((Delegate)dele1, (Delegate)dele2));\n                    }\n                }\n                else\n                    return ILIntepreter.PushObject(ret, mStack, dele1);\n            }\n            else\n                return ILIntepreter.PushNull(ret);\n        }\n\n        /*public unsafe static object DelegateRemove(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var esp = ctx.ESP;\n            var mStack = ctx.ManagedStack;\n            var domain = ctx.AppDomain;\n\n            var dele1 = StackObject.ToObject((esp - 1 - 1), domain, mStack);\n            var dele2 = StackObject.ToObject((esp - 1), domain, mStack);\n\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            if (dele1 == dele2)\n                                return ((IDelegateAdapter)dele1).Next;\n                            else\n                                ((IDelegateAdapter)dele1).Remove((IDelegateAdapter)dele2);\n                        }\n                        else\n                            ((IDelegateAdapter)dele1).Remove((Delegate)dele2);\n                        return dele1;\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return Delegate.Remove((Delegate)dele1, ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType()));\n                        else\n                            return Delegate.Remove((Delegate)dele1, (Delegate)dele2);\n                    }\n                }\n                else\n                    return dele1;\n            }\n            else\n                return null;\n        }*/\n\n        public unsafe static StackObject* DelegateEqulity(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            //Don't ask me why not esp -2, unity won't return the right result\n            var ret = esp - 1 - 1;\n            AppDomain domain = intp.AppDomain;\n            var param = esp - 1;\n            object dele2 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = esp - 1 - 1;\n            object dele1 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            bool res = false;\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            res = ((IDelegateAdapter)dele1).Equals((IDelegateAdapter)dele2);\n                        else\n                            res = ((IDelegateAdapter)dele1).Equals((Delegate)dele2);\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            res = (Delegate)dele1 == ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType());\n                        }\n                        else\n                            res = (Delegate)dele1 == (Delegate)dele2;\n                    }\n                }\n                else\n                    res = dele1 == null;\n            }\n            else\n                res = dele2 == null;\n\n            if (res)\n                return ILIntepreter.PushOne(ret);\n            else\n                return ILIntepreter.PushZero(ret);\n        }\n\n        /*public unsafe static object DelegateEqulity(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            //op_Equality,op_Inequality\n            var esp = ctx.ESP;\n            var mStack = ctx.ManagedStack;\n            var domain = ctx.AppDomain;\n\n            var dele1 = StackObject.ToObject((esp - 1 - 1), domain, mStack);\n            var dele2 = StackObject.ToObject((esp - 1), domain, mStack);\n\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return ((IDelegateAdapter)dele1).Equals((IDelegateAdapter)dele2);\n                        else\n                            return ((IDelegateAdapter)dele1).Equals((Delegate)dele2);\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            return (Delegate)dele1 == ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType());\n                        }\n                        else\n                            return (Delegate)dele1 == (Delegate)dele2;\n                    }\n                }\n                else\n                    return dele1 == null;\n            }\n            else\n                return dele2 == null;\n        }*/\n\n        public unsafe static StackObject* DelegateInequlity(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            //Don't ask me why not esp -2, unity won't return the right result\n            var ret = esp - 1 - 1;\n            AppDomain domain = intp.AppDomain;\n            var param = esp - 1;\n            object dele2 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = esp - 1 - 1;\n            object dele1 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            bool res = false;\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            res = !((IDelegateAdapter)dele1).Equals((IDelegateAdapter)dele2);\n                        else\n                            res = !((IDelegateAdapter)dele1).Equals((Delegate)dele2);\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            res = (Delegate)dele1 != ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType());\n                        else\n                            res = (Delegate)dele1 != (Delegate)dele2;\n                    }\n                }\n                else\n                    res = dele1 != null;\n            }\n            else\n                res = dele2 != null;\n            if (res)\n                return ILIntepreter.PushOne(ret);\n            else\n                return ILIntepreter.PushZero(ret);\n        }\n\n        /*public unsafe static object DelegateInequlity(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            //op_Equality,op_Inequality\n            var esp = ctx.ESP;\n            var mStack = ctx.ManagedStack;\n            var domain = ctx.AppDomain;\n\n            var dele1 = StackObject.ToObject((esp - 1 - 1), domain, mStack);\n            var dele2 = StackObject.ToObject((esp - 1), domain, mStack);\n\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return !((IDelegateAdapter)dele1).Equals((IDelegateAdapter)dele2);\n                        else\n                            return !((IDelegateAdapter)dele1).Equals((Delegate)dele2);\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return (Delegate)dele1 != ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType());\n                        else\n                            return (Delegate)dele1 != (Delegate)dele2;\n                    }\n                }\n                else\n                    return dele1 != null;\n            }\n            else\n                return dele2 != null;\n        }*/\n\n        public static StackObject* GetTypeFromHandle(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            //Nothing to do\n            return esp;\n        }\n\n        /*public static object GetTypeFromHandle(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            return param[0];\n        }*/\n\n        public unsafe static StackObject* MethodInfoInvoke(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            AppDomain domain = intp.AppDomain;\n            //Don't ask me why not esp - 3, unity won't return the right result\n            var ret = ILIntepreter.Minus(esp, 3);\n            var param = esp - 1;\n            var p = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = esp - 1 - 1;\n            var obj = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = ILIntepreter.Minus(esp, 3);\n            object instance = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            if (instance is ILRuntimeMethodInfo)\n            {\n                if (obj != null)\n                    esp = ILIntepreter.PushObject(ret, mStack, obj);\n                else\n                    esp = ret;\n                if (p != null)\n                {\n                    object[] arr = (object[])p;\n                    foreach (var i in arr)\n                    {\n                        esp = ILIntepreter.PushObject(esp, mStack, i);\n                    }\n                }\n                bool unhandled;\n                var ilmethod = ((ILRuntimeMethodInfo)instance).ILMethod;\n                return intp.Execute(ilmethod, esp, out unhandled);\n            }\n            else\n                return ILIntepreter.PushObject(ret, mStack, ((MethodInfo)instance).Invoke(obj, (object[])p));\n        }\n\n        /*public unsafe static object MethodInfoInvoke(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var esp = ctx.ESP;\n            var mStack = ctx.ManagedStack;\n            var domain = ctx.AppDomain;\n            var intp = ctx.Interpreter;\n            //Don't ask me why not esp - 3, unity won't return the right result\n            var obj = param[0];\n            var p = param[1];\n\n            if (instance is ILRuntimeMethodInfo)\n            {\n                if (obj != null)\n                    esp = ILIntepreter.PushObject(esp, mStack, obj);\n                if (p != null)\n                {\n                    object[] arr = (object[])p;\n                    foreach (var i in arr)\n                    {\n                        esp = ILIntepreter.PushObject(esp, mStack, i);\n                    }\n                }\n                bool unhandled;\n                var ilmethod = ((ILRuntimeMethodInfo)instance).ILMethod;\n                esp = intp.Execute(ilmethod, esp, out unhandled);\n                object res = null;\n                if (ilmethod.ReturnType != domain.VoidType)\n                {\n                    res = StackObject.ToObject((esp - 1),domain, mStack);\n                    intp.Free(esp - 1);\n                }\n                return res;\n            }\n            else\n                return ((MethodInfo)instance).Invoke(obj, (object[])p);\n        }*/\n\n        public unsafe static StackObject* ObjectGetType(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            AppDomain domain = intp.AppDomain;\n            var ret = esp - 1;\n            var param = esp - 1;\n            var instance = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n             \n            var type = instance.GetType();\n            if (type == typeof(ILTypeInstance))\n            {\n                return ILIntepreter.PushObject(ret, mStack, ((ILTypeInstance)instance).Type.ReflectionType);\n            }\n            else\n                return ILIntepreter.PushObject(ret, mStack, type);\n        }\n\n        /*public unsafe static object ObjectGetType(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var type = instance.GetType();\n            if (type == typeof(ILTypeInstance))\n            {\n                return ((ILTypeInstance)instance).Type.ReflectionType;\n            }\n            else\n                return type;\n        }*/\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Enviorment/CrossBindingAdaptor.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Runtime.Enviorment\n{\n    public interface CrossBindingAdaptorType\n    {\n        ILTypeInstance ILInstance { get; }\n    }\n    /// <summary>\n    /// This interface is used for inheritance and implementation of CLR Types or interfaces\n    /// </summary>\n    public abstract class CrossBindingAdaptor : IType\n    {\n        IType type;\n        /// <summary>\n        /// This returns the CLR type to be inherited or CLR interface to be implemented\n        /// </summary>\n        public abstract Type BaseCLRType { get; }\n\n        /// <summary>\n        /// If this Adaptor is capable to impelement multuple interfaces, use this Property, AND BaseCLRType should return null\n        /// </summary>\n        public virtual Type[] BaseCLRTypes\n        {\n            get\n            {\n                return null;\n            }\n        }\n\n        public abstract Type AdaptorType { get; }\n\n        public abstract object CreateCLRInstance(Enviorment.AppDomain appdomain, ILTypeInstance instance);\n\n        internal IType RuntimeType { get { return type; } set { type = value; } }\n\n        #region IType Members\n\n        public IMethod GetMethod(string name, int paramCount, bool declaredOnly = false)\n        {\n            return type.GetMethod(name, paramCount, declaredOnly);\n        }\n\n        public IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false)\n        {\n            return type.GetMethod(name, param, genericArguments, returnType, declaredOnly);\n        }\n\n        public List<IMethod> GetMethods()\n        {\n            return type.GetMethods();\n        }\n\n        public int GetFieldIndex(object token)\n        {\n            return type.GetFieldIndex(token);\n        }\n\n        public IMethod GetConstructor(List<IType> param)\n        {\n            return type.GetConstructor(param);\n        }\n\n        public bool CanAssignTo(IType type)\n        {\n            bool res = false;\n            if (BaseType != null)\n                res = BaseType.CanAssignTo(type);\n            var interfaces = Implements;\n            if (!res && interfaces != null)\n            {\n                for (int i = 0; i < interfaces.Length; i++)\n                {\n                    var im = interfaces[i];\n                    res = im.CanAssignTo(type);\n                    if (res)\n                        return true;\n                }\n            }\n            return res;\n        }\n\n        public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)\n        {\n            return type.MakeGenericInstance(genericArguments);\n        }\n\n        public IType MakeByRefType()\n        {\n            return type.MakeByRefType();\n        }\n\n        public IType MakeArrayType()\n        {\n            return type.MakeArrayType();\n        }\n\n        public IType FindGenericArgument(string key)\n        {\n            return type.FindGenericArgument(key);\n        }\n\n        public IType ResolveGenericType(IType contextType)\n        {\n            return type.ResolveGenericType(contextType);\n        }\n\n        public IMethod GetVirtualMethod(IMethod method)\n        {\n            return type.GetVirtualMethod(method);\n        }\n\n        public bool IsGenericInstance\n        {\n            get\n            {\n                return type.IsGenericInstance;\n            }\n        }\n\n        public KeyValuePair<string, IType>[] GenericArguments\n        {\n            get\n            {\n                return type.GenericArguments;\n            }\n        }\n\n        public Type TypeForCLR\n        {\n            get\n            {\n                return type.TypeForCLR;\n            }\n        }\n\n        public IType ByRefType\n        {\n            get\n            {\n                return type.ByRefType;\n            }\n        }\n\n        public IType ArrayType\n        {\n            get\n            {\n                return type.ArrayType;\n            }\n        }\n\n        public string FullName\n        {\n            get\n            {\n                return type.FullName;\n            }\n        }\n\n        public string Name\n        {\n            get\n            {\n                return type.Name;\n            }\n        }\n\n        public bool IsValueType\n        {\n            get\n            {\n                return type.IsValueType;\n            }\n        }\n\n        public bool IsPrimitive\n        {\n            get\n            {\n                return type.IsPrimitive;\n            }\n        }\n\n        public bool IsDelegate\n        {\n            get\n            {\n                return type.IsDelegate;\n            }\n        }\n\n        public AppDomain AppDomain\n        {\n            get\n            {\n                return type.AppDomain;\n            }\n        }\n\n        public Type ReflectionType\n        {\n            get\n            {\n                return type.ReflectionType;\n            }\n        }\n\n        public IType BaseType\n        {\n            get\n            {\n                return type.BaseType;\n            }\n        }\n\n        public IType[] Implements\n        {\n            get\n            {\n                return type.Implements;\n            }\n        }\n\n        public bool HasGenericParameter\n        {\n            get\n            {\n                return type.HasGenericParameter;\n            }\n        }\n        public bool IsArray\n        {\n            get { return false; }\n        }\n        #endregion\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Enviorment/DelegateManager.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Other;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Runtime.Enviorment\n{\n    public class DelegateManager\n    {\n        List<DelegateMapNode> methods = new List<DelegateMapNode>();\n        List<DelegateMapNode> functions = new List<DelegateMapNode>();\n        IDelegateAdapter zeroParamMethodAdapter = new MethodDelegateAdapter();\n        IDelegateAdapter dummyAdapter = new DummyDelegateAdapter();\n        Dictionary<Type, Func<Delegate, Delegate>> clrDelegates = new Dictionary<Type, Func<Delegate, Delegate>>(new ByReferenceKeyComparer<Type>());\n        Func<Delegate, Delegate> defaultConverter;\n        Enviorment.AppDomain appdomain;\n        public DelegateManager(Enviorment.AppDomain appdomain)\n        {\n            this.appdomain = appdomain;\n            defaultConverter = DefaultConverterStub;\n        }\n\n        static Delegate DefaultConverterStub(Delegate dele)\n        {\n            return dele;\n        }\n\n        public void RegisterDelegateConvertor<T>(Func<Delegate, Delegate> action)\n        {\n            var type = typeof(T);\n            if (type.IsSubclassOf(typeof(Delegate)))\n            {\n                clrDelegates[type] = action;\n            }\n            else\n                throw new NotSupportedException();\n        }\n\n        public void RegisterMethodDelegate<T1>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new MethodDelegateAdapter<T1>();\n            node.ParameterTypes = new Type[] { typeof(T1) };\n            methods.Add(node);\n            RegisterDelegateConvertor<Action<T1>>(defaultConverter);\n        }\n\n        public void RegisterMethodDelegate<T1, T2>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new MethodDelegateAdapter<T1, T2>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2) };\n            methods.Add(node);\n            RegisterDelegateConvertor<Action<T1, T2>>(defaultConverter);\n        }\n\n        public void RegisterMethodDelegate<T1, T2, T3>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new MethodDelegateAdapter<T1, T2, T3>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2), typeof(T3) };\n            methods.Add(node);\n            RegisterDelegateConvertor<Action<T1, T2, T3>>(defaultConverter);\n        }\n\n        public void RegisterMethodDelegate<T1, T2, T3, T4>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new MethodDelegateAdapter<T1, T2, T3, T4>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) };\n            methods.Add(node);\n            RegisterDelegateConvertor<Action<T1, T2, T3, T4>>(defaultConverter);\n        }\n\n        public void RegisterFunctionDelegate<TResult>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new FunctionDelegateAdapter<TResult>();\n            node.ParameterTypes = new Type[] { typeof(TResult) };\n            functions.Add(node);\n            RegisterDelegateConvertor<Func<TResult>>(defaultConverter);\n        }\n\n        public void RegisterFunctionDelegate<T1, TResult>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new FunctionDelegateAdapter<T1, TResult>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(TResult) };\n            functions.Add(node);\n            RegisterDelegateConvertor<Func<T1, TResult>>(defaultConverter);\n        }\n\n        public void RegisterFunctionDelegate<T1, T2, TResult>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new FunctionDelegateAdapter<T1, T2, TResult>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2), typeof(TResult) };\n            functions.Add(node);\n            RegisterDelegateConvertor<Func<T1, T2, TResult>>(defaultConverter);\n        }\n\n        public void RegisterFunctionDelegate<T1, T2, T3, TResult>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new FunctionDelegateAdapter<T1, T2, T3, TResult>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(TResult) };\n            functions.Add(node);\n            RegisterDelegateConvertor<Func<T1, T2, T3, TResult>>(defaultConverter);\n        }\n\n        public void RegisterFunctionDelegate<T1, T2, T3, T4, TResult>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new FunctionDelegateAdapter<T1, T2, T3, T4, TResult>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(TResult) };\n            functions.Add(node);\n            RegisterDelegateConvertor<Func<T1, T2, T3, T4, TResult>>(defaultConverter);\n        }\n\n        internal Delegate ConvertToDelegate(Type clrDelegateType, IDelegateAdapter adapter)\n        {\n            Func<Delegate, Delegate> func;\n            if(adapter is DummyDelegateAdapter)\n            {\n                DelegateAdapter.ThrowAdapterNotFound(adapter.Method);\n                return null;\n            }\n            if (clrDelegates.TryGetValue(clrDelegateType, out func))\n            {\n                return func(adapter.Delegate);\n            }\n            else\n            {\n                StringBuilder sb = new StringBuilder();\n                string clsName, rName;\n                bool isByRef;\n                clrDelegateType.GetClassName(out clsName, out rName, out isByRef);\n                sb.AppendLine(\"Cannot find convertor for \" + rName);\n                sb.AppendLine(\"Please add following code:\");\n                sb.Append(\"appdomain.DelegateManager.RegisterDelegateConvertor<\");\n                sb.Append(rName);\n                sb.AppendLine(\">((act) =>\");\n                sb.AppendLine(\"{\");\n                sb.Append(\"    return new \");\n                sb.Append(rName);\n                sb.Append(\"((\");\n                var mi = clrDelegateType.GetMethod(\"Invoke\");\n                bool first = true;\n                foreach(var i in mi.GetParameters())\n                {\n                    if (first)\n                    {\n                        first = false;\n                    }\n                    else\n                        sb.Append(\", \");\n                    sb.Append(i.Name);\n                }\n                sb.AppendLine(\") =>\");\n                sb.AppendLine(\"    {\");\n                if(mi.ReturnType != appdomain.VoidType.TypeForCLR)\n                {\n                    sb.Append(\"        return ((Func<\");\n                    first = true;\n                    foreach (var i in mi.GetParameters())\n                    {\n                        if (first)\n                        {\n                            first = false;\n                        }\n                        else\n                            sb.Append(\", \");\n                        i.ParameterType.GetClassName(out clsName, out rName, out isByRef);\n                        sb.Append(rName);\n                    }\n                    if (!first)\n                        sb.Append(\", \");\n                    mi.ReturnType.GetClassName(out clsName, out rName, out isByRef);\n                    sb.Append(rName);\n                }\n                else\n                {\n                    sb.Append(\"        ((Action<\");\n                    first = true;\n                    foreach (var i in mi.GetParameters())\n                    {\n                        if (first)\n                        {\n                            first = false;\n                        }\n                        else\n                            sb.Append(\", \");\n                        i.ParameterType.GetClassName(out clsName, out rName, out isByRef);\n                        sb.Append(rName);\n                    }\n                }\n                sb.Append(\">)act)(\");\n                first = true;\n                foreach (var i in mi.GetParameters())\n                {\n                    if (first)\n                    {\n                        first = false;\n                    }\n                    else\n                        sb.Append(\", \");\n                    sb.Append(i.Name);\n                }\n                sb.AppendLine(\");\");\n                sb.AppendLine(\"    });\");\n                sb.AppendLine(\"});\");\n                throw new KeyNotFoundException(sb.ToString());\n            }\n        }\n\n        internal IDelegateAdapter FindDelegateAdapter(ILTypeInstance instance, ILMethod method)\n        {\n            IDelegateAdapter res;\n            if (method.ReturnType == appdomain.VoidType)\n            {\n                if (method.ParameterCount == 0)\n                {\n                    res = zeroParamMethodAdapter.Instantiate(appdomain, instance, method);\n                    if (instance != null)\n                        instance.SetDelegateAdapter(method, res);\n                    return res;\n                }\n                foreach (var i in methods)\n                {\n                    if (i.ParameterTypes.Length == method.ParameterCount)\n                    {\n                        bool match = true;\n                        for (int j = 0; j < method.ParameterCount; j++)\n                        {\n                            if (i.ParameterTypes[j] != method.Parameters[j].TypeForCLR)\n                            {\n                                match = false;\n                                break;\n                            }\n                        }\n                        if (match)\n                        {\n                            res = i.Adapter.Instantiate(appdomain, instance, method);\n                            if (instance != null)\n                                instance.SetDelegateAdapter(method, res);\n                            return res;\n                        }\n                    }\n                }\n            }\n            else\n            {\n                foreach (var i in functions)\n                {\n                    if (i.ParameterTypes.Length == method.ParameterCount + 1)\n                    {\n                        bool match = true;\n                        for (int j = 0; j < method.ParameterCount; j++)\n                        {\n                            if (i.ParameterTypes[j] != method.Parameters[j].TypeForCLR)\n                            {\n                                match = false;\n                                break;\n                            }\n                        }\n                        if (match)\n                        {\n                            if (method.ReturnType.TypeForCLR == i.ParameterTypes[method.ParameterCount])\n                            {\n                                res = i.Adapter.Instantiate(appdomain, instance, method);\n                                if (instance != null)\n                                    instance.SetDelegateAdapter(method, res);\n                                return res;\n                            }\n                        }\n                    }\n                }\n            }\n\n            res = dummyAdapter.Instantiate(appdomain, instance, method);\n            if (instance != null)\n                instance.SetDelegateAdapter(method, res);\n            return res;\n        }\n\n        class DelegateMapNode\n        {\n            public IDelegateAdapter Adapter { get; set; }\n            public Type[] ParameterTypes { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Enviorment/ILContext.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.CLR.Method;\nnamespace ILRuntime.Runtime.Enviorment\n{\n    public unsafe struct ILContext\n    {\n        public AppDomain AppDomain { get; private set; }\n        public StackObject* ESP { get; private set; }\n        public IList<object> ManagedStack { get; private set; }\n        public IMethod Method { get; private set; }\n        public ILIntepreter Interpreter { get; private set; }\n\n        internal ILContext(AppDomain domain,ILIntepreter intpreter, StackObject* esp, IList<object> mStack, IMethod method)\n        {\n            AppDomain = domain;\n            ESP = esp;\n            ManagedStack = mStack;\n            Method = method;\n            Interpreter = intpreter;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Enviorment/ValueTypeBinder.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Stack;\n\nnamespace ILRuntime.Runtime.Enviorment\n{\n    public unsafe abstract class ValueTypeBinder\n    {\n        CLRType clrType;\n        Enviorment.AppDomain domain;\n\n        public CLRType CLRType\n        {\n            get { return clrType; }\n            set\n            {\n                if (clrType == null)\n                {\n                    clrType = value;\n                    domain = value.AppDomain;\n                }\n                else\n                    throw new NotSupportedException();\n            }\n        }\n\n        public abstract void CopyValueTypeToStack(object ins, StackObject* ptr, IList<object> mStack);\n\n        public abstract object ToObject(StackObject* esp, IList<object> managedStack);\n\n        public virtual void RegisterCLRRedirection(Enviorment.AppDomain appdomain)\n        {\n\n        }\n\n        protected void CopyValueTypeToStack<K>(ref K ins, StackObject* esp, IList<object> mStack)\n            where K : struct\n        {\n            switch (esp->ObjectType)\n            {\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        var dst = *(StackObject**)&esp->Value;\n                        var vb = ((CLRType)domain.GetType(dst->Value)).ValueTypeBinder as ValueTypeBinder<K>;\n                        if (vb != null)\n                        {\n                            vb.CopyValueTypeToStack(ref ins, dst, mStack);\n                        }\n                        else\n                            throw new NotSupportedException();\n                    }\n                    break;\n                case ObjectTypes.Object:\n                    mStack[esp->Value] = ins;\n                    break;\n                default:\n                    throw new NotImplementedException();\n            }\n        }\n\n        protected void AssignFromStack<K>(ref K ins, StackObject* esp, IList<object> mStack)\n            where K : struct\n        {\n            switch (esp->ObjectType)\n            {\n                case ObjectTypes.Null:\n                    throw new NullReferenceException();\n                case ObjectTypes.Object:\n                    ins = (K)mStack[esp->Value];\n                    break;\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        var dst = *(StackObject**)&esp->Value;\n                        var vb = ((CLRType)domain.GetType(dst->Value)).ValueTypeBinder as ValueTypeBinder<K>;\n                        if (vb != null)\n                        {\n                            vb.AssignFromStack(ref ins, dst, mStack);\n                        }\n                        else\n                            throw new NotSupportedException();\n                    }\n                    break;\n                default:\n                    throw new NotImplementedException();\n            }\n        }        \n    }\n\n    public unsafe abstract class ValueTypeBinder<T> : ValueTypeBinder\n        where T : struct\n    {\n        public override unsafe void CopyValueTypeToStack(object ins, StackObject* ptr, IList<object> mStack)\n        {\n            T obj = (T)ins;\n            CopyValueTypeToStack(ref obj, ptr, mStack);\n        }\n\n        public abstract void CopyValueTypeToStack(ref T ins, StackObject* ptr, IList<object> mStack);\n\n        public override unsafe object ToObject(StackObject* esp, IList<object> managedStack)\n        {\n            T obj = new T();\n            AssignFromStack(ref obj, esp, managedStack);\n            return obj;\n        }\n\n        public abstract void AssignFromStack(ref T ins, StackObject* ptr, IList<object> mStack);\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Extensions.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.Runtime.Stack;\n\nnamespace ILRuntime.Runtime\n{\n    static class Extensions\n    {\n        public static void GetClassName(this Type type, out string clsName, out string realClsName, out bool isByRef, bool simpleClassName = false)\n        {\n            isByRef = type.IsByRef;\n            bool isArray = type.IsArray;\n            if (isByRef)\n                type = type.GetElementType();\n            if (isArray)\n                type = type.GetElementType();\n            string realNamespace = null;\n            bool isNestedGeneric = false;\n            if (type.IsNested)\n            {\n                string bClsName, bRealClsName;\n                bool tmp;\n                var rt = type.ReflectedType;\n                if(rt.IsGenericType && rt.IsGenericTypeDefinition)\n                {\n                    if (type.IsGenericType)\n                    {\n                        rt = rt.MakeGenericType(type.GetGenericArguments());\n                        isNestedGeneric = true;\n                    }\n                }\n                GetClassName(rt, out bClsName, out bRealClsName, out tmp);\n                clsName = simpleClassName ? \"\" : bClsName + \"_\";\n                realNamespace = bRealClsName + \".\";\n            }\n            else\n            {\n                clsName = simpleClassName ? \"\" : (!string.IsNullOrEmpty(type.Namespace) ? type.Namespace.Replace(\".\", \"_\") + \"_\" : \"\");\n                realNamespace = !string.IsNullOrEmpty(type.Namespace) ? type.Namespace + \".\" : null;\n            }\n            clsName = clsName + type.Name.Replace(\".\", \"_\").Replace(\"`\", \"_\").Replace(\"<\", \"_\").Replace(\">\", \"_\");\n            bool isGeneric = false;\n            string ga = null;\n            if (type.IsGenericType && !isNestedGeneric)\n            {\n                isGeneric = true;\n                clsName += \"_\";\n                ga = \"<\";\n                var args = type.GetGenericArguments();\n                bool first = true;\n                foreach (var j in args)\n                {\n                    if (first)\n                        first = false;\n                    else\n                    {\n                        clsName += \"_\";\n                        ga += \", \";\n                    }\n                    string a, b;\n                    bool tmp;\n                    GetClassName(j, out a, out b, out tmp, true);\n                    clsName += a;\n                    ga += b;\n                }\n                ga += \">\";\n            }\n            if (!simpleClassName)\n                clsName += \"_Binding\";\n            if (isArray)\n                clsName += \"_Array\";\n\n            realClsName = realNamespace;\n            if (isGeneric)\n            {\n                int idx = type.Name.IndexOf(\"`\");\n                if (idx > 0)\n                {\n                    realClsName += type.Name.Substring(0, idx);\n                    realClsName += ga;\n                }\n                else\n                    realClsName += type.Name;\n            }\n            else\n                realClsName += type.Name;\n\n            if (isArray)\n                realClsName += \"[]\";\n\n        }\n        public static int ToInt32(this object obj)\n        {\n            if (obj is int)\n                return (int)obj;\n            if (obj is float)\n                return (int)(float)obj;\n            if (obj is long)\n                return (int)(long)obj;\n            if (obj is short)\n                return (int)(short)obj;\n            if (obj is double)\n                return (int)(double)obj;\n            if (obj is byte)\n                return (int)(byte)obj;\n            if (obj is Intepreter.ILEnumTypeInstance)\n                return (int)((Intepreter.ILEnumTypeInstance)obj)[0];\n            if (obj is uint)\n                return (int)(uint)obj;\n            if (obj is ushort)\n                return (int)(ushort)obj;\n            if (obj is sbyte)\n                return (int)(sbyte)obj;\n            throw new InvalidCastException();\n        }\n        public static long ToInt64(this object obj)\n        {\n            if (obj is long)\n                return (long)obj;\n            if (obj is int)\n                return (long)(int)obj;\n            if (obj is float)\n                return (long)(float)obj;\n            if (obj is short)\n                return (long)(short)obj;\n            if (obj is double)\n                return (long)(double)obj;\n            if (obj is byte)\n                return (long)(byte)obj;\n            if (obj is uint)\n                return (long)(uint)obj;\n            if (obj is ushort)\n                return (long)(ushort)obj;\n            if (obj is sbyte)\n                return (long)(sbyte)obj;\n            throw new InvalidCastException();\n        }\n        public static short ToInt16(this object obj)\n        {\n            if (obj is short)\n                return (short)obj;\n            if (obj is long)\n                return (short)(long)obj;\n            if (obj is int)\n                return (short)(int)obj;\n            if (obj is float)\n                return (short)(float)obj;\n            if (obj is double)\n                return (short)(double)obj;\n            if (obj is byte)\n                return (short)(byte)obj;\n            if (obj is uint)\n                return (short)(uint)obj;\n            if (obj is ushort)\n                return (short)(ushort)obj;\n            if (obj is sbyte)\n                return (short)(sbyte)obj;\n            throw new InvalidCastException();\n        }\n        public static float ToFloat(this object obj)\n        {\n            if (obj is float)\n                return (float)obj;\n            if (obj is int)\n                return (float)(int)obj;\n            if (obj is long)\n                return (float)(long)obj;\n            if (obj is short)\n                return (float)(short)obj;\n            if (obj is double)\n                return (float)(double)obj;\n            if (obj is byte)\n                return (float)(byte)obj;\n            if (obj is uint)\n                return (float)(uint)obj;\n            if (obj is ushort)\n                return (float)(ushort)obj;\n            if (obj is sbyte)\n                return (float)(sbyte)obj;\n            throw new InvalidCastException();\n        }\n\n        public static double ToDouble(this object obj)\n        {\n            if (obj is double)\n                return (double)obj;\n            if (obj is float)\n                return (float)obj;\n            if (obj is int)\n                return (double)(int)obj;\n            if (obj is long)\n                return (double)(long)obj;\n            if (obj is short)\n                return (double)(short)obj;\n            if (obj is byte)\n                return (double)(byte)obj;\n            if (obj is uint)\n                return (double)(uint)obj;\n            if (obj is ushort)\n                return (double)(ushort)obj;\n            if (obj is sbyte)\n                return (double)(sbyte)obj;\n            throw new InvalidCastException();\n        }\n\n        public static Type GetActualType(this object value)\n        {\n            if (value is ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)\n                return ((ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)value).ILInstance.Type.ReflectionType;\n            if (value is ILRuntime.Runtime.Intepreter.ILTypeInstance)\n                return ((ILRuntime.Runtime.Intepreter.ILTypeInstance)value).Type.ReflectionType;\n            else\n                return value.GetType();\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Intepreter/DelegateAdapter.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Other;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.Intepreter\n{\n    #region Functions\n    class FunctionDelegateAdapter<TResult> : DelegateAdapter\n    {\n        Func<TResult> action;\n\n        public FunctionDelegateAdapter()\n        {\n\n        }\n\n        private FunctionDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        TResult InvokeILMethod()\n        {\n            if (method.HasThis)\n                return (TResult)appdomain.Invoke(method, instance, null);\n            else\n                return (TResult)appdomain.Invoke(method, null, null);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new FunctionDelegateAdapter<TResult>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new FunctionDelegateAdapter<TResult>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Func<TResult>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Func<TResult>)dele;\n        }\n    }\n\n    class FunctionDelegateAdapter<T1, TResult> : DelegateAdapter\n    {\n        Func<T1, TResult> action;\n\n        public FunctionDelegateAdapter()\n        {\n\n        }\n\n        private FunctionDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        TResult InvokeILMethod(T1 p1)\n        {\n            if (method.HasThis)\n                return (TResult)appdomain.Invoke(method, instance, p1);\n            else\n                return (TResult)appdomain.Invoke(method, null, p1);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new FunctionDelegateAdapter<T1, TResult>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new FunctionDelegateAdapter<T1, TResult>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Func<T1, TResult>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Func<T1, TResult>)dele;\n        }\n    }\n\n    class FunctionDelegateAdapter<T1, T2, TResult> : DelegateAdapter\n    {\n        Func<T1, T2, TResult> action;\n\n        public FunctionDelegateAdapter()\n        {\n\n        }\n\n        private FunctionDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        TResult InvokeILMethod(T1 p1, T2 p2)\n        {\n            if (method.HasThis)\n                return (TResult)appdomain.Invoke(method, instance, p1, p2);\n            else\n                return (TResult)appdomain.Invoke(method, null, p1, p2);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new FunctionDelegateAdapter<T1, T2, TResult>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new FunctionDelegateAdapter<T1, T2, TResult>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Func<T1, T2, TResult>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Func<T1, T2, TResult>)dele;\n        }\n    }\n\n    class FunctionDelegateAdapter<T1, T2, T3, TResult> : DelegateAdapter\n    {\n        Func<T1, T2, T3, TResult> action;\n\n        public FunctionDelegateAdapter()\n        {\n\n        }\n\n        private FunctionDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        TResult InvokeILMethod(T1 p1, T2 p2, T3 p3)\n        {\n            if (method.HasThis)\n                return (TResult)appdomain.Invoke(method, instance, p1, p2, p3);\n            else\n                return (TResult)appdomain.Invoke(method, null, p1, p2, p3);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new FunctionDelegateAdapter<T1, T2, T3, TResult>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new FunctionDelegateAdapter<T1, T2, T3, TResult>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n        public override void Combine(Delegate dele)\n        {\n            action += (Func<T1, T2, T3, TResult>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Func<T1, T2, T3, TResult>)dele;\n        }\n    }\n\n    class FunctionDelegateAdapter<T1, T2, T3, T4, TResult> : DelegateAdapter\n    {\n        Func<T1, T2, T3, T4, TResult> action;\n\n        public FunctionDelegateAdapter()\n        {\n\n        }\n\n        private FunctionDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        TResult InvokeILMethod(T1 p1, T2 p2, T3 p3, T4 p4)\n        {\n            if (method.HasThis)\n                return (TResult)appdomain.Invoke(method, instance, p1, p2, p3, p4);\n            else\n                return (TResult)appdomain.Invoke(method, null, p1, p2, p3, p4);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new FunctionDelegateAdapter<T1, T2, T3, T4, TResult>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new FunctionDelegateAdapter<T1, T2, T3, T4, TResult>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Func<T1, T2, T3, T4, TResult>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Func<T1, T2, T3, T4, TResult>)dele;\n        }\n    }\n    #endregion\n\n    #region Methods\n    class MethodDelegateAdapter<T1> : DelegateAdapter\n    {\n        Action<T1> action;\n\n        public MethodDelegateAdapter()\n        {\n\n        }\n\n        private MethodDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        void InvokeILMethod(T1 p1)\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, p1);\n            else\n                appdomain.Invoke(method, null, p1);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new MethodDelegateAdapter<T1>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new MethodDelegateAdapter<T1>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Action<T1>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Action<T1>)dele;\n        }\n    }\n\n    class MethodDelegateAdapter<T1, T2> : DelegateAdapter\n    {\n        Action<T1, T2> action;\n\n        public MethodDelegateAdapter()\n        {\n\n        }\n\n        private MethodDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        void InvokeILMethod(T1 p1, T2 p2)\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, p1, p2);\n            else\n                appdomain.Invoke(method, instance, p1, p2);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new MethodDelegateAdapter<T1, T2>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new MethodDelegateAdapter<T1, T2>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Action<T1, T2>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Action<T1, T2>)dele;\n        }\n    }\n\n    class MethodDelegateAdapter<T1, T2, T3> : DelegateAdapter\n    {\n        Action<T1, T2, T3> action;\n\n        public MethodDelegateAdapter()\n        {\n\n        }\n\n        private MethodDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        void InvokeILMethod(T1 p1, T2 p2, T3 p3)\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, p1, p2, p3);\n            else\n                appdomain.Invoke(method, null, p1, p2, p3);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new MethodDelegateAdapter<T1, T2, T3>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new MethodDelegateAdapter<T1, T2, T3>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Action<T1, T2, T3>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Action<T1, T2, T3>)dele;\n        }\n    }\n\n    class MethodDelegateAdapter<T1, T2, T3, T4> : DelegateAdapter\n    {\n        Action<T1, T2, T3, T4> action;\n\n        public MethodDelegateAdapter()\n        {\n\n        }\n\n        private MethodDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        void InvokeILMethod(T1 p1, T2 p2, T3 p3, T4 p4)\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, p1, p2, p3, p4);\n            else\n                appdomain.Invoke(method, null, p1, p2, p3, p4);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new MethodDelegateAdapter<T1, T2, T3, T4>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new MethodDelegateAdapter<T1, T2, T3, T4>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Action<T1, T2, T3, T4>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Action<T1, T2, T3, T4>)dele;\n        }\n    }\n\n    class MethodDelegateAdapter : DelegateAdapter\n    {\n        Action action;\n        \n        public MethodDelegateAdapter()\n        {\n\n        }\n\n        protected MethodDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        void InvokeILMethod()\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, null);\n            else\n                appdomain.Invoke(method, null, null);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new MethodDelegateAdapter(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new MethodDelegateAdapter(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Action)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Action)dele;\n        }\n    }\n\n    class DummyDelegateAdapter : DelegateAdapter\n    {\n        public DummyDelegateAdapter()\n        {\n\n        }\n\n        protected DummyDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            \n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                ThrowAdapterNotFound(method);\n                return null;\n            }\n        }\n\n        void InvokeILMethod()\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, null);\n            else\n                appdomain.Invoke(method, null, null);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new DummyDelegateAdapter(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new DummyDelegateAdapter(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            ThrowAdapterNotFound(method);\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            ThrowAdapterNotFound(method);\n        }\n    }\n    #endregion\n    abstract class DelegateAdapter : ILTypeInstance, IDelegateAdapter\n    {\n        protected ILMethod method;\n        protected ILTypeInstance instance;\n        protected Enviorment.AppDomain appdomain;\n        Dictionary<Type, Delegate> converters;\n        IDelegateAdapter next;\n        protected bool isClone;\n\n        public abstract Delegate Delegate { get; }\n\n        public IDelegateAdapter Next { get { return next; } }\n\n        public ILTypeInstance Instance { get { return instance; } }\n\n        public ILMethod Method { get { return method; } }\n\n        protected DelegateAdapter() { }\n\n        protected DelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            this.appdomain = appdomain;\n            this.instance = instance;\n            this.method = method;\n            CLRInstance = this;\n        }\n\n        public override bool IsValueType\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        public unsafe StackObject* ILInvoke(ILIntepreter intp, StackObject* esp, IList<object> mStack)\n        {\n            var ebp = esp;\n            esp = ILInvokeSub(intp, esp, mStack);\n            return ClearStack(intp, esp, ebp, mStack);\n        }\n\n        unsafe StackObject* ILInvokeSub(ILIntepreter intp, StackObject* esp, IList<object> mStack)\n        {\n            var ebp = esp;\n            bool unhandled;\n            if (method.HasThis)\n                esp = ILIntepreter.PushObject(esp, mStack, instance);\n            int paramCnt = method.ParameterCount;\n            for(int i = paramCnt; i > 0; i--)\n            {\n                intp.CopyToStack(esp, Minus(ebp, i), mStack);\n                esp++;\n            }\n            var ret = intp.Execute(method, esp, out unhandled);\n            if (next != null)\n            {\n                if (method.ReturnType != appdomain.VoidType)\n                {\n                    intp.Free(ret - 1);//Return value for multicast delegate doesn't make sense, only return the last one's value\n                }\n                DelegateAdapter n = (DelegateAdapter)next;\n                ret = n.ILInvokeSub(intp, ebp, mStack);\n\n            }\n            return ret;\n        }\n\n        unsafe StackObject* ClearStack(ILIntepreter intp, StackObject* esp, StackObject* ebp, IList<object> mStack)\n        {\n            int paramCnt = method.ParameterCount;\n            object retObj = null;\n            StackObject retSObj = StackObject.Null;\n            bool hasReturn = method.ReturnType != appdomain.VoidType;\n            if (hasReturn)\n            {\n                var ret = esp - 1;\n                retSObj = *ret;\n                if(ret->ObjectType>= ObjectTypes.Object)\n                {\n                    retObj = mStack[ret->Value];\n                }\n                intp.Free(ret);\n            }\n            for (int i = 1; i <= paramCnt; i++)\n            {\n                intp.Free(ebp - i);\n            }\n            var returnVal = Minus(ebp, paramCnt + 1);\n            intp.Free(returnVal);//Free delegateInstance\n            if (hasReturn)\n            {\n                *returnVal = retSObj;\n                if(retObj != null)\n                {\n                    returnVal->Value = mStack.Count;\n                    mStack.Add(retObj);\n                }\n                returnVal++;\n            }\n            return returnVal;\n        }\n\n        public abstract IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method);\n\n        public new abstract IDelegateAdapter Clone();\n\n        public bool IsClone\n        {\n            get\n            {\n                return isClone;\n            }\n        }\n\n        public virtual void Combine(IDelegateAdapter adapter)\n        {\n            if (next != null)\n                next.Combine(adapter);\n            else\n                next = adapter;\n        }\n\n        public abstract void Combine(Delegate dele);\n\n        public virtual void Remove(IDelegateAdapter adapter)\n        {\n            if (next != null)\n            {\n                if (next.Equals(adapter))\n                {\n                    next = ((DelegateAdapter)next).next;\n                }\n                else\n                    next.Remove(adapter);\n            }\n        }\n\n        public abstract void Remove(Delegate dele);\n\n        public virtual bool Equals(IDelegateAdapter adapter)\n        {\n            if (adapter is DelegateAdapter)\n            {\n                DelegateAdapter b = (DelegateAdapter)adapter;\n                return instance == b.instance && method == b.method;\n            }\n            else\n                return false;\n        }\n\n        public virtual bool Equals(Delegate dele)\n        {\n            return Delegate == dele;\n        }\n\n        public override string ToString()\n        {\n            return method.ToString();\n        }\n\n        public Delegate GetConvertor(Type type)\n        {\n            if (converters == null)\n                converters = new Dictionary<System.Type, Delegate>(new ByReferenceKeyComparer<Type>());\n            Delegate res;\n            if (converters.TryGetValue(type, out res))\n                return res;\n            else\n            {\n                res = appdomain.DelegateManager.ConvertToDelegate(type, this);\n                converters[type] = res;\n                return res;\n            }\n        }\n\n        unsafe StackObject* Minus(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a - sizeof(StackObject) * b);\n        }\n\n        public static void ThrowAdapterNotFound(IMethod method)\n        {\n            StringBuilder sb = new StringBuilder();\n            sb.Append(\"Cannot find Delegate Adapter for:\");\n            sb.Append(method.ToString());\n            string clsName, rName;\n            bool isByRef;\n            if (method.ReturnType.Name != \"Void\" || method.ParameterCount > 0)\n            {\n                sb.AppendLine(\", Please add following code:\");\n                if (method.ReturnType.Name == \"Void\")\n                {\n                    sb.Append(\"appdomain.DelegateManager.RegisterMethodDelegate<\");\n                    bool first = true;\n                    foreach(var i in method.Parameters)\n                    {\n                        if (first)\n                        {\n                            first = false;\n                        }\n                        else\n                        {\n                            sb.Append(\", \");\n                        }\n                        i.TypeForCLR.GetClassName(out clsName, out rName, out isByRef);\n                        sb.Append(rName);                        \n                    }\n                    sb.AppendLine(\">();\");\n                }\n                else\n                {\n                    sb.Append(\"appdomain.DelegateManager.RegisterFunctionDelegate<\");\n                    bool first = true;\n                    foreach (var i in method.Parameters)\n                    {\n                        if (first)\n                        {\n                            first = false;\n                        }\n                        else\n                        {\n                            sb.Append(\", \");\n                        }\n                        i.TypeForCLR.GetClassName(out clsName, out rName, out isByRef);\n                        sb.Append(rName);\n                    }\n                    if (!first)\n                        sb.Append(\", \");\n                    method.ReturnType.TypeForCLR.GetClassName(out clsName, out rName, out isByRef);\n                    sb.Append(rName);\n                    sb.AppendLine(\">();\");\n                }\n            }\n            throw new KeyNotFoundException(sb.ToString());\n        }\n    }\n\n    unsafe interface IDelegateAdapter\n    {\n        Delegate Delegate { get; }\n        IDelegateAdapter Next { get; }\n        ILTypeInstance Instance { get; }\n        ILMethod Method { get; }\n        StackObject* ILInvoke(ILIntepreter intp, StackObject* esp, IList<object> mStack);\n        IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method);\n        bool IsClone { get; }\n        IDelegateAdapter Clone();\n        Delegate GetConvertor(Type type);\n        void Combine(IDelegateAdapter adapter);\n        void Combine(Delegate dele);\n        void Remove(IDelegateAdapter adapter);\n        void Remove(Delegate dele);\n        bool Equals(IDelegateAdapter adapter);\n        bool Equals(Delegate dele);\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Intepreter/ILIntepreter.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\n\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Intepreter.OpCodes;\nusing ILRuntime.Runtime.Debugger;\nusing ILRuntime.CLR.Utils;\nusing ILRuntime.Other;\n\nnamespace ILRuntime.Runtime.Intepreter\n{\n    public unsafe class ILIntepreter\n    {\n        Enviorment.AppDomain domain;\n        RuntimeStack stack;\n        object _lockObj;\n        bool allowUnboundCLRMethod;\n\n        public RuntimeStack Stack { get { return stack; } }\n        public bool ShouldBreak { get; set; }\n        public StepTypes CurrentStepType { get; set; }\n        public StackObject* LastStepFrameBase { get; set; }\n        public int LastStepInstructionIndex { get; set; }\n        StackObject* ValueTypeBasePointer;\n        public ILIntepreter(Enviorment.AppDomain domain)\n        {\n            this.domain = domain;\n            stack = new RuntimeStack(this);\n            allowUnboundCLRMethod = domain.AllowUnboundCLRMethod;\n#if DEBUG\n            _lockObj = new object();\n#endif\n        }\n\n        public Enviorment.AppDomain AppDomain { get { return domain; } }\n\n        public void Break()\n        {\n            //Clear old debug state\n            ClearDebugState();\n            lock (_lockObj)\n                Monitor.Wait(_lockObj);\n        }\n\n        public void Resume()\n        {\n            lock (_lockObj)\n                Monitor.Pulse(_lockObj);\n        }\n\n        public void ClearDebugState()\n        {\n            ShouldBreak = false;\n            CurrentStepType = StepTypes.None;\n            LastStepFrameBase = (StackObject*)0;\n            LastStepInstructionIndex = 0;\n        }\n        public object Run(ILMethod method, object instance, object[] p)\n        {\n            IList<object> mStack = stack.ManagedStack;\n            int mStackBase = mStack.Count;\n            StackObject* esp = stack.StackBase;\n            stack.ResetValueTypePointer();\n            if (method.HasThis)\n            {\n                if (instance is CrossBindingAdaptorType)\n                    instance = ((CrossBindingAdaptorType)instance).ILInstance;\n                if (instance == null)\n                    throw new NullReferenceException(\"instance should not be null!\");\n                esp = PushObject(esp, mStack, instance);\n            }\n            esp = PushParameters(method, esp, p);\n            bool unhandledException;\n            esp = Execute(method, esp, out unhandledException);\n            object result = method.ReturnType != domain.VoidType ? method.ReturnType.TypeForCLR.CheckCLRTypes(StackObject.ToObject((esp - 1), domain, mStack)) : null;\n            //ClearStack\n#if DEBUG\n            ((List<object>)mStack).RemoveRange(mStackBase, mStack.Count - mStackBase);\n#else\n            ((UncheckedList<object>)mStack).RemoveRange(mStackBase, mStack.Count - mStackBase);\n#endif\n            return result;\n        }\n        internal StackObject* Execute(ILMethod method, StackObject* esp, out bool unhandledException)\n        {\n            if (method == null)\n                throw new NullReferenceException();\n#if UNITY_EDITOR\n            if (System.Threading.Thread.CurrentThread.ManagedThreadId == AppDomain.UnityMainThreadID)\n\n#if UNITY_5_5_OR_NEWER\n                UnityEngine.Profiling.Profiler.BeginSample(method.ToString());\n#else\n                UnityEngine.Profiler.BeginSample(method.ToString());\n#endif\n\n#endif\n            OpCode[] body = method.Body;\n            StackFrame frame;\n            stack.InitializeFrame(method, esp, out frame);\n            StackObject* v1 = frame.LocalVarPointer;\n            StackObject* v2 = frame.LocalVarPointer + 1;\n            StackObject* v3 = frame.LocalVarPointer + 1 + 1;\n            StackObject* v4 = Add(frame.LocalVarPointer, 3);\n            int finallyEndAddress = 0;\n\n            esp = frame.BasePointer;\n            StackObject* arg = Minus(frame.LocalVarPointer, method.ParameterCount);\n            IList<object> mStack = stack.ManagedStack;\n            int paramCnt = method.ParameterCount;\n            if (method.HasThis)//this parameter is always object reference\n            {\n                arg--;\n                paramCnt++;\n            }\n            unhandledException = false;\n\n            //Managed Stack reserved for arguments(In case of starg)\n            for (int i = 0; i < paramCnt; i++)\n            {\n                var a = Add(arg, i);\n                switch (a->ObjectType)\n                {\n                    case ObjectTypes.Null:\n                        //Need to reserve place for null, in case of starg\n                        a->ObjectType = ObjectTypes.Object;\n                        a->Value = mStack.Count;\n                        mStack.Add(null);\n                        break;\n                    case ObjectTypes.ValueTypeObjectReference:\n                        CloneStackValueType(a, a, mStack);\n                        break;\n                    case ObjectTypes.Object:\n                    case ObjectTypes.FieldReference:\n                    case ObjectTypes.ArrayReference:\n                        frame.ManagedStackBase--;\n                        break;\n                }\n            }\n\n            stack.PushFrame(ref frame);\n\n            int locBase = mStack.Count;\n            //Managed Stack reserved for local variable\n            for (int i = 0; i < method.LocalVariableCount; i++)\n            {\n                mStack.Add(null);\n            }\n\n            for (int i = 0; i < method.LocalVariableCount; i++)\n            {\n                var v = method.Variables[i];\n                if (v.VariableType.IsValueType && !v.VariableType.IsPrimitive)\n                {\n                    var t = AppDomain.GetType(v.VariableType, method.DeclearingType, method);\n                    if (t is ILType)\n                    {\n                        //var obj = ((ILType)t).Instantiate(false);\n                        var loc = Add(v1, i);\n                        stack.AllocValueType(loc, t);\n\n                        /*loc->ObjectType = ObjectTypes.Object;\n                        loc->Value = mStack.Count;\n                        mStack.Add(obj);*/\n\n                    }\n                    else\n                    {\n                        CLRType cT = (CLRType)t;\n                        var loc = Add(v1, i);\n                        if (cT.ValueTypeBinder != null)\n                        {\n                            stack.AllocValueType(loc, t);\n                        }\n                        else\n                        {\n                            var obj = ((CLRType)t).CreateDefaultInstance();\n                            loc->ObjectType = ObjectTypes.Object;\n                            loc->Value = locBase + i;\n                            mStack[locBase + i] = obj;\n                        }\n                    }\n                }\n                else\n                {\n                    if (v.VariableType.IsPrimitive)\n                    {\n                        var t = AppDomain.GetType(v.VariableType, method.DeclearingType, method);\n                        var loc = Add(v1, i);\n                        StackObject.Initialized(loc, t);\n                    }\n                    else\n                    {\n                        var loc = Add(v1, i);\n                        loc->ObjectType = ObjectTypes.Object;\n                        loc->Value = locBase + i;\n                    }\n                }\n            }\n            var bp = stack.ValueTypeStackPointer;\n            ValueTypeBasePointer = bp;\n            fixed (OpCode* ptr = body)\n            {\n                OpCode* ip = ptr;\n                OpCodeEnum code = ip->Code;\n                bool returned = false;\n                while (!returned)\n                {\n                    try\n                    {\n#if DEBUG\n                        if (ShouldBreak)\n                            Break();\n                        var insOffset = (int)(ip - ptr);\n                        frame.Address.Value = insOffset;\n                        AppDomain.DebugService.CheckShouldBreak(method, this, insOffset);\n#endif\n                        code = ip->Code;\n                        switch (code)\n                        {\n                            #region Arguments and Local Variable\n                            case OpCodeEnum.Ldarg_0:\n                                CopyToStack(esp, arg, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldarg_1:\n                                CopyToStack(esp, arg + 1, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldarg_2:\n                                CopyToStack(esp, arg + 1 + 1, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldarg_3:\n                                CopyToStack(esp, arg + 1 + 1 + 1, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldarg:\n                            case OpCodeEnum.Ldarg_S:\n                                CopyToStack(esp, Add(arg, ip->TokenInteger), mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldarga:\n                            case OpCodeEnum.Ldarga_S:\n                                {\n                                    var a = Add(arg, ip->TokenInteger);\n                                    esp->ObjectType = ObjectTypes.StackObjectReference;\n                                    *(StackObject**)&esp->Value = a;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Starg:\n                            case OpCodeEnum.Starg_S:\n                                {\n                                    var a = Add(arg, ip->TokenInteger);\n                                    var val = esp - 1;\n                                    int idx = a->Value;\n                                    bool isObj = a->ObjectType >= ObjectTypes.Object;\n                                    if (val->ObjectType >= ObjectTypes.Object)\n                                    {\n                                        a->ObjectType = val->ObjectType;\n                                        mStack[a->Value] = mStack[val->Value];\n                                        a->ValueLow = val->ValueLow;\n                                    }\n                                    else\n                                    {\n                                        *a = *val;\n                                        if (isObj)\n                                        {\n                                            a->Value = idx;\n                                            if (val->ObjectType == ObjectTypes.Null)\n                                            {\n                                                mStack[a->Value] = null;\n                                            }\n                                        }\n                                    }\n                                    Free(val);\n                                    esp--;\n                                }\n                                break;\n                            case OpCodeEnum.Stloc_0:\n                                {\n                                    esp--;\n                                    int idx = locBase;\n                                    StLocSub(esp, v1, bp, idx, mStack);\n                                }\n                                break;\n                            case OpCodeEnum.Ldloc_0:\n                                CopyToStack(esp, v1, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Stloc_1:\n                                {\n                                    esp--;\n                                    int idx = locBase + 1;\n                                    StLocSub(esp, v2, bp, idx, mStack);\n                                }\n                                break;\n                            case OpCodeEnum.Ldloc_1:\n                                CopyToStack(esp, v2, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Stloc_2:\n                                {\n                                    esp--;\n                                    int idx = locBase + 2;\n                                    StLocSub(esp, v3, bp, idx, mStack);\n                                    break;\n                                }\n                            case OpCodeEnum.Ldloc_2:\n                                CopyToStack(esp, v3, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Stloc_3:\n                                {\n                                    esp--;\n                                    int idx = locBase + 3;\n\n                                    StLocSub(esp, v4, bp, idx, mStack);\n                                }\n                                break;\n                            case OpCodeEnum.Ldloc_3:\n                                CopyToStack(esp, v4, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Stloc:\n                            case OpCodeEnum.Stloc_S:\n                                {\n                                    esp--;\n                                    var v = Add(frame.LocalVarPointer, ip->TokenInteger);\n                                    int idx = locBase + ip->TokenInteger;\n                                    StLocSub(esp, v, bp, idx, mStack);\n                                }\n                                break;\n                            case OpCodeEnum.Ldloc:\n                            case OpCodeEnum.Ldloc_S:\n                                {\n                                    var v = Add(frame.LocalVarPointer, ip->TokenInteger);\n                                    CopyToStack(esp, v, mStack);\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldloca:\n                            case OpCodeEnum.Ldloca_S:\n                                {\n                                    var v = Add(frame.LocalVarPointer, ip->TokenInteger);\n                                    esp->ObjectType = ObjectTypes.StackObjectReference;\n                                    *(StackObject**)&esp->Value = v;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldobj:\n                                {\n                                    var objRef = esp - 1;\n                                    switch (objRef->ObjectType)\n                                    {\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var t = AppDomain.GetType(ip->TokenInteger);\n                                                var obj = mStack[objRef->Value];\n                                                var idx = objRef->ValueLow;\n                                                Free(objRef);\n                                                LoadFromArrayReference(obj, idx, objRef, t, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.StackObjectReference:\n                                            {\n                                                var obj = GetObjectAndResolveReference(objRef);\n                                                *objRef = *obj;\n                                                if (objRef->ObjectType >= ObjectTypes.Object)\n                                                {\n                                                    objRef->Value = mStack.Count;\n                                                    mStack.Add(mStack[obj->Value]);\n                                                }\n                                            }\n                                            break;\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var obj = mStack[objRef->Value];\n                                                int idx = objRef->ValueLow;\n                                                Free(objRef);\n                                                if (obj is ILTypeInstance)\n                                                {\n                                                    ((ILTypeInstance)obj).PushToStack(idx, objRef, AppDomain, mStack);\n                                                }\n                                                else\n                                                {\n                                                    var t = AppDomain.GetType(ip->TokenInteger);\n                                                    obj = ((CLRType) t).GetFieldValue(idx, obj);\n                                                    PushObject(objRef, mStack, obj);\n                                                }\n                                            }\n                                            break;\n                                        case ObjectTypes.StaticFieldReference:\n                                            {\n                                                var t = AppDomain.GetType(objRef->Value);\n                                                int idx = objRef->ValueLow;\n                                                Free(objRef);\n                                                if (t is ILType)\n                                                {\n                                                    ((ILType)t).StaticInstance.PushToStack(idx, objRef, AppDomain, mStack);\n                                                }\n                                                else\n                                                {\n                                                    var obj = ((CLRType)t).GetFieldValue(idx, null);\n                                                    PushObject(objRef, mStack, obj);\n                                                }\n                                            }\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Stobj:\n                                {\n                                    var objRef = esp - 1 - 1;\n                                    var val = esp - 1;\n                                    switch (objRef->ObjectType)\n                                    {\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var t = AppDomain.GetType(ip->TokenInteger);\n                                                StoreValueToArrayReference(objRef, val, t, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.StackObjectReference:\n                                            {\n                                                objRef = GetObjectAndResolveReference(objRef);\n                                                if (val->ObjectType >= ObjectTypes.Object)\n                                                {\n                                                    mStack[objRef->Value] = mStack[val->Value];\n                                                    objRef->ValueLow = val->ValueLow;\n                                                }\n                                                else\n                                                {\n                                                    *objRef = *val;\n                                                }\n                                            }\n                                            break;\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var obj = mStack[objRef->Value];\n                                                int idx = objRef->ValueLow;\n                                                if (obj is ILTypeInstance)\n                                                {\n                                                    ((ILTypeInstance)obj).AssignFromStack(idx, val, AppDomain, mStack);\n                                                }\n                                                else\n                                                {\n                                                    var t = AppDomain.GetType(ip->TokenInteger);\n                                                    ((CLRType)t).SetFieldValue(idx, ref obj, t.TypeForCLR.CheckCLRTypes(StackObject.ToObject(val, AppDomain, mStack)));\n                                                }\n                                            }\n                                            break;\n                                        case ObjectTypes.StaticFieldReference:\n                                            {\n                                                var t = AppDomain.GetType(objRef->Value);\n                                                if (t is ILType)\n                                                {\n                                                    ((ILType)t).StaticInstance.AssignFromStack(objRef->ValueLow, val, AppDomain, mStack);\n                                                }\n                                                else\n                                                {\n                                                    ((CLRType)t).SetStaticFieldValue(objRef->ValueLow, t.TypeForCLR.CheckCLRTypes(StackObject.ToObject(val, AppDomain, mStack)));\n                                                }\n                                            }\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                }\n                                break;\n                            #endregion\n\n                            #region Load Constants\n                            case OpCodeEnum.Ldc_I4_M1:\n                                esp->Value = -1;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_0:\n                                esp->Value = 0;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_1:\n                                esp->Value = 1;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_2:\n                                esp->Value = 2;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_3:\n                                esp->Value = 3;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_4:\n                                esp->Value = 4;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_5:\n                                esp->Value = 5;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_6:\n                                esp->Value = 6;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_7:\n                                esp->Value = 7;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_8:\n                                esp->Value = 8;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4:\n                            case OpCodeEnum.Ldc_I4_S:\n                                esp->Value = ip->TokenInteger;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I8:\n                                {\n                                    *(long*)(&esp->Value) = ip->TokenLong;\n                                    esp->ObjectType = ObjectTypes.Long;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldc_R4:\n                                {\n                                    *(float*)(&esp->Value) = *(float*)&ip->TokenInteger;\n                                    esp->ObjectType = ObjectTypes.Float;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldc_R8:\n                                {\n                                    *(double*)(&esp->Value) = *(double*)&ip->TokenLong;\n                                    esp->ObjectType = ObjectTypes.Double;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldnull:\n                                {\n                                    esp = PushNull(esp);\n                                }\n                                break;\n                            case OpCodeEnum.Ldind_I:\n                            case OpCodeEnum.Ldind_I1:\n                            case OpCodeEnum.Ldind_I2:\n                            case OpCodeEnum.Ldind_I4:\n                            case OpCodeEnum.Ldind_U1:\n                            case OpCodeEnum.Ldind_U2:\n                            case OpCodeEnum.Ldind_U4:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var dst = esp - 1;\n                                    switch (val->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromFieldReference(instance, idx, dst, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromArrayReference(instance, idx, dst, instance.GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                dst->ObjectType = ObjectTypes.Integer;\n                                                dst->Value = val->Value;\n                                                dst->ValueLow = 0;\n                                            }\n                                            break;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldind_I8:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var dst = esp - 1;\n                                    switch (val->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromFieldReference(instance, idx, dst, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromArrayReference(instance, idx, dst, instance.GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                *dst = *val;\n                                                dst->ObjectType = ObjectTypes.Long;\n                                                dst->ValueLow = 0;\n                                            }\n                                            break;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldind_R4:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var dst = esp - 1;\n                                    switch (val->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromFieldReference(instance, idx, dst, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromArrayReference(instance, idx, dst, instance.GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                dst->ObjectType = ObjectTypes.Float;\n                                                dst->Value = val->Value;\n                                                dst->ValueLow = 0;\n                                            }\n                                            break;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldind_R8:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var dst = esp - 1;\n                                    switch (val->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromFieldReference(instance, idx, dst, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromArrayReference(instance, idx, dst, instance.GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                *dst = *val;\n                                                dst->ObjectType = ObjectTypes.Double;\n                                            }\n                                            break;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldind_Ref:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var dst = esp - 1;\n                                    switch (val->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromFieldReference(instance, idx, dst, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromArrayReference(instance, idx, dst, instance.GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                dst->ObjectType = ObjectTypes.Object;\n                                                dst->Value = mStack.Count;\n                                                mStack.Add(mStack[val->Value]);\n                                            }\n                                            break;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Stind_I:\n                            case OpCodeEnum.Stind_I1:\n                            case OpCodeEnum.Stind_I2:\n                            case OpCodeEnum.Stind_I4:\n                            case OpCodeEnum.Stind_R4:\n                                {\n                                    var dst = GetObjectAndResolveReference(esp - 1 - 1);\n                                    var val = esp - 1;\n                                    switch (dst->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                StoreValueToFieldReference(mStack[dst->Value], dst->ValueLow, val, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                StoreValueToArrayReference(dst, val, mStack[dst->Value].GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                dst->Value = val->Value;\n                                            }\n                                            break;\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stind_I8:\n                            case OpCodeEnum.Stind_R8:\n                                {\n                                    var dst = GetObjectAndResolveReference(esp - 1 - 1);\n                                    var val = esp - 1;\n                                    switch (dst->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                StoreValueToFieldReference(mStack[dst->Value], dst->ValueLow, val, mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                dst->Value = val->Value;\n                                                dst->ValueLow = val->ValueLow;\n                                            }\n                                            break;\n                                    }\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stind_Ref:\n                                {\n                                    var dst = GetObjectAndResolveReference(esp - 1 - 1);\n                                    var val = esp - 1;\n                                    switch (dst->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                StoreValueToFieldReference(mStack[dst->Value], dst->ValueLow, val, mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                switch (val->ObjectType)\n                                                {\n                                                    case ObjectTypes.Object:\n                                                        mStack[dst->Value] = mStack[val->Value];\n                                                        break;\n                                                    case ObjectTypes.Null:\n                                                        mStack[dst->Value] = null;\n                                                        break;\n                                                    default:\n                                                        throw new NotImplementedException();\n                                                }\n                                            }\n                                            break;\n                                    }\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldstr:\n                                esp = PushObject(esp, mStack, AppDomain.GetString(ip->TokenLong));\n                                break;\n                            #endregion\n\n                            #region Althemetics\n                            case OpCodeEnum.Add:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) + *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value + b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *((float*)&esp->Value) = *((float*)&a->Value) + *((float*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *((double*)&esp->Value) = *((double*)&a->Value) + *((double*)&b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Sub:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) - *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value - b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *((float*)&esp->Value) = *((float*)&a->Value) - *((float*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *((double*)&esp->Value) = *((double*)&a->Value) - *((double*)&b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Mul:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) * *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value * b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *((float*)&esp->Value) = *((float*)&a->Value) * *((float*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *((double*)&esp->Value) = *((double*)&a->Value) * *((double*)&b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Div:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) / *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value / b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *((float*)&esp->Value) = *((float*)&a->Value) / *((float*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *((double*)&esp->Value) = *((double*)&a->Value) / *((double*)&b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Div_Un:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((ulong*)&esp->Value) = *((ulong*)&a->Value) / *((ulong*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = (int)((uint)a->Value / (uint)b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Rem:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) % *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value % b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *(float*)&esp->Value = *(float*)&a->Value % *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *(double*)&esp->Value = *(double*)&a->Value % *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Rem_Un:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((ulong*)&esp->Value) = *((ulong*)&a->Value) % *((ulong*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = (int)((uint)a->Value % (uint)b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Xor:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) ^ *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value ^ b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.And:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) & *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value & b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Or:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) | *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value | b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Shl:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    int bits = b->Value;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) << bits;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value << bits;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Shr:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    int bits = b->Value;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) >> bits;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value >> bits;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Shr_Un:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    int bits = b->Value;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((ulong*)&esp->Value) = *((ulong*)&a->Value) >> bits;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            *(uint*)&esp->Value = (uint)a->Value >> bits;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Not:\n                                {\n                                    StackObject* a = esp - 1;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&a->Value) = ~*((long*)&a->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            a->Value = ~a->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Neg:\n                                {\n                                    StackObject* a = esp - 1;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&a->Value) = -*((long*)&a->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            a->Value = -a->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *((float*)&a->Value) = -*((float*)&a->Value);\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *((double*)&a->Value) = -*((double*)&a->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                }\n                                break;\n                            #endregion\n\n                            #region Control Flows\n                            case OpCodeEnum.Ret:\n                                returned = true;\n                                break;\n                            case OpCodeEnum.Brtrue:\n                            case OpCodeEnum.Brtrue_S:\n                                {\n                                    esp--;\n                                    bool res = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            res = esp->Value != 0;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = *(long*)&esp->Value != 0;\n                                            break;\n                                        case ObjectTypes.Object:\n                                            res = mStack[esp->Value] != null;\n                                            break;\n                                    }\n                                    if (res)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        Free(esp);\n                                        continue;\n                                    }\n                                    else\n                                        Free(esp);\n                                }\n                                break;\n                            case OpCodeEnum.Brfalse:\n                            case OpCodeEnum.Brfalse_S:\n                                {\n                                    esp--;\n                                    bool res = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Null:\n                                            res = true;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            res = esp->Value == 0;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = *(long*)&esp->Value == 0;\n                                            break;\n                                        case ObjectTypes.Object:\n                                            res = mStack[esp->Value] == null;\n                                            Free(esp);\n                                            break;\n                                        default:\n                                            Free(esp);\n                                            break;\n                                    }\n                                    if (res)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Beq:\n                            case OpCodeEnum.Beq_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    bool transfer = false;\n                                    if (a->ObjectType == b->ObjectType)\n                                    {\n                                        switch (a->ObjectType)\n                                        {\n                                            case ObjectTypes.Null:\n                                                transfer = true;\n                                                break;\n                                            case ObjectTypes.Integer:\n                                                transfer = a->Value == b->Value;\n                                                break;\n                                            case ObjectTypes.Long:\n                                                transfer = *(long*)&a->Value == *(long*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Float:\n                                                transfer = *(float*)&a->Value == *(float*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Double:\n                                                transfer = *(double*)&a->Value == *(double*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Object:\n                                                transfer = mStack[a->Value] == mStack[b->Value];\n                                                break;\n                                            default:\n                                                throw new NotImplementedException();\n                                        }\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Bne_Un:\n                            case OpCodeEnum.Bne_Un_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    bool transfer = false;\n                                    if (a->ObjectType == b->ObjectType)\n                                    {\n                                        switch (a->ObjectType)\n                                        {\n                                            case ObjectTypes.Null:\n                                                transfer = false;\n                                                break;\n                                            case ObjectTypes.Integer:\n                                                transfer = (uint)a->Value != (uint)b->Value;\n                                                break;\n                                            case ObjectTypes.Float:\n                                                transfer = *(float*)&a->Value != *(float*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Long:\n                                                transfer = *(long*)&a->Value != *(long*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Double:\n                                                transfer = *(double*)&a->Value != *(double*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Object:\n                                                transfer = mStack[a->Value] != mStack[b->Value];\n                                                break;\n                                            default:\n                                                throw new NotImplementedException();\n                                        }\n                                    }\n                                    else\n                                        transfer = true;\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Bgt:\n                            case OpCodeEnum.Bgt_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = a->Value > b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(long*)&a->Value > *(long*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value > *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value > *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Bgt_Un:\n                            case OpCodeEnum.Bgt_Un_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = (uint)a->Value > (uint)b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(ulong*)&a->Value > *(ulong*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value > *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value > *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Bge:\n                            case OpCodeEnum.Bge_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = a->Value >= b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(long*)&a->Value >= *(long*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value >= *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value >= *(double*)&b->Value;\n                                            break;\n\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Bge_Un:\n                            case OpCodeEnum.Bge_Un_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = (uint)a->Value >= (uint)b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(ulong*)&a->Value >= *(ulong*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value >= *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value >= *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Blt:\n                            case OpCodeEnum.Blt_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = a->Value < b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(long*)&a->Value < *(long*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value < *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value < *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Blt_Un:\n                            case OpCodeEnum.Blt_Un_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = (uint)a->Value < (uint)b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(ulong*)&a->Value < *(ulong*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value < *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value < *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Ble:\n                            case OpCodeEnum.Ble_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = a->Value <= b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(long*)&a->Value <= *(long*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value <= *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value <= *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Ble_Un:\n                            case OpCodeEnum.Ble_Un_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = (uint)a->Value <= (uint)b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(ulong*)&a->Value <= *(ulong*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value <= *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value <= *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Br_S:\n                            case OpCodeEnum.Br:\n                                ip = ptr + ip->TokenInteger;\n                                continue;\n                            case OpCodeEnum.Switch:\n                                {\n                                    var val = (esp - 1)->Value;\n                                    Free(esp - 1);\n                                    esp--;\n                                    var table = method.JumpTables[ip->TokenInteger];\n                                    if (val >= 0 && val < table.Length)\n                                    {\n                                        ip = ptr + table[val];\n                                        continue;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Leave:\n                            case OpCodeEnum.Leave_S:\n                                {\n                                    if (method.ExceptionHandler != null)\n                                    {\n                                        ExceptionHandler eh = null;\n\n                                        int addr = ip->TokenInteger;\n                                        var sql = from e in method.ExceptionHandler\n                                                  where addr == e.HandlerEnd + 1 && e.HandlerType == ExceptionHandlerType.Finally || e.HandlerType == ExceptionHandlerType.Fault\n                                                  select e;\n                                        eh = sql.FirstOrDefault();\n                                        if (eh != null)\n                                        {\n                                            finallyEndAddress = ip->TokenInteger;\n                                            ip = ptr + eh.HandlerStart;\n                                            continue;\n                                        }\n                                    }\n                                    ip = ptr + ip->TokenInteger;\n                                    continue;\n                                }\n                            case OpCodeEnum.Endfinally:\n                                {\n                                    ip = ptr + finallyEndAddress;\n                                    finallyEndAddress = 0;\n                                    continue;\n                                }\n                            case OpCodeEnum.Call:\n                            case OpCodeEnum.Callvirt:\n                                {\n                                    IMethod m = domain.GetMethod(ip->TokenInteger);\n                                    if (m == null)\n                                    {\n                                        //Irrelevant method\n                                        int cnt = (int)ip->TokenLong;\n                                        //Balance the stack\n                                        for (int i = 0; i < cnt; i++)\n                                        {\n                                            Free(esp - 1);\n                                            esp--;\n                                        }\n                                    }\n                                    else\n                                    {\n                                        if (m is ILMethod)\n                                        {\n                                            ILMethod ilm = (ILMethod)m;\n                                            bool processed = false;\n                                            if (m.IsDelegateInvoke)\n                                            {\n                                                var instance = StackObject.ToObject((Minus(esp, m.ParameterCount + 1)), domain, mStack);\n                                                if (instance is IDelegateAdapter)\n                                                {\n                                                    esp = ((IDelegateAdapter)instance).ILInvoke(this, esp, mStack);\n                                                    processed = true;\n                                                }\n                                            }\n                                            if (!processed)\n                                            {\n                                                if (code == OpCodeEnum.Callvirt)\n                                                {\n                                                    var objRef = GetObjectAndResolveReference(Minus(esp, ilm.ParameterCount + 1));\n                                                    if (objRef->ObjectType == ObjectTypes.Null)\n                                                        throw new NullReferenceException();\n                                                    var obj = mStack[objRef->Value];\n                                                    if (obj == null)\n                                                        throw new NullReferenceException();\n                                                    ilm = ((ILTypeInstance)obj).Type.GetVirtualMethod(ilm) as ILMethod;\n                                                }\n                                                esp = Execute(ilm, esp, out unhandledException);\n                                                ValueTypeBasePointer = bp;\n                                                if (unhandledException)\n                                                    returned = true;\n                                            }\n                                        }\n                                        else\n                                        {\n                                            CLRMethod cm = (CLRMethod)m;\n                                            bool processed = false;\n                                            if (cm.IsDelegateInvoke)\n                                            {\n                                                var instance = StackObject.ToObject((Minus(esp, cm.ParameterCount + 1)), domain, mStack);\n                                                if (instance is IDelegateAdapter)\n                                                {\n                                                    esp = ((IDelegateAdapter)instance).ILInvoke(this, esp, mStack);\n                                                    processed = true;\n                                                }\n                                            }\n\n                                            if (!processed)\n                                            {\n                                                var redirect = cm.Redirection;\n                                                if (redirect != null)\n                                                    esp = redirect(this, esp, mStack, cm, false);\n                                                else\n                                                {\n#if DEBUG\n                                                    if (!allowUnboundCLRMethod)\n                                                        throw new NotSupportedException(cm.ToString() + \" is not bound!\");\n#endif\n#if UNITY_EDITOR\n                                                    if (System.Threading.Thread.CurrentThread.ManagedThreadId == AppDomain.UnityMainThreadID)\n\n#if UNITY_5_5_OR_NEWER\n                                                        UnityEngine.Profiling.Profiler.BeginSample(cm.ToString());\n#else\n                                                        UnityEngine.Profiler.BeginSample(cm.ToString());\n#endif\n#endif\n                                                    object result = cm.Invoke(this, esp, mStack);\n#if UNITY_EDITOR\n                                                    if (System.Threading.Thread.CurrentThread.ManagedThreadId == AppDomain.UnityMainThreadID)\n#if UNITY_5_5_OR_NEWER\n                                                        UnityEngine.Profiling.Profiler.EndSample();\n#else\n                                                        UnityEngine.Profiler.EndSample();\n#endif\n\n#endif\n                                                    if (result is CrossBindingAdaptorType)\n                                                        result = ((CrossBindingAdaptorType)result).ILInstance;\n                                                    int paramCount = cm.ParameterCount;\n                                                    for (int i = 1; i <= paramCount; i++)\n                                                    {\n                                                        Free(Minus(esp, i));\n                                                    }\n                                                    esp = Minus(esp, paramCount);\n                                                    if (cm.HasThis)\n                                                    {\n                                                        Free(esp - 1);\n                                                        esp--;\n                                                    }\n                                                    if (cm.ReturnType != AppDomain.VoidType && !cm.IsConstructor)\n                                                    {\n                                                        esp = PushObject(esp, mStack, result, cm.ReturnType.TypeForCLR == typeof(object));\n                                                    }\n                                                }\n                                            }\n                                        }\n\n                                    }\n                                }\n                                break;\n                            #endregion\n\n                            #region FieldOperation\n                            case OpCodeEnum.Stfld:\n                                {\n                                    var objRef = GetObjectAndResolveReference(esp - 1 - 1);\n                                    if (objRef->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                                    {\n                                        StackObject* dst = *(StackObject**)&objRef->Value;\n                                        var ft = domain.GetType(dst->Value);\n                                        if (ft is ILType)\n                                            CopyToValueTypeField(dst, (int)ip->TokenLong, esp - 1, mStack);\n                                        else\n                                            CopyToValueTypeField(dst, ((CLRType)ft).FieldIndexMapping[(int)ip->TokenLong], esp - 1, mStack);\n                                    }\n                                    else\n                                    {\n                                        object obj = RetriveObject(objRef, mStack);\n\n                                        if (obj != null)\n                                        {\n                                            if (obj is ILTypeInstance)\n                                            {\n                                                ILTypeInstance instance = obj as ILTypeInstance;\n                                                StackObject* val = esp - 1;\n                                                instance.AssignFromStack((int)ip->TokenLong, val, AppDomain, mStack);\n                                            }\n                                            else\n                                            {\n                                                var t = obj.GetType();\n                                                var type = AppDomain.GetType((int)(ip->TokenLong >> 32));\n                                                if (type != null)\n                                                {\n                                                    var val = esp - 1;\n                                                    var fieldToken = (int)ip->TokenLong;\n                                                    var f = ((CLRType)type).GetField(fieldToken);\n                                                    ((CLRType)type).SetFieldValue(fieldToken, ref obj, f.FieldType.CheckCLRTypes(CheckAndCloneValueType(StackObject.ToObject(val, domain, mStack), domain)));\n                                                    //Writeback\n                                                    if (t.IsValueType)\n                                                    {\n                                                        switch (objRef->ObjectType)\n                                                        {\n                                                            case ObjectTypes.Object:\n                                                                break;\n                                                            case ObjectTypes.FieldReference:\n                                                                {\n                                                                    var oldObj = mStack[objRef->Value];\n                                                                    int idx = objRef->ValueLow;\n                                                                    if (oldObj is ILTypeInstance)\n                                                                    {\n                                                                        ((ILTypeInstance)oldObj)[idx] = obj;\n                                                                    }\n                                                                    else\n                                                                    {\n                                                                        var it = AppDomain.GetType(oldObj.GetType());\n                                                                        ((CLRType)it).SetFieldValue(idx, ref oldObj, obj);\n                                                                    }\n                                                                }\n                                                                break;\n                                                            case ObjectTypes.StaticFieldReference:\n                                                                {\n                                                                    var it = AppDomain.GetType(objRef->Value);\n                                                                    int idx = objRef->ValueLow;\n                                                                    if (it is ILType)\n                                                                    {\n                                                                        ((ILType)it).StaticInstance[idx] = obj;\n                                                                    }\n                                                                    else\n                                                                    {\n                                                                        ((CLRType)it).SetStaticFieldValue(idx, obj);\n                                                                    }\n                                                                }\n                                                                break;\n                                                            default:\n                                                                throw new NotImplementedException();\n                                                        }\n                                                    }\n                                                }\n                                                else\n                                                    throw new TypeLoadException();\n                                            }\n                                        }\n                                        else\n                                            throw new NullReferenceException();\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldfld:\n                                {\n                                    StackObject* objRef = GetObjectAndResolveReference(esp - 1);\n                                    if (objRef->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                                    {\n                                        var dst = *(StackObject**)&objRef->Value;\n                                        var ft = domain.GetType(dst->Value);\n                                        if (ft is ILType)\n                                            dst = Minus(dst, (int)ip->TokenLong + 1);\n                                        else\n                                            dst = Minus(dst, ((CLRType)ft).FieldIndexMapping[(int)ip->TokenLong] + 1);\n                                        CopyToStack(objRef, dst, mStack);\n                                    }\n                                    else\n                                    {\n                                        object obj = RetriveObject(objRef, mStack);\n                                        Free(esp - 1);\n                                        if (obj != null)\n                                        {\n                                            if (obj is ILTypeInstance)\n                                            {\n                                                ILTypeInstance instance = obj as ILTypeInstance;\n                                                instance.PushToStack((int)ip->TokenLong, esp - 1, AppDomain, mStack);\n                                            }\n                                            else\n                                            {\n                                                //var t = obj.GetType();\n                                                var type = AppDomain.GetType((int)(ip->TokenLong >> 32));\n                                                if (type != null)\n                                                {\n                                                    var token = (int)ip->TokenLong;\n                                                    var ft = ((CLRType)type).GetField(token);\n                                                    var val = ((CLRType)type).GetFieldValue(token, obj);\n                                                    if (val is CrossBindingAdaptorType)\n                                                        val = ((CrossBindingAdaptorType)val).ILInstance;\n                                                    PushObject(esp - 1, mStack, val, ft.FieldType == typeof(object));\n                                                }\n                                                else\n                                                    throw new TypeLoadException();\n                                            }\n                                        }\n                                        else\n                                            throw new NullReferenceException();\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldflda:\n                                {\n                                    StackObject* objRef = GetObjectAndResolveReference(esp - 1);\n                                    if (objRef->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                                    {\n                                        var dst = esp - 1;\n                                        var ft = domain.GetType((int)(ip->TokenLong >> 32));\n                                        StackObject* fieldAddr;\n                                        if (ft is ILType)\n                                        {\n                                            fieldAddr = Minus(*(StackObject**)&objRef->Value, (int)ip->TokenLong + 1);                                            \n                                        }\n                                        else\n                                        {\n                                            fieldAddr = Minus(*(StackObject**)&objRef->Value, ((CLRType)ft).FieldIndexMapping[(int)ip->TokenLong] + 1);\n                                        }\n                                        dst->ObjectType = ObjectTypes.StackObjectReference;\n                                        *(StackObject**)&dst->Value = fieldAddr;\n                                    }\n                                    else\n                                    {\n                                        object obj = RetriveObject(objRef, mStack);\n\n                                        Free(esp - 1);\n                                        if (obj != null)\n                                        {\n                                            if (obj is ILTypeInstance)\n                                            {\n                                                ILTypeInstance instance = obj as ILTypeInstance;\n                                                instance.PushFieldAddress((int)ip->TokenLong, esp - 1, mStack);\n                                            }\n                                            else\n                                            {\n                                                objRef = esp - 1;\n                                                objRef->ObjectType = ObjectTypes.FieldReference;\n                                                objRef->Value = mStack.Count;\n                                                mStack.Add(obj);\n                                                objRef->ValueLow = (int)ip->TokenLong;\n                                            }\n                                        }\n                                        else\n                                            throw new NullReferenceException();\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Stsfld:\n                                {\n                                    IType type = AppDomain.GetType((int)(ip->TokenLong >> 32));\n                                    if (type != null)\n                                    {\n                                        if (type is ILType)\n                                        {\n                                            ILType t = type as ILType;\n                                            StackObject* val = esp - 1;\n                                            t.StaticInstance.AssignFromStack((int)ip->TokenLong, val, AppDomain, mStack);\n                                        }\n                                        else\n                                        {\n                                            CLRType t = type as CLRType;\n                                            int idx = (int)ip->TokenLong;\n                                            var f = t.GetField(idx);\n                                            StackObject* val = esp - 1;\n                                            t.SetStaticFieldValue(idx, f.FieldType.CheckCLRTypes(CheckAndCloneValueType(StackObject.ToObject(val, domain, mStack), domain)));\n                                        }\n                                    }\n                                    else\n                                        throw new TypeLoadException();\n                                    Free(esp - 1);\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldsfld:\n                                {\n                                    IType type = AppDomain.GetType((int)(ip->TokenLong >> 32));\n                                    if (type != null)\n                                    {\n                                        if (type is ILType)\n                                        {\n                                            ILType t = type as ILType;\n                                            t.StaticInstance.PushToStack((int)ip->TokenLong, esp, AppDomain, mStack);\n                                        }\n                                        else\n                                        {\n                                            CLRType t = type as CLRType;\n                                            int idx = (int)ip->TokenLong;\n                                            var f = t.GetField(idx);\n                                            var val = t.GetFieldValue(idx, null);\n                                            if (val is CrossBindingAdaptorType)\n                                                val = ((CrossBindingAdaptorType)val).ILInstance;\n                                            PushObject(esp, mStack, val, f.FieldType == typeof(object));\n                                        }\n                                    }\n                                    else\n                                        throw new TypeLoadException();\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldsflda:\n                                {\n                                    int type = (int)(ip->TokenLong >> 32);\n                                    int fieldIdx = (int)(ip->TokenLong);\n                                    esp->ObjectType = ObjectTypes.StaticFieldReference;\n                                    esp->Value = type;\n                                    esp->ValueLow = fieldIdx;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldtoken:\n                                {\n                                    switch (ip->TokenInteger)\n                                    {\n                                        case 0:\n                                            {\n                                                IType type = AppDomain.GetType((int)(ip->TokenLong >> 32));\n                                                if (type != null)\n                                                {\n                                                    if (type is ILType)\n                                                    {\n                                                        ILType t = type as ILType;\n                                                        t.StaticInstance.PushToStack((int)ip->TokenLong, esp, AppDomain, mStack);\n                                                    }\n                                                    else\n                                                        throw new NotImplementedException();\n                                                }\n                                            }\n                                            esp++;\n                                            break;\n                                        case 1:\n                                            {\n                                                IType type = AppDomain.GetType((int)ip->TokenLong);\n                                                if (type != null)\n                                                {\n                                                    esp = PushObject(esp, mStack, type.ReflectionType);\n                                                }\n                                                else\n                                                    throw new TypeLoadException();\n                                            }\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldftn:\n                                {\n                                    IMethod m = domain.GetMethod(ip->TokenInteger);\n                                    esp = PushObject(esp, mStack, m);\n                                }\n                                break;\n                            case OpCodeEnum.Ldvirtftn:\n                                {\n                                    IMethod m = domain.GetMethod(ip->TokenInteger);\n                                    var objRef = esp - 1;\n                                    if (m is ILMethod)\n                                    {\n                                        ILMethod ilm = (ILMethod)m;\n\n                                        var obj = mStack[objRef->Value];\n                                        m = ((ILTypeInstance)obj).Type.GetVirtualMethod(ilm) as ILMethod;\n                                    }\n                                    else\n                                    {\n                                        var obj = mStack[objRef->Value];\n                                        if (obj is ILTypeInstance)\n                                            m = ((ILTypeInstance)obj).Type.GetVirtualMethod(m);\n                                        else if (obj is CrossBindingAdaptorType)\n                                        {\n                                            m = ((CrossBindingAdaptorType)obj).ILInstance.Type.BaseType.GetVirtualMethod(m);\n                                        }\n                                    }\n                                    Free(objRef);\n                                    esp = PushObject(objRef, mStack, m);\n                                }\n                                break;\n                            #endregion\n\n                            #region Compare\n                            case OpCodeEnum.Ceq:\n                                {\n                                    StackObject* obj1 = esp - 1 - 1;\n                                    StackObject* obj2 = esp - 1;\n                                    bool res = false;\n                                    if (obj1->ObjectType == obj2->ObjectType)\n                                    {\n                                        switch (obj1->ObjectType)\n                                        {\n                                            case ObjectTypes.Integer:\n                                            case ObjectTypes.Float:\n                                                res = obj1->Value == obj2->Value;\n                                                break;\n                                            case ObjectTypes.Object:\n                                                res = mStack[obj1->Value] == mStack[obj2->Value];\n                                                break;\n                                            case ObjectTypes.FieldReference:\n                                                res = mStack[obj1->Value] == mStack[obj2->Value] && obj1->ValueLow == obj2->ValueLow;\n                                                break;\n                                            case ObjectTypes.Null:\n                                                res = true;\n                                                break;\n                                            default:\n                                                res = obj1->Value == obj2->Value && obj1->ValueLow == obj2->ValueLow;\n                                                break;\n                                        }\n                                    }\n                                    else\n                                    {\n                                        switch (obj1->ObjectType)\n                                        {\n                                            case ObjectTypes.Object:\n                                                res = mStack[obj1->Value] == null && obj2->ObjectType == ObjectTypes.Null;\n                                                break;\n                                            case ObjectTypes.Null:\n                                                res = obj2->ObjectType == ObjectTypes.Object && mStack[obj2->Value] == null;\n                                                break;\n                                        }\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    if (res)\n                                        esp = PushOne(esp - 1 - 1);\n                                    else\n                                        esp = PushZero(esp - 1 - 1);\n\n                                }\n                                break;\n                            case OpCodeEnum.Clt:\n                                {\n                                    StackObject* obj1 = esp - 1 - 1;\n                                    StackObject* obj2 = esp - 1;\n                                    bool res = false;\n                                    switch (obj1->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            res = obj1->Value < obj2->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = *(long*)&obj1->Value < *(long*)&obj2->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            res = *(float*)&obj1->Value < *(float*)&obj2->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            res = *(double*)&obj1->Value < *(double*)&obj2->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    if (res)\n                                        esp = PushOne(esp - 1 - 1);\n                                    else\n                                        esp = PushZero(esp - 1 - 1);\n                                }\n                                break;\n                            case OpCodeEnum.Clt_Un:\n                                {\n                                    StackObject* obj1 = esp - 1 - 1;\n                                    StackObject* obj2 = esp - 1;\n                                    bool res = false;\n                                    switch (obj1->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            res = (uint)obj1->Value < (uint)obj2->Value && obj2->ObjectType != ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = (ulong)*(long*)&obj1->Value < (ulong)*(long*)&obj2->Value && obj2->ObjectType != ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            res = *(float*)&obj1->Value < *(float*)&obj2->Value && obj2->ObjectType != ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            res = *(double*)&obj1->Value < *(double*)&obj2->Value && obj2->ObjectType != ObjectTypes.Null;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    if (res)\n                                        esp = PushOne(esp - 1 - 1);\n                                    else\n                                        esp = PushZero(esp - 1 - 1);\n                                }\n                                break;\n                            case OpCodeEnum.Cgt:\n                                {\n                                    StackObject* obj1 = esp - 1 - 1;\n                                    StackObject* obj2 = esp - 1;\n                                    bool res = false;\n                                    switch (obj1->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            res = obj1->Value > obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = *(long*)&obj1->Value > *(long*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            res = *(float*)&obj1->Value > *(float*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            res = *(double*)&obj1->Value > *(double*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    if (res)\n                                        esp = PushOne(esp - 1 - 1);\n                                    else\n                                        esp = PushZero(esp - 1 - 1);\n                                }\n                                break;\n                            case OpCodeEnum.Cgt_Un:\n                                {\n                                    StackObject* obj1 = esp - 1 - 1;\n                                    StackObject* obj2 = esp - 1;\n                                    bool res = false;\n                                    switch (obj1->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            res = ((uint)obj1->Value > (uint)obj2->Value) || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = (ulong)*(long*)&obj1->Value > (ulong)*(long*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            res = *(float*)&obj1->Value > *(float*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            res = *(double*)&obj1->Value > *(double*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Object:\n                                            res = mStack[obj1->Value] != null && obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Null:\n                                            res = false;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    if (res)\n                                        esp = PushOne(esp - 1 - 1);\n                                    else\n                                        esp = PushZero(esp - 1 - 1);\n                                }\n                                break;\n                            #endregion\n\n                            #region Initialization & Instantiation\n                            case OpCodeEnum.Newobj:\n                                {\n                                    IMethod m = domain.GetMethod(ip->TokenInteger);\n                                    if (m is ILMethod)\n                                    {\n                                        ILType type = m.DeclearingType as ILType;\n                                        if (type.IsDelegate)\n                                        {\n                                            var objRef = GetObjectAndResolveReference(esp - 1 - 1);\n                                            var mi = (IMethod)mStack[(esp - 1)->Value];\n                                            object ins;\n                                            if (objRef->ObjectType == ObjectTypes.Null)\n                                                ins = null;\n                                            else\n                                                ins = mStack[objRef->Value];\n                                            Free(esp - 1);\n                                            Free(esp - 1 - 1);\n                                            esp = esp - 1 - 1;\n                                            object dele;\n                                            if (mi is ILMethod)\n                                            {\n                                                if (ins != null)\n                                                {\n                                                    dele = ((ILTypeInstance)ins).GetDelegateAdapter((ILMethod)mi);\n                                                    if (dele == null)\n                                                        dele = domain.DelegateManager.FindDelegateAdapter((ILTypeInstance)ins, (ILMethod)mi);\n                                                }\n                                                else\n                                                {\n                                                    if (((ILMethod)mi).DelegateAdapter == null)\n                                                    {\n                                                        ((ILMethod)mi).DelegateAdapter = domain.DelegateManager.FindDelegateAdapter(null, (ILMethod)mi);\n                                                    }\n                                                    dele = ((ILMethod)mi).DelegateAdapter;\n                                                }\n                                            }\n\n                                            else\n                                            {\n                                                throw new NotImplementedException();\n                                            }\n                                            esp = PushObject(esp, mStack, dele);\n                                        }\n                                        else\n                                        {\n                                            var a = esp - m.ParameterCount;\n                                            StackObject* objRef;\n                                            ILTypeInstance obj = null;\n                                            bool isValueType = type.IsValueType;\n                                            if (isValueType)\n                                            {\n                                                stack.AllocValueType(esp, type);\n                                                objRef = esp + 1;\n                                                objRef->ObjectType = ObjectTypes.StackObjectReference;\n                                                *(StackObject**)&objRef->Value = esp;\n                                                objRef++;\n                                            }\n                                            else\n                                            {\n                                                obj = type.Instantiate(false);\n                                                objRef = PushObject(esp, mStack, obj);//this parameter for constructor\n                                            }\n                                            esp = objRef;\n                                            for (int i = 0; i < m.ParameterCount; i++)\n                                            {\n                                                CopyToStack(esp, a + i, mStack);\n                                                esp++;\n                                            }\n                                            esp = Execute((ILMethod)m, esp, out unhandledException);\n                                            ValueTypeBasePointer = bp;\n                                            if (isValueType)\n                                            {\n                                                var ins = objRef - 1 - 1;\n                                                *a = *ins;\n                                                esp = a + 1;\n                                            }\n                                            else\n                                                esp = PushObject(a, mStack, obj);//new constructedObj\n                                        }\n                                        if (unhandledException)\n                                            returned = true;\n                                    }\n                                    else\n                                    {\n                                        CLRMethod cm = (CLRMethod)m;\n                                        //Means new object();\n                                        if (cm == null)\n                                        {\n                                            esp = PushObject(esp, mStack, new object());\n                                        }\n                                        else\n                                        {\n                                            if (cm.DeclearingType.IsDelegate)\n                                            {\n                                                var objRef = GetObjectAndResolveReference(esp - 1 - 1);\n                                                var mi = (IMethod)mStack[(esp - 1)->Value];\n                                                object ins;\n                                                if (objRef->ObjectType == ObjectTypes.Null)\n                                                    ins = null;\n                                                else\n                                                    ins = mStack[objRef->Value];\n                                                Free(esp - 1);\n                                                Free(esp - 1 - 1);\n                                                esp = esp - 1 - 1;\n                                                object dele;\n                                                if (mi is ILMethod)\n                                                {\n                                                    if (ins != null)\n                                                    {\n                                                        dele = ((ILTypeInstance)ins).GetDelegateAdapter((ILMethod)mi);\n                                                        if (dele == null)\n                                                            dele = domain.DelegateManager.FindDelegateAdapter((ILTypeInstance)ins, (ILMethod)mi);\n                                                    }\n                                                    else\n                                                    {\n                                                        if (((ILMethod)mi).DelegateAdapter == null)\n                                                        {\n                                                            ((ILMethod)mi).DelegateAdapter = domain.DelegateManager.FindDelegateAdapter(null, (ILMethod)mi);\n                                                        }\n                                                        dele = ((ILMethod)mi).DelegateAdapter;\n                                                    }\n                                                }\n                                                else\n                                                {\n                                                    if (ins is ILTypeInstance)\n                                                        ins = ((ILTypeInstance)ins).CLRInstance;\n                                                    dele = Delegate.CreateDelegate(cm.DeclearingType.TypeForCLR, ins, ((CLRMethod)mi).MethodInfo);\n                                                }\n                                                esp = PushObject(esp, mStack, dele);\n                                            }\n                                            else\n                                            {\n                                                var redirect = cm.Redirection;\n                                                if (redirect != null)\n                                                    esp = redirect(this, esp, mStack, cm, true);\n                                                else\n                                                {\n                                                    object result = cm.Invoke(this, esp, mStack, true);\n                                                    int paramCount = cm.ParameterCount;\n                                                    for (int i = 1; i <= paramCount; i++)\n                                                    {\n                                                        Free(esp - i);\n                                                    }\n                                                    esp = Minus(esp, paramCount);\n                                                    esp = PushObject(esp, mStack, result);//new constructedObj\n                                                }\n                                            }\n                                        }\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Constrained:\n                                {\n                                    var objRef = esp - 1;\n                                    var obj = GetObjectAndResolveReference(objRef);\n                                    var type = domain.GetType(ip->TokenInteger);\n                                    if (type != null)\n                                    {\n                                        if (type is ILType)\n                                        {\n                                            var t = (ILType)type;\n                                            if (t.IsEnum)\n                                            {\n                                                ILEnumTypeInstance ins = new ILEnumTypeInstance(t);\n                                                switch (obj->ObjectType)\n                                                {\n                                                    case ObjectTypes.FieldReference:\n                                                        {\n                                                            var owner = mStack[obj->Value] as ILTypeInstance;\n                                                            int idx = obj->ValueLow;\n                                                            Free(objRef);\n                                                            owner.PushToStack(idx, objRef, AppDomain, mStack);\n                                                            ins.AssignFromStack(0, objRef, AppDomain, mStack);\n                                                            ins.Boxed = true;\n                                                        }\n                                                        break;\n                                                    case ObjectTypes.StaticFieldReference:\n                                                        {\n                                                            var st = AppDomain.GetType(obj->Value) as ILType;\n                                                            int idx = obj->ValueLow;\n                                                            Free(objRef);\n                                                            st.StaticInstance.PushToStack(idx, objRef, AppDomain, mStack);\n                                                            ins.AssignFromStack(0, objRef, AppDomain, mStack);\n                                                            ins.Boxed = true;\n                                                        }\n                                                        break;\n                                                    case ObjectTypes.ArrayReference:\n                                                        {\n                                                            var arr = mStack[obj->Value];\n                                                            var idx = obj->ValueLow;\n                                                            Free(objRef);\n                                                            LoadFromArrayReference(arr, idx, objRef, t, mStack);\n                                                            ins.AssignFromStack(0, objRef, AppDomain, mStack);\n                                                            ins.Boxed = true;\n                                                        }\n                                                        break;\n                                                    default:\n                                                        ins.AssignFromStack(0, obj, AppDomain, mStack);\n                                                        ins.Boxed = true;\n                                                        break;\n                                                }\n                                                esp = PushObject(esp - 1, mStack, ins);\n                                            }\n                                            else\n                                            {\n                                                //Nothing to do for normal IL Types\n                                            }\n                                        }\n                                        else\n                                        {\n                                            var tt = type.TypeForCLR;\n                                            if (tt.IsEnum)\n                                            {\n                                                esp = PushObject(esp - 1, mStack, Enum.ToObject(tt, StackObject.ToObject(obj, AppDomain, mStack)));\n                                            }\n                                            else if (tt.IsPrimitive)\n                                            {\n                                                esp = PushObject(esp - 1, mStack, tt.CheckCLRTypes(StackObject.ToObject(obj, AppDomain, mStack)));\n                                            }\n                                            else\n                                            {\n                                                //Nothing to do for other CLR types\n                                            }\n                                        }\n                                    }\n                                    else\n                                        throw new NullReferenceException();\n                                }\n                                break;\n                            case OpCodeEnum.Box:\n                                {\n                                    var obj = esp - 1;\n                                    var type = domain.GetType(ip->TokenInteger);\n                                    if (type != null)\n                                    {\n                                        if (type is ILType)\n                                        {\n                                            if (((ILType)type).IsEnum)\n                                            {\n                                                ILEnumTypeInstance ins = new Intepreter.ILEnumTypeInstance((ILType)type);\n                                                ins.AssignFromStack(0, obj, AppDomain, mStack);\n                                                ins.Boxed = true;\n                                                esp = PushObject(obj, mStack, ins, true);\n                                            }\n                                            else\n                                            {\n                                                switch (obj->ObjectType)\n                                                {\n                                                    case ObjectTypes.Null:\n                                                        break;\n                                                    case ObjectTypes.ValueTypeObjectReference:\n                                                        {\n                                                            ILTypeInstance ins = ((ILType)type).Instantiate(false);\n                                                            ins.AssignFromStack(obj, domain, mStack);\n                                                            FreeStackValueType(obj);\n                                                            esp = PushObject(obj, mStack, ins, true);\n                                                        }\n                                                        break;\n                                                    default:\n                                                        {\n                                                            var val = mStack[obj->Value];\n                                                            Free(obj);\n                                                            ILTypeInstance ins = (ILTypeInstance)val;\n                                                            if (ins != null)\n                                                            {\n                                                                if (ins.IsValueType)\n                                                                {\n                                                                    ins.Boxed = true;\n                                                                }\n                                                                esp = PushObject(obj, mStack, ins, true);\n                                                            }\n                                                            else\n                                                            {\n                                                                esp = PushNull(obj);\n                                                            }\n                                                        }\n                                                        break;\n                                                }\n                                            }\n                                        }\n                                        else\n                                        {\n                                            if (type.TypeForCLR.IsPrimitive)\n                                            {\n                                                var t = type.TypeForCLR;\n                                                if (t == typeof(int))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, 0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(bool))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (obj->Value == 1), true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, false, true);\n                                                            break;\n                                                        case ObjectTypes.Object:\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(byte))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (byte)obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, 0L, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(short))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (short)obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, (short)0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(long))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Long:\n                                                            esp = PushObject(obj, mStack, *(long*)&obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, 0L, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(float))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Float:\n                                                            esp = PushObject(obj, mStack, *(float*)&obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, 0f, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(double))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Double:\n                                                            esp = PushObject(obj, mStack, *(double*)&obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, 0.0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(char))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (char)obj->Value, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(uint))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (uint)obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, (uint)0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(ushort))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (ushort)obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, (ushort)0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(ulong))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Long:\n                                                            esp = PushObject(obj, mStack, *(ulong*)&obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, (ulong)0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(sbyte))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (sbyte)obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, (sbyte)0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else\n                                                    throw new NotImplementedException();\n                                            }\n                                            else if (type.TypeForCLR.IsEnum)\n                                            {\n                                                esp = PushObject(obj, mStack, Enum.ToObject(type.TypeForCLR, StackObject.ToObject(obj, AppDomain, mStack)), true);\n                                            }\n                                            else\n                                            {\n                                                if(obj->ObjectType== ObjectTypes.ValueTypeObjectReference)\n                                                {\n                                                    var dst = *(StackObject**)&obj->Value;\n                                                    var vt = domain.GetType(dst->Value);\n                                                    if (vt != type)\n                                                        throw new InvalidCastException();\n                                                    object ins = ((CLRType)vt).ValueTypeBinder.ToObject(dst, mStack);\n                                                    FreeStackValueType(obj);\n                                                    esp = PushObject(obj, mStack, ins, true);\n                                                }\n                                                //nothing to do for CLR type boxing\n                                            }\n                                        }\n                                    }\n                                    else\n                                        throw new NullReferenceException();\n                                }\n                                break;\n                            case OpCodeEnum.Unbox:\n                            case OpCodeEnum.Unbox_Any:\n                                {\n                                    var objRef = esp - 1;\n                                    if (objRef->ObjectType == ObjectTypes.Object)\n                                    {\n                                        object obj = mStack[objRef->Value];\n                                        Free(objRef);\n                                        if (obj != null)\n                                        {\n                                            var t = domain.GetType(ip->TokenInteger);\n                                            if (t != null)\n                                            {\n                                                var type = t.TypeForCLR;\n                                                if ((t is CLRType) && type.IsPrimitive)\n                                                {\n                                                    if (type == typeof(int))\n                                                    {\n                                                        int val = obj.ToInt32();\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(bool))\n                                                    {\n                                                        bool val = (bool)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val ? 1 : 0;\n                                                    }\n                                                    else if (type == typeof(short))\n                                                    {\n                                                        short val = obj.ToInt16();\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(long))\n                                                    {\n                                                        long val = obj.ToInt64();\n                                                        objRef->ObjectType = ObjectTypes.Long;\n                                                        *(long*)&objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(float))\n                                                    {\n                                                        float val = obj.ToFloat();\n                                                        objRef->ObjectType = ObjectTypes.Float;\n                                                        *(float*)&objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(byte))\n                                                    {\n                                                        byte val = (byte)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(double))\n                                                    {\n                                                        double val = obj.ToDouble();\n                                                        objRef->ObjectType = ObjectTypes.Double;\n                                                        *(double*)&objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(char))\n                                                    {\n                                                        char val = (char)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        *(char*)&objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(uint))\n                                                    {\n                                                        uint val = (uint)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = (int)val;\n                                                    }\n                                                    else if (type == typeof(ushort))\n                                                    {\n                                                        ushort val = (ushort)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(ulong))\n                                                    {\n                                                        ulong val = (ulong)obj;\n                                                        objRef->ObjectType = ObjectTypes.Long;\n                                                        *(ulong*)&objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(sbyte))\n                                                    {\n                                                        sbyte val = (sbyte)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val;\n                                                    }\n                                                    else\n                                                        throw new NotImplementedException();\n                                                }\n                                                else if (t.IsValueType)\n                                                {\n                                                    if (obj is ILTypeInstance)\n                                                    {\n                                                        var res = ((ILTypeInstance)obj);\n                                                        if (res is ILEnumTypeInstance)\n                                                        {\n                                                            res.PushToStack(0, objRef, AppDomain, mStack);\n                                                        }\n                                                        else\n                                                        {\n                                                            if (res.Boxed)\n                                                            {\n                                                                res = res.Clone();\n                                                                res.Boxed = false;\n                                                            }\n                                                            PushObject(objRef, mStack, res);\n                                                        }\n                                                    }\n                                                    else\n                                                        PushObject(objRef, mStack, obj);\n                                                }\n                                                else\n                                                {\n                                                    PushObject(objRef, mStack, obj);\n                                                }\n                                            }\n                                            else\n                                                throw new TypeLoadException();\n                                        }\n                                        else\n                                            throw new NullReferenceException();\n                                    }\n                                    else if (objRef->ObjectType < ObjectTypes.StackObjectReference)\n                                    {\n                                        //Nothing to do with primitive types\n                                    }\n                                    else\n                                        throw new InvalidCastException();\n                                }\n                                break;\n                            case OpCodeEnum.Initobj:\n                                {\n                                    var objRef = GetObjectAndResolveReference(esp - 1);\n                                    var type = domain.GetType(ip->TokenInteger);\n                                    if (type is ILType)\n                                    {\n                                        ILType it = (ILType)type;\n                                        if (it.IsValueType)\n                                        {\n                                            switch (objRef->ObjectType)\n                                            {\n                                                case ObjectTypes.Null:\n                                                    throw new NullReferenceException();\n                                                case ObjectTypes.ValueTypeObjectReference:\n                                                    stack.ClearValueTypeObject(type, *(StackObject**)&objRef->Value);\n                                                    break;\n                                                case ObjectTypes.Object:\n                                                    {\n                                                        var obj = mStack[objRef->Value];\n                                                        if (obj != null)\n                                                        {\n                                                            if (obj is ILTypeInstance)\n                                                            {\n                                                                ILTypeInstance instance = obj as ILTypeInstance;\n                                                                instance.Clear();\n                                                            }\n                                                            else\n                                                                throw new NotSupportedException();\n                                                        }\n                                                        else\n                                                            throw new NullReferenceException();\n                                                    }\n                                                    break;\n                                                default:\n                                                    throw new NotImplementedException();\n                                            }\n\n                                            Free(esp - 1);\n                                            esp--;\n                                        }\n                                        else\n                                        {\n                                            PushNull(esp);\n                                            switch (objRef->ObjectType)\n                                            {\n                                                case ObjectTypes.StaticFieldReference:\n                                                    {\n                                                        var t = AppDomain.GetType(objRef->Value) as ILType;\n                                                        t.StaticInstance.AssignFromStack(objRef->ValueLow, esp, AppDomain, mStack);\n                                                    }\n                                                    break;\n                                                case ObjectTypes.FieldReference:\n                                                    {\n                                                        var instance = mStack[objRef->Value] as ILTypeInstance;\n                                                        instance.AssignFromStack(objRef->ValueLow, esp, AppDomain, mStack);\n                                                        Free(esp - 1);\n                                                        esp--;\n                                                    }\n                                                    break;\n                                                default:\n                                                    {\n                                                        if (objRef->ObjectType >= ObjectTypes.Object)\n                                                            mStack[objRef->Value] = null;\n                                                        else\n                                                            PushNull(objRef);\n                                                    }\n                                                    break;\n                                            }\n                                        }\n                                    }\n                                    else\n                                    {\n                                        if (objRef->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                                        {\n                                            stack.ClearValueTypeObject(type, *(StackObject**)&objRef->Value);\n                                        }\n                                        Free(esp - 1);\n                                        esp--;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Isinst:\n                                {\n                                    var objRef = esp - 1;\n                                    var type = domain.GetType(ip->TokenInteger);\n                                    if (type != null)\n                                    {\n                                        objRef = GetObjectAndResolveReference(objRef);\n                                        if (objRef->ObjectType <= ObjectTypes.Double)\n                                        {\n                                            var tclr = type.TypeForCLR;\n                                            switch (objRef->ObjectType)\n                                            {\n                                                case ObjectTypes.Integer:\n                                                    {\n                                                        if (tclr != typeof(int) && tclr != typeof(bool) && tclr != typeof(short) && tclr != typeof(byte) && tclr != typeof(ushort) && tclr !=typeof(uint))\n                                                        {\n                                                            objRef->ObjectType = ObjectTypes.Null;\n                                                            objRef->Value = -1;\n                                                            objRef->ValueLow = 0;\n                                                        }\n                                                    }\n                                                    break;\n                                                case ObjectTypes.Long:\n                                                    {\n                                                        if (tclr != typeof(long) && tclr != typeof(ulong))\n                                                        {\n                                                            objRef->ObjectType = ObjectTypes.Null;\n                                                            objRef->Value = -1;\n                                                            objRef->ValueLow = 0;\n                                                        }\n                                                    }\n                                                    break;\n                                                case ObjectTypes.Float:\n                                                    {\n                                                        if (tclr != typeof(float))\n                                                        {\n                                                            objRef->ObjectType = ObjectTypes.Null;\n                                                            objRef->Value = -1;\n                                                            objRef->ValueLow = 0;\n                                                        }\n                                                    }\n                                                    break;\n                                                case ObjectTypes.Double:\n                                                    {\n                                                        if (tclr != typeof(double))\n                                                        {\n                                                            objRef->ObjectType = ObjectTypes.Null;\n                                                            objRef->Value = -1;\n                                                            objRef->ValueLow = 0;\n                                                        }\n                                                    }\n                                                    break;\n                                                case ObjectTypes.Null:\n                                                    objRef->ObjectType = ObjectTypes.Null;\n                                                    objRef->Value = -1;\n                                                    objRef->ValueLow = 0;\n                                                    break;\n                                            }\n                                        }\n                                        else\n                                        {\n                                            var obj = RetriveObject(objRef, mStack);\n                                            Free(objRef);\n\n                                            if (obj != null)\n                                            {\n                                                if (obj is ILTypeInstance)\n                                                {\n                                                    if (((ILTypeInstance)obj).CanAssignTo(type))\n                                                    {\n                                                        esp = PushObject(objRef, mStack, obj);\n                                                    }\n                                                    else\n                                                    {\n#if !DEBUG\n                                                        objRef->ObjectType = ObjectTypes.Null;\n                                                        objRef->Value = -1;\n                                                        objRef->ValueLow = 0;\n#endif\n                                                    }\n                                                }\n                                                else\n                                                {\n                                                    if (type.TypeForCLR.IsAssignableFrom(obj.GetType()))\n                                                    {\n                                                        esp = PushObject(objRef, mStack, obj, true);\n                                                    }\n                                                    else\n                                                    {\n#if !DEBUG\n                                                        objRef->ObjectType = ObjectTypes.Null;\n                                                        objRef->Value = -1;\n                                                        objRef->ValueLow = 0;\n#endif\n                                                    }\n                                                }\n                                            }\n                                            else\n                                            {\n#if !DEBUG\n                                                    objRef->ObjectType = ObjectTypes.Null;\n                                                    objRef->Value = -1;\n                                                    objRef->ValueLow = 0;\n#endif\n                                            }\n                                        }\n                                    }\n                                    else\n                                        throw new NullReferenceException();\n                                }\n                                break;\n                            #endregion\n\n                            #region Array\n                            case OpCodeEnum.Newarr:\n                                {\n                                    var cnt = (esp - 1);\n                                    var type = domain.GetType(ip->TokenInteger);\n                                    object arr = null;\n                                    if (type != null)\n                                    {\n                                        if (type.TypeForCLR != typeof(ILTypeInstance))\n                                        {\n                                            if (type is CLRType)\n                                            {\n                                                arr = ((CLRType)type).CreateArrayInstance(cnt->Value);\n                                            }\n                                            else\n                                            {\n                                                arr = Array.CreateInstance(type.TypeForCLR, cnt->Value);\n                                            }\n\n                                            //Register Type\n                                            AppDomain.GetType(arr.GetType());\n                                        }\n                                        else\n                                        {\n                                            arr = new ILTypeInstance[cnt->Value];\n                                        }\n                                    }\n                                    cnt->ObjectType = ObjectTypes.Object;\n                                    cnt->Value = mStack.Count;\n                                    mStack.Add(arr);\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_Ref:\n                            case OpCodeEnum.Stelem_Any:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    Array arr = mStack[arrRef->Value] as Array;\n                                    if (arr is object[])\n                                    {\n                                        switch (val->ObjectType)\n                                        {\n                                            case ObjectTypes.Null:\n                                                arr.SetValue(null, idx->Value);\n                                                break;\n                                            case ObjectTypes.Object:\n                                                ArraySetValue(arr, mStack[val->Value], idx->Value);\n                                                break;\n                                            case ObjectTypes.Integer:\n                                                arr.SetValue(val->Value, idx->Value);\n                                                break;\n                                            case ObjectTypes.Long:\n                                                arr.SetValue(*(long*)&val->Value, idx->Value);\n                                                break;\n                                            case ObjectTypes.Float:\n                                                arr.SetValue(*(float*)&val->Value, idx->Value);\n                                                break;\n                                            case ObjectTypes.Double:\n                                                arr.SetValue(*(double*)&val->Value, idx->Value);\n                                                break;\n                                            default:\n                                                throw new NotImplementedException();\n                                        }\n                                    }\n                                    else\n                                    {\n                                        switch (val->ObjectType)\n                                        {\n                                            case ObjectTypes.Object:\n                                                ArraySetValue(arr, mStack[val->Value], idx->Value);\n                                                break;\n                                            case ObjectTypes.Integer:\n                                                {\n                                                    StoreIntValueToArray(arr, val, idx);\n                                                }\n                                                break;\n                                            case ObjectTypes.Long:\n                                                {\n                                                    if (arr is long[])\n                                                    {\n                                                        ((long[])arr)[idx->Value] = *(long*)&val->Value;\n                                                    }\n                                                    else\n                                                    {\n                                                        ((ulong[])arr)[idx->Value] = *(ulong*)&val->Value;\n                                                    }\n                                                }\n                                                break;\n                                            case ObjectTypes.Float:\n                                                {\n                                                    ((float[])arr)[idx->Value] = *(float*)&val->Value;\n                                                }\n                                                break;\n                                            case ObjectTypes.Double:\n                                                {\n                                                    ((double[])arr)[idx->Value] = *(double*)&val->Value;\n                                                }\n                                                break;\n                                            default:\n                                                throw new NotImplementedException();\n                                        }\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n\n                            case OpCodeEnum.Ldelem_Ref:\n                            case OpCodeEnum.Ldelem_Any:\n                                {\n                                    var idx = esp - 1;\n                                    var arrRef = esp - 1 - 1;\n                                    Array arr = mStack[arrRef->Value] as Array;\n                                    object val = arr.GetValue(idx->Value);\n                                    if (val is CrossBindingAdaptorType)\n                                        val = ((CrossBindingAdaptorType)val).ILInstance;\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    esp = PushObject(esp - 1 - 1, mStack, val);\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_I1:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    byte[] arr = mStack[arrRef->Value] as byte[];\n                                    if (arr != null)\n                                    {\n                                        arr[idx->Value] = (byte)val->Value;\n                                    }\n                                    else\n                                    {\n                                        bool[] arr2 = mStack[arrRef->Value] as bool[];\n                                        if (arr2 != null)\n                                        {\n                                            arr2[idx->Value] = val->Value == 1;\n                                        }\n                                        else\n                                        {\n                                            sbyte[] arr3 = mStack[arrRef->Value] as sbyte[];\n                                            arr3[idx->Value] = (sbyte)val->Value;\n                                        }\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_I1:\n                                {\n                                    var idx = esp - 1;\n                                    var arrRef = esp - 1 - 1;\n                                    bool[] arr = mStack[arrRef->Value] as bool[];\n                                    int val;\n                                    if (arr != null)\n                                        val = arr[idx->Value] ? 1 : 0;\n                                    else\n                                    {\n                                        sbyte[] arr2 = mStack[arrRef->Value] as sbyte[];\n                                        val = arr2[idx->Value];\n                                    }\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = val;\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_U1:\n                                {\n                                    var idx = (esp - 1);\n                                    var arrRef = esp - 1 - 1;\n                                    byte[] arr = mStack[arrRef->Value] as byte[];\n                                    int val;\n                                    if (arr != null)\n                                        val = arr[idx->Value];\n                                    else\n                                    {\n                                        bool[] arr2 = mStack[arrRef->Value] as bool[];\n                                        val = arr2[idx->Value] ? 1 : 0;\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = val;\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_I2:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    short[] arr = mStack[arrRef->Value] as short[];\n                                    if (arr != null)\n                                    {\n                                        arr[idx->Value] = (short)val->Value;\n                                    }\n                                    else\n                                    {\n                                        ushort[] arr2 = mStack[arrRef->Value] as ushort[];\n                                        if (arr2 != null)\n                                        {\n                                            arr2[idx->Value] = (ushort)val->Value;\n                                        }\n                                        else\n                                        {\n                                            char[] arr3 = mStack[arrRef->Value] as char[];\n                                            arr3[idx->Value] = (char)val->Value;\n                                        }\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_I2:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    short[] arr = mStack[arrRef->Value] as short[];\n                                    int val = 0;\n                                    if (arr != null)\n                                    {\n                                        val = arr[idx];\n                                    }\n                                    else\n                                    {\n                                        char[] arr2 = mStack[arrRef->Value] as char[];\n                                        val = arr2[idx];\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = val;\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_U2:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    ushort[] arr = mStack[arrRef->Value] as ushort[];\n                                    int val = 0;\n                                    if (arr != null)\n                                    {\n                                        val = arr[idx];\n                                    }\n                                    else\n                                    {\n                                        char[] arr2 = mStack[arrRef->Value] as char[];\n                                        val = arr2[idx];\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = val;\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_I4:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    int[] arr = mStack[arrRef->Value] as int[];\n                                    if (arr != null)\n                                    {\n                                        arr[idx->Value] = val->Value;\n                                    }\n                                    else\n                                    {\n                                        uint[] arr2 = mStack[arrRef->Value] as uint[];\n                                        arr2[idx->Value] = (uint)val->Value;\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_I4:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    int[] arr = mStack[arrRef->Value] as int[];\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = arr[idx];\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_U4:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    uint[] arr = mStack[arrRef->Value] as uint[];\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = (int)arr[idx];\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_I8:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    long[] arr = mStack[arrRef->Value] as long[];\n                                    if (arr != null)\n                                    {\n                                        arr[idx->Value] = *(long*)&val->Value;\n                                    }\n                                    else\n                                    {\n                                        ulong[] arr2 = mStack[arrRef->Value] as ulong[];\n                                        arr2[idx->Value] = *(ulong*)&val->Value;\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_I8:\n                                {\n                                    var idx = esp - 1;\n                                    var arrRef = esp - 1 - 1;\n                                    long[] arr = mStack[arrRef->Value] as long[];\n                                    long val;\n                                    if (arr != null)\n                                        val = arr[idx->Value];\n                                    else\n                                    {\n                                        ulong[] arr2 = mStack[arrRef->Value] as ulong[];\n                                        val = (long)arr2[idx->Value];\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Long;\n                                    *(long*)&arrRef->Value = val;\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_R4:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    float[] arr = mStack[arrRef->Value] as float[];\n                                    arr[idx->Value] = *(float*)&val->Value;\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_R4:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    float[] arr = mStack[arrRef->Value] as float[];\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Float;\n                                    *(float*)&arrRef->Value = arr[idx];\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_R8:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    double[] arr = mStack[arrRef->Value] as double[];\n                                    arr[idx->Value] = *(double*)&val->Value;\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_R8:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    double[] arr = mStack[arrRef->Value] as double[];\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Double;\n                                    *(double*)&arrRef->Value = arr[idx];\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldlen:\n                                {\n                                    var arrRef = esp - 1;\n                                    Array arr = mStack[arrRef->Value] as Array;\n                                    Free(esp - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = arr.Length;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelema:\n                                {\n                                    var arrRef = esp - 1 - 1;\n                                    var idx = (esp - 1)->Value;\n\n                                    Array arr = mStack[arrRef->Value] as Array;\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.ArrayReference;\n                                    arrRef->Value = mStack.Count;\n                                    mStack.Add(arr);\n                                    arrRef->ValueLow = idx;\n                                    esp--;\n                                }\n                                break;\n                            #endregion\n\n                            #region Conversion\n                            case OpCodeEnum.Conv_U1:\n                            case OpCodeEnum.Conv_Ovf_U1:\n                            case OpCodeEnum.Conv_Ovf_U1_Un:\n                                {\n                                    var obj = esp - 1;\n                                    int val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                        case ObjectTypes.Integer:\n                                            val = (byte)obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (byte)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (byte)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = val;\n                                    obj->ValueLow = 0;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_I1:\n                            case OpCodeEnum.Conv_Ovf_I1:\n                            case OpCodeEnum.Conv_Ovf_I1_Un:\n                                {\n                                    var obj = esp - 1;\n                                    int val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                        case ObjectTypes.Integer:\n                                            val = (sbyte)obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (sbyte)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (sbyte)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = val;\n                                    obj->ValueLow = 0;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_U2:\n                            case OpCodeEnum.Conv_Ovf_U2:\n                            case OpCodeEnum.Conv_Ovf_U2_Un:\n                                {\n                                    var obj = esp - 1;\n                                    int val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                        case ObjectTypes.Integer:\n                                            val = (ushort)obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (ushort)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (ushort)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = val;\n                                    obj->ValueLow = 0;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_I2:\n                            case OpCodeEnum.Conv_Ovf_I2:\n                            case OpCodeEnum.Conv_Ovf_I2_Un:\n                                {\n                                    var obj = esp - 1;\n                                    int val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                        case ObjectTypes.Integer:\n                                            val = (short)(obj->Value);\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (short)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (short)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = val;\n                                    obj->ValueLow = 0;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_U4:\n                            case OpCodeEnum.Conv_Ovf_U4:\n                            case OpCodeEnum.Conv_Ovf_U4_Un:\n                                {\n                                    var obj = esp - 1;\n                                    uint val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            val = (uint)*(long*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            val = (uint)obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (uint)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (uint)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = (int)val;\n                                    obj->ValueLow = 0;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_I4:\n                            case OpCodeEnum.Conv_Ovf_I:\n                            case OpCodeEnum.Conv_Ovf_I_Un:\n                            case OpCodeEnum.Conv_Ovf_I4:\n                            case OpCodeEnum.Conv_Ovf_I4_Un:\n                                {\n                                    var obj = esp - 1;\n                                    int val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            val = (int)*(long*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (int)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (int)*(double*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            val = obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = val;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_U8:\n                            case OpCodeEnum.Conv_I8:\n                            case OpCodeEnum.Conv_Ovf_I8:\n                            case OpCodeEnum.Conv_Ovf_I8_Un:\n                            case OpCodeEnum.Conv_Ovf_U8:\n                            case OpCodeEnum.Conv_Ovf_U8_Un:\n                                {\n                                    var obj = esp - 1;\n                                    long val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            val = obj->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            ip++;\n                                            continue;\n                                        case ObjectTypes.Float:\n                                            val = (long)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (long)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Long;\n                                    *(long*)(&obj->Value) = val;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_R4:\n                                {\n                                    var obj = esp - 1;\n                                    float val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            val = (float)*(long*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            ip++;\n                                            continue;\n                                        case ObjectTypes.Double:\n                                            val = (float)*(double*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            val = obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Float;\n                                    *(float*)&obj->Value = val;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_R8:\n                                {\n                                    var obj = esp - 1;\n                                    double val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            val = (double)*(long*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = *(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            val = obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            ip++;\n                                            continue;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Double;\n                                    *(double*)&obj->Value = val;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_R_Un:\n                                {\n                                    var obj = esp - 1;\n                                    bool isDouble = false;\n                                    float val = 0;\n                                    double val2 = 0;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            val2 = (double)*(ulong*)&obj->Value;\n                                            isDouble = true;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            ip++;\n                                            continue;\n                                        case ObjectTypes.Integer:\n                                            val = (uint)obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            ip++;\n                                            continue;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    if (isDouble)\n                                    {\n                                        obj->ObjectType = ObjectTypes.Double;\n                                        *(double*)&obj->Value = val2;\n                                    }\n                                    else\n                                    {\n                                        obj->ObjectType = ObjectTypes.Float;\n                                        *(float*)&obj->Value = val;\n                                    }\n                                }\n                                break;\n                            #endregion\n\n                            #region Stack operation\n                            case OpCodeEnum.Pop:\n                                {\n                                    Free(esp - 1);\n                                    esp--;\n                                }\n                                break;\n                            case OpCodeEnum.Dup:\n                                {\n                                    var obj = esp - 1;\n                                    *esp = *obj;\n                                    if (esp->ObjectType >= ObjectTypes.Object)\n                                    {\n                                        esp->Value = mStack.Count;\n                                        mStack.Add(mStack[obj->Value]);\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            #endregion\n\n                            case OpCodeEnum.Throw:\n                                {\n                                    var obj = GetObjectAndResolveReference(esp - 1);\n                                    var ex = mStack[obj->Value] as Exception;\n                                    Free(obj);\n                                    esp--;\n                                    throw ex;\n                                }\n                            case OpCodeEnum.Nop:\n                            case OpCodeEnum.Volatile:\n                            case OpCodeEnum.Castclass:\n                                break;\n                            default:\n                                throw new NotSupportedException(\"Not supported opcode \" + code);\n                        }\n                        ip++;\n                    }\n                    catch (Exception ex)\n                    {\n                        if (method.ExceptionHandler != null)\n                        {\n                            int addr = (int)(ip - ptr);\n                            var eh = GetCorrespondingExceptionHandler(method, ex, addr, ExceptionHandlerType.Catch, true);\n\n                            if (eh == null)\n                            {\n                                eh = GetCorrespondingExceptionHandler(method, ex, addr, ExceptionHandlerType.Catch, false);\n                            }\n                            if (eh != null)\n                            {\n                                if (ex is ILRuntimeException)\n                                {\n                                    ILRuntimeException ire = (ILRuntimeException)ex;\n                                    var inner = ire.InnerException;\n                                    inner.Data[\"ThisInfo\"] = ire.ThisInfo;\n                                    inner.Data[\"StackTrace\"] = ire.StackTrace;\n                                    inner.Data[\"LocalInfo\"] = ire.LocalInfo;\n                                    ex = inner;\n                                }\n                                else\n                                {\n                                    var debugger = AppDomain.DebugService;\n                                    if (method.HasThis)\n                                        ex.Data[\"ThisInfo\"] = debugger.GetThisInfo(this);\n                                    else\n                                        ex.Data[\"ThisInfo\"] = \"\";\n                                    ex.Data[\"StackTrace\"] = debugger.GetStackTrance(this);\n                                    ex.Data[\"LocalInfo\"] = debugger.GetLocalVariableInfo(this);\n                                }\n                                //Clear call stack\n                                while (stack.Frames.Peek().BasePointer != frame.BasePointer)\n                                {\n                                    var f = stack.Frames.Peek();\n                                    esp = stack.PopFrame(ref f, esp);\n                                    if (f.Method.ReturnType != AppDomain.VoidType)\n                                    {\n                                        Free(esp - 1);\n                                        esp--;\n                                    }\n                                }\n                                esp = PushObject(esp, mStack, ex);\n                                unhandledException = false;\n                                ip = ptr + eh.HandlerStart;\n                                continue;\n                            }\n                        }\n                        if (unhandledException)\n                        {\n                            throw ex;\n                        }\n\n                        unhandledException = true;\n                        returned = true;\n#if DEBUG\n                        if (!AppDomain.DebugService.Break(this, ex))\n#endif\n                        {\n                            var newEx = new ILRuntimeException(ex.Message, this, method, ex);\n                            throw newEx;\n                        }\n                    }\n                }\n            }\n#if UNITY_EDITOR\n            if (System.Threading.Thread.CurrentThread.ManagedThreadId == AppDomain.UnityMainThreadID)\n#if UNITY_5_5_OR_NEWER\n                UnityEngine.Profiling.Profiler.EndSample();\n#else\n                UnityEngine.Profiler.EndSample();\n#endif\n#endif\n            //ClearStack\n            return stack.PopFrame(ref frame, esp);\n        }\n\n        void DumpStack(StackObject* esp)\n        {\n            AppDomain.DebugService.DumpStack(esp, stack);\n        }\n\n        void CloneStackValueType(StackObject* src, StackObject* dst, IList<object> mStack)\n        {\n            StackObject* descriptor = *(StackObject**)&src->Value;\n            stack.AllocValueType(dst, AppDomain.GetType(descriptor->Value));\n            StackObject* dstDescriptor = *(StackObject**)&dst->Value;\n            int cnt = descriptor->ValueLow;\n            for(int i = 0; i < cnt; i++)\n            {\n                StackObject* val = Minus(descriptor, i + 1);\n                CopyToValueTypeField(dstDescriptor, i, val, mStack);\n            }\n        }\n\n        void CopyStackValueType(StackObject* src, StackObject* dst, IList<object> mStack)\n        {\n            StackObject* descriptor = *(StackObject**)&src->Value;\n            StackObject* dstDescriptor = *(StackObject**)&dst->Value;\n            if (descriptor->Value != dstDescriptor->Value)\n                throw new InvalidCastException();\n            int cnt = descriptor->ValueLow;\n            for(int i = 0; i < cnt; i++)\n            {\n                StackObject* srcVal = Minus(descriptor, i + 1);\n                StackObject* dstVal = Minus(dstDescriptor, i + 1);\n                if (srcVal->ObjectType != dstVal->ObjectType)\n                    throw new NotSupportedException();\n                switch (dstVal->ObjectType)\n                {\n                    case ObjectTypes.Object:\n                    case ObjectTypes.ArrayReference:\n                    case ObjectTypes.FieldReference:\n                        mStack[dstVal->Value] = mStack[srcVal->Value];\n                        break;\n                    case ObjectTypes.ValueTypeObjectReference:\n                        CopyStackValueType(srcVal, dstVal, mStack);\n                        break;\n                    default:\n                        *dstVal = *srcVal;\n                        break;\n                }\n            }\n        }\n\n        void CopyToValueTypeField(StackObject* obj, int idx, StackObject* val, IList<object> mStack)\n        {\n            StackObject* dst = Minus(obj, idx + 1);\n            switch (val->ObjectType)\n            {\n                case ObjectTypes.Null:\n                    {\n                        mStack[dst->Value] = null;\n                    }\n                    break;\n                case ObjectTypes.Object:\n                case ObjectTypes.FieldReference:\n                case ObjectTypes.ArrayReference:\n                    {\n                        if (dst->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                        {\n                            var ins = mStack[val->Value];\n                            dst = *(StackObject**)&dst->Value;\n\n                            if (ins is ILTypeInstance)\n                            {\n                                ((ILTypeInstance)ins).CopyValueTypeToStack(dst, mStack);\n                            }\n                            else\n                            {\n                                var vb = ((CLRType)domain.GetType(dst->Value)).ValueTypeBinder;\n                                vb.CopyValueTypeToStack(ins, dst, mStack);\n                            }\n                        }\n                        else\n                        {\n                            mStack[dst->Value] = CheckAndCloneValueType(mStack[val->Value], domain);                            \n                        }\n                    }\n                    break;\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        if (dst->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                        {\n                            CopyStackValueType(val, dst, mStack);\n                        }\n                        else\n                            throw new NotImplementedException();\n                    }\n                    break;\n                default:\n                    *dst = *val;\n                    break;\n            }\n        }\n\n        void StLocSub(StackObject* esp, StackObject* v, StackObject* bp, int idx, IList<object> mStack)\n        {\n            switch (esp->ObjectType)\n            {\n                case ObjectTypes.Null:\n                    v->ObjectType = ObjectTypes.Object;\n                    v->Value = idx;\n                    mStack[idx] = null;\n                    break;\n                case ObjectTypes.Object:\n                case ObjectTypes.FieldReference:\n                case ObjectTypes.ArrayReference:\n                    if (v->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                    {\n                        var obj = mStack[esp->Value];\n                        if (obj is ILTypeInstance)\n                        {\n                            var dst = *(StackObject**)&v->Value;\n                            ((ILTypeInstance)obj).CopyValueTypeToStack(dst, mStack);\n                        }\n                        else\n                        {\n                            var dst = *(StackObject**)&v->Value;\n                            var ct = domain.GetType(dst->Value) as CLRType;\n                            var binder = ct.ValueTypeBinder;\n                            binder.CopyValueTypeToStack(obj, dst, mStack);\n                        }                            \n                    }\n                    else\n                    {\n                        *v = *esp;\n                        mStack[idx] = CheckAndCloneValueType(mStack[v->Value], domain);\n                        v->Value = idx;\n                    }\n                    Free(esp);\n                    break;\n                case ObjectTypes.ValueTypeObjectReference:\n                    if (v->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                    {\n                        CopyStackValueType(esp, v, mStack);\n                    }\n                    else\n                        throw new NotImplementedException();\n                    FreeStackValueType(esp);\n                    break;\n                default:\n                    *v = *esp;\n                    mStack[idx] = null;\n                    break;\n            }\n        }\n\n        object RetriveObject(StackObject* esp, IList<object> mStack)\n        {\n            StackObject* objRef = GetObjectAndResolveReference(esp);\n            if (objRef->ObjectType == ObjectTypes.Null)\n                return null;\n            object obj = null;\n            switch (objRef->ObjectType)\n            {\n                case ObjectTypes.Object:\n                    obj = mStack[objRef->Value];\n                    break;\n                case ObjectTypes.FieldReference:\n                    {\n                        obj = mStack[objRef->Value];\n                        int idx = objRef->ValueLow;\n                        if (obj is ILTypeInstance)\n                        {\n                            obj = ((ILTypeInstance)obj)[idx];\n                        }\n                        else\n                        {\n                            var t = AppDomain.GetType(obj.GetType());\n                            obj = ((CLRType) t).GetFieldValue(idx, obj);\n                        }\n                    }\n                    break;\n                case ObjectTypes.ArrayReference:\n                    {\n                        Array arr = mStack[objRef->Value] as Array;\n                        int idx = objRef->ValueLow;\n                        obj = arr.GetValue(idx);\n                        obj = obj.GetType().CheckCLRTypes(obj);\n                    }\n                    break;\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = AppDomain.GetType(objRef->Value);\n                        int idx = objRef->ValueLow;\n                        if (t is ILType)\n                        {\n                            obj = ((ILType)t).StaticInstance[idx];\n                        }\n                        else\n                        {\n                            obj = ((CLRType)t).GetFieldValue(idx, null);\n                        }\n                    }\n                    break;\n                default:\n                    throw new NotImplementedException();\n            }\n            return obj;\n        }\n\n        void ArraySetValue(Array arr, object obj, int idx)\n        {\n            if (obj == null)\n                arr.SetValue(null, idx);\n            else\n                arr.SetValue(arr.GetType().GetElementType().CheckCLRTypes(obj), idx);\n        }\n\n        void StoreIntValueToArray(Array arr, StackObject* val, StackObject* idx)\n        {\n            {\n                int[] tmp = arr as int[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = val->Value;\n                    return;\n                }\n            }\n            {\n                short[] tmp = arr as short[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (short)val->Value;\n                    return;\n                }\n            }\n            {\n                byte[] tmp = arr as byte[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (byte)val->Value;\n                    return;\n                }\n            }\n            {\n                bool[] tmp = arr as bool[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = val->Value == 1;\n                    return;\n                }\n            }\n            {\n                uint[] tmp = arr as uint[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (uint)val->Value;\n                    return;\n                }\n            }\n            {\n                ushort[] tmp = arr as ushort[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (ushort)val->Value;\n                    return;\n                }\n            }\n            {\n                char[] tmp = arr as char[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (char)val->Value;\n                    return;\n                }\n            }\n            {\n                sbyte[] tmp = arr as sbyte[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (sbyte)val->Value;\n                    return;\n                }\n            }\n            throw new NotImplementedException();\n        }\n\n        ExceptionHandler GetCorrespondingExceptionHandler(ILMethod method, object obj, int addr, ExceptionHandlerType type, bool explicitMatch)\n        {\n            ExceptionHandler res = null;\n            int distance = int.MaxValue;\n            Exception ex = obj is ILRuntimeException ? ((ILRuntimeException)obj).InnerException : obj as Exception;\n            foreach (var i in method.ExceptionHandler)\n            {\n                if (i.HandlerType == type)\n                {\n                    if (addr >= i.TryStart && addr <= i.TryEnd)\n                    {\n                        if (CheckExceptionType(i.CatchType, ex, explicitMatch))\n                        {\n                            int d = addr - i.TryStart;\n                            if (d < distance)\n                            {\n                                distance = d;\n                                res = i;\n                            }\n                        }\n                    }\n                }\n            }\n            return res;\n        }\n\n        void LoadFromFieldReference(object obj, int idx, StackObject* dst, IList<object> mStack)\n        {\n            if (obj is ILTypeInstance)\n            {\n                ((ILTypeInstance)obj).PushToStack(idx, dst, AppDomain, mStack);\n            }\n            else\n            {\n                CLRType t = AppDomain.GetType(obj.GetType()) as CLRType;\n                ILIntepreter.PushObject(dst, mStack, t.GetFieldValue(idx, obj));\n            }\n        }\n\n        void StoreValueToFieldReference(object obj, int idx, StackObject* val, IList<object> mStack)\n        {\n            if (obj is ILTypeInstance)\n            {\n                ((ILTypeInstance)obj).AssignFromStack(idx, val, AppDomain, mStack);\n            }\n            else\n            {\n                CLRType t = AppDomain.GetType(obj.GetType()) as CLRType;\n                var v = obj.GetType().CheckCLRTypes(CheckAndCloneValueType(StackObject.ToObject(val, AppDomain, mStack), AppDomain));\n                t.SetFieldValue(idx, ref obj, v);\n            }\n        }\n\n        void LoadFromArrayReference(object obj, int idx, StackObject* objRef, IType t, IList<object> mStack)\n        {\n            var nT = t.TypeForCLR;\n            LoadFromArrayReference(obj, idx, objRef, nT, mStack);\n        }\n\n        void LoadFromArrayReference(object obj, int idx, StackObject* objRef, Type nT, IList<object> mStack)\n        {\n            if (nT.IsPrimitive)\n            {\n                if (nT == typeof(int))\n                {\n                    int[] arr = obj as int[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(short))\n                {\n                    short[] arr = obj as short[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(long))\n                {\n                    long[] arr = obj as long[];\n                    objRef->ObjectType = ObjectTypes.Long;\n                    *(long*)&objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(float))\n                {\n                    float[] arr = obj as float[];\n                    objRef->ObjectType = ObjectTypes.Float;\n                    *(float*)&objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(double))\n                {\n                    double[] arr = obj as double[];\n                    objRef->ObjectType = ObjectTypes.Double;\n                    *(double*)&objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(byte))\n                {\n                    byte[] arr = obj as byte[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(char))\n                {\n                    char[] arr = obj as char[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(uint))\n                {\n                    uint[] arr = obj as uint[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    *(uint*)&objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(sbyte))\n                {\n                    sbyte[] arr = obj as sbyte[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                Array arr = obj as Array;\n                objRef->ObjectType = ObjectTypes.Object;\n                objRef->Value = mStack.Count;\n                mStack.Add(arr.GetValue(idx));\n                objRef->ValueLow = 0;\n            }\n        }\n\n        void StoreValueToArrayReference(StackObject* objRef, StackObject* val, IType t, IList<object> mStack)\n        {\n            var nT = t.TypeForCLR;\n            StoreValueToArrayReference(objRef, val, nT, mStack);\n        }\n\n        void StoreValueToArrayReference(StackObject* objRef, StackObject* val, Type nT, IList<object> mStack)\n        {\n            if (nT.IsPrimitive)\n            {\n                if (nT == typeof(int))\n                {\n                    int[] arr = mStack[objRef->Value] as int[];\n                    arr[objRef->ValueLow] = val->Value;\n                }\n                else if (nT == typeof(short))\n                {\n                    short[] arr = mStack[objRef->Value] as short[];\n                    arr[objRef->ValueLow] = (short)val->Value;\n                }\n                else if (nT == typeof(long))\n                {\n                    long[] arr = mStack[objRef->Value] as long[];\n                    arr[objRef->ValueLow] = *(long*)&val->Value;\n                }\n                else if (nT == typeof(float))\n                {\n                    float[] arr = mStack[objRef->Value] as float[];\n                    arr[objRef->ValueLow] = *(float*)&val->Value;\n                }\n                else if (nT == typeof(double))\n                {\n                    double[] arr = mStack[objRef->Value] as double[];\n                    arr[objRef->ValueLow] = *(double*)&val->Value;\n                }\n                else if (nT == typeof(byte))\n                {\n                    byte[] arr = mStack[objRef->Value] as byte[];\n                    arr[objRef->ValueLow] = (byte)val->Value;\n                }\n                else if (nT == typeof(char))\n                {\n                    char[] arr = mStack[objRef->Value] as char[];\n                    arr[objRef->ValueLow] = (char)val->Value;\n                }\n                else if (nT == typeof(uint))\n                {\n                    uint[] arr = mStack[objRef->Value] as uint[];\n                    arr[objRef->ValueLow] = (uint)val->Value;\n                }\n                else if (nT == typeof(sbyte))\n                {\n                    sbyte[] arr = mStack[objRef->Value] as sbyte[];\n                    arr[objRef->ValueLow] = (sbyte)val->Value;\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                Array arr = mStack[objRef->Value] as Array;\n                arr.SetValue(mStack[val->Value], objRef->ValueLow);\n            }\n        }\n\n        bool CheckExceptionType(IType catchType, object exception, bool explicitMatch)\n        {\n            if (catchType is CLRType)\n            {\n                if (explicitMatch)\n                    return exception.GetType() == catchType.TypeForCLR;\n                else\n                    return catchType.TypeForCLR.IsAssignableFrom(exception.GetType());\n            }\n            else\n                throw new NotImplementedException();\n        }\n\n        public static StackObject* GetObjectAndResolveReference(StackObject* esp)\n        {\n            if (esp->ObjectType == ObjectTypes.StackObjectReference)\n            {\n                return *(StackObject**)&esp->Value;\n            }\n            else\n                return esp;\n        }\n\n        StackObject* PushParameters(IMethod method, StackObject* esp, object[] p)\n        {\n            IList<object> mStack = stack.ManagedStack;\n            var plist = method.Parameters;\n            int pCnt = plist != null ? plist.Count : 0;\n            int pCnt2 = p != null ? p.Length : 0;\n            if (pCnt != pCnt2)\n                throw new ArgumentOutOfRangeException(\"Parameter mismatch\");\n            if (pCnt2 > 0)\n            {\n                for (int i = 0; i < p.Length; i++)\n                {\n                    bool isBox = false;\n                    if (plist != null && i < plist.Count)\n                        isBox = plist[i] == AppDomain.ObjectType;\n                    object obj = p[i];\n                    if (obj is CrossBindingAdaptorType)\n                        obj = ((CrossBindingAdaptorType)obj).ILInstance;\n                    esp = ILIntepreter.PushObject(esp, mStack, obj, isBox);\n                }\n            }\n            return esp;\n        }\n\n        public void CopyToStack(StackObject* dst, StackObject* src, IList<object> mStack)\n        {\n            *dst = *src;\n            if (dst->ObjectType >= ObjectTypes.Object)\n            {\n                dst->Value = mStack.Count;\n                var obj = mStack[src->Value];\n                mStack.Add(obj);\n            }\n        }\n\n        internal static object CheckAndCloneValueType(object obj, Enviorment.AppDomain domain)\n        {\n            if (obj != null)\n            {\n                if (obj is ILTypeInstance)\n                {\n                    ILTypeInstance ins = obj as ILTypeInstance;\n                    if (ins.IsValueType)\n                    {\n                        return ins.Clone();\n                    }\n                }\n                else\n                {\n                    var type = obj.GetType();\n                    var typeFlags = type.GetTypeFlags();\n\n                    var isPrimitive = (typeFlags & CLR.Utils.Extensions.TypeFlags.IsPrimitive) != 0;\n                    var isValueType = (typeFlags & CLR.Utils.Extensions.TypeFlags.IsValueType) != 0;\n\n                    if (!isPrimitive && isValueType)\n                    {\n                        var t = domain.GetType(type);\n                        return ((CLRType)t).PerformMemberwiseClone(obj);\n                    }\n                }\n            }\n            return obj;\n        }\n        public static StackObject* PushOne(StackObject* esp)\n        {\n            esp->ObjectType = ObjectTypes.Integer;\n            esp->Value = 1;\n            return esp + 1;\n        }\n\n        public static StackObject* PushZero(StackObject* esp)\n        {\n            esp->ObjectType = ObjectTypes.Integer;\n            esp->Value = 0;\n            return esp + 1;\n        }\n\n        public static StackObject* PushNull(StackObject* esp)\n        {\n            esp->ObjectType = ObjectTypes.Null;\n            esp->Value = -1;\n            esp->ValueLow = 0;\n            return esp + 1;\n        }\n\n        public static void UnboxObject(StackObject* esp, object obj)\n        {\n            if (obj is int)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (int)obj;\n            }\n            else if (obj is bool)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (bool)(obj) ? 1 : 0;\n            }\n            else if (obj is short)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (short)obj;\n            }\n            else if (obj is long)\n            {\n                esp->ObjectType = ObjectTypes.Long;\n                *(long*)(&esp->Value) = (long)obj;\n            }\n            else if (obj is float)\n            {\n                esp->ObjectType = ObjectTypes.Float;\n                *(float*)(&esp->Value) = (float)obj;\n            }\n            else if (obj is byte)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (byte)obj;\n            }\n            else if (obj is uint)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (int)(uint)obj;\n            }\n            else if (obj is ushort)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (int)(ushort)obj;\n            }\n            else if (obj is char)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (int)(char)obj;\n            }\n            else if (obj is double)\n            {\n                esp->ObjectType = ObjectTypes.Double;\n                *(double*)(&esp->Value) = (double)obj;\n            }\n            else if (obj is ulong)\n            {\n                esp->ObjectType = ObjectTypes.Long;\n                *(ulong*)(&esp->Value) = (ulong)obj;\n            }\n            else if (obj is sbyte)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (sbyte)obj;\n            }\n            else\n                throw new NotImplementedException();\n        }\n\n        public static StackObject* PushObject(StackObject* esp, IList<object> mStack, object obj, bool isBox = false)\n        {\n            if (obj != null)\n            {\n                if (!isBox)\n                {\n                    var typeFlags = obj.GetType().GetTypeFlags();\n\n                    if ((typeFlags & CLR.Utils.Extensions.TypeFlags.IsPrimitive) != 0)\n                    {\n                        UnboxObject(esp, obj);\n                    }\n                    else if ((typeFlags & CLR.Utils.Extensions.TypeFlags.IsEnum) != 0)\n                    {\n                        esp->ObjectType = ObjectTypes.Integer;\n                        esp->Value = Convert.ToInt32(obj);\n                    }\n                    else\n                    {\n                        esp->ObjectType = ObjectTypes.Object;\n                        esp->Value = mStack.Count;\n                        mStack.Add(obj);\n                    }\n                }\n                else\n                {\n                    esp->ObjectType = ObjectTypes.Object;\n                    esp->Value = mStack.Count;\n                    mStack.Add(obj);\n                }\n            }\n            else\n            {\n                return PushNull(esp);\n            }\n            return esp + 1;\n        }\n\n        //Don't ask me why add this funky method for this, otherwise Unity won't calculate the right value\n        public static StackObject* Add(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a + sizeof(StackObject) * b);\n        }\n\n        public static StackObject* Minus(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a - sizeof(StackObject) * b);\n        }\n\n        public void Free(StackObject* esp)\n        {\n            if (esp->ObjectType >= ObjectTypes.Object)\n            {\n                if (esp->Value == stack.ManagedStack.Count - 1)\n                    stack.ManagedStack.RemoveAt(esp->Value);\n            }\n#if DEBUG\n            esp->ObjectType = ObjectTypes.Null;\n            esp->Value = -1;\n            esp->ValueLow = 0;\n#endif\n        }\n        public void FreeStackValueType(StackObject* esp)\n        {\n            if (esp->ObjectType == ObjectTypes.ValueTypeObjectReference)\n            {\n                var addr = *(StackObject**)&esp->Value;\n                if (addr <= ValueTypeBasePointer)//Only Stack allocation after base pointer should be freed, local variable are freed automatically\n                    stack.FreeValueTypeObject(esp);\n            }\n        }\n\n        public void AllocValueType(StackObject* ptr, IType type)\n        {\n            stack.AllocValueType(ptr, type);\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Intepreter/ILRuntimeException.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.Runtime.Stack;\n\nnamespace ILRuntime.Runtime.Intepreter\n{\n    public class ILRuntimeException : Exception\n    {\n        string stackTrace;\n        string thisInfo, localInfo;\n        internal ILRuntimeException(string message, ILIntepreter intepreter, CLR.Method.ILMethod method, Exception innerException = null)\n            : base(message, innerException)\n        \n        {\n            var ds = intepreter.AppDomain.DebugService;\n            if (innerException is ILRuntimeException)\n            {\n                ILRuntimeException e = innerException as ILRuntimeException;\n                stackTrace = e.stackTrace;\n                thisInfo = e.thisInfo;\n                localInfo = e.localInfo;\n            }\n            else\n            {\n                stackTrace = ds.GetStackTrance(intepreter);\n                if (method.HasThis)\n                    thisInfo = ds.GetThisInfo(intepreter);\n                else\n                    thisInfo = \"\";\n                localInfo = ds.GetLocalVariableInfo(intepreter);\n            }\n        }\n\n        public override string StackTrace\n        {\n            get\n            {\n                return stackTrace;\n            }\n        }\n\n        public string ThisInfo\n        {\n            get { return thisInfo; }\n        }\n\n        public string LocalInfo\n        {\n            get\n            {\n                return localInfo;\n            }\n        }\n\n        public override string ToString()\n        {\n            StringBuilder message = new StringBuilder();\n            message.AppendLine(Message);\n            if (!string.IsNullOrEmpty(ThisInfo))\n            {\n                message.AppendLine(\"this:\");\n                message.AppendLine(ThisInfo);\n            }\n            message.AppendLine(\"Local Variables:\");\n            message.AppendLine(LocalInfo);\n            message.AppendLine(StackTrace);\n            if (InnerException != null)\n                message.AppendLine(InnerException.ToString());\n            return message.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Intepreter/ILTypeInstance.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.Utils;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Stack;\nnamespace ILRuntime.Runtime.Intepreter\n{\n    public class ILTypeStaticInstance : ILTypeInstance\n    {\n        public unsafe ILTypeStaticInstance(ILType type)\n        {\n            this.type = type;\n            fields = new StackObject[type.StaticFieldTypes.Length];\n            managedObjs = new List<object>(fields.Length);\n            for (int i = 0; i < fields.Length; i++)\n            {\n                var ft = type.StaticFieldTypes[i];\n                var t = ft.TypeForCLR;\n                managedObjs.Add(null);\n                StackObject.Initialized(ref fields[i], i, t, ft, managedObjs);\n            }\n            int idx = 0;\n            foreach (var i in type.TypeDefinition.Fields)\n            {\n                if (i.IsStatic)\n                {\n                    if (i.InitialValue != null && i.InitialValue.Length > 0)\n                    {\n                        fields[idx].ObjectType = ObjectTypes.Object;\n                        managedObjs[idx] = i.InitialValue;\n                    }\n                    idx++;\n                }\n            }\n        }\n    }\n\n    unsafe class ILEnumTypeInstance : ILTypeInstance\n    {\n        public ILEnumTypeInstance(ILType type)\n        {\n            if (!type.IsEnum)\n                throw new NotSupportedException();\n            this.type = type;\n            fields = new StackObject[1];\n        }\n\n        public override string ToString()\n        {\n            var fields = type.TypeDefinition.Fields;\n            long longVal = 0;\n            int intVal = 0;\n            bool isLong = this.fields[0].ObjectType == ObjectTypes.Long;\n            if (isLong)\n            {\n                fixed (StackObject* f = this.fields)\n                    longVal = *(long*)&f->Value;\n            }\n            else\n                intVal = this.fields[0].Value;\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var f = fields[i];\n                if (f.IsStatic)\n                {\n                    if (isLong)\n                    {\n                        long val = f.Constant is long ? (long)f.Constant : (long)(ulong)f.Constant;\n                        if (val == longVal)\n                            return f.Name;\n                    }\n                    else\n                    {\n                        if (f.Constant is int)\n                        {\n                            if ((int)f.Constant == intVal)\n                                return f.Name;\n                        }\n                        else if (f.Constant is short)\n                        {\n                            if ((short)f.Constant == intVal)\n                                return f.Name;\n                        }\n                        else if (f.Constant is byte)\n                        {\n                            if ((byte)f.Constant == intVal)\n                                return f.Name;\n                        }\n                        else\n                            throw new NotImplementedException();\n                    }\n                }\n            }\n            return isLong ? longVal.ToString() : intVal.ToString();\n        }\n    }\n\n    public class ILTypeInstance\n    {\n        protected ILType type;\n        protected StackObject[] fields;\n        protected IList<object> managedObjs;\n        object clrInstance;\n        Dictionary<ILMethod, IDelegateAdapter> delegates;\n\n        public ILType Type\n        {\n            get\n            {\n                return type;\n            }\n        }\n\n        public StackObject[] Fields\n        {\n            get { return fields; }\n        }\n\n        public virtual bool IsValueType\n        {\n            get\n            {\n                return type.IsValueType && !Boxed;\n            }\n        }\n\n        /// <summary>\n        /// 是否已装箱\n        /// </summary>\n        public bool Boxed { get; set; }\n\n        public IList<object> ManagedObjects { get { return managedObjs; } }\n\n        public object CLRInstance { get { return clrInstance; } set { clrInstance = value; } }\n\n        protected ILTypeInstance()\n        {\n\n        }\n        public ILTypeInstance(ILType type, bool initializeCLRInstance = true)\n        {\n            this.type = type;\n            fields = new StackObject[type.TotalFieldCount];\n            managedObjs = new List<object>(fields.Length);\n            for (int i = 0; i < fields.Length; i++)\n            {\n                managedObjs.Add(null);\n            }\n            InitializeFields(type);\n            if (initializeCLRInstance)\n            {\n                if (type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n                {\n                    clrInstance = ((Enviorment.CrossBindingAdaptor)type.FirstCLRBaseType).CreateCLRInstance(type.AppDomain, this);\n                }\n                else\n                {\n                    clrInstance = this;\n                }\n                if(type.FirstCLRInterface is Enviorment.CrossBindingAdaptor)\n                {\n                    if (clrInstance != this)//Only one CLRInstance is allowed atm, so implementing multiple interfaces is not supported\n                    {\n                        throw new NotSupportedException(\"Inheriting and implementing interface at the same time is not supported yet\");\n                    }\n                    clrInstance = ((Enviorment.CrossBindingAdaptor)type.FirstCLRInterface).CreateCLRInstance(type.AppDomain, this);\n                }\n            }\n            else\n                clrInstance = this;\n        }\n\n        public unsafe object this[int index]\n        {\n            get\n            {\n                if (index < fields.Length && index >= 0)\n                {\n                    fixed (StackObject* ptr = fields)\n                    {\n                        StackObject* esp = &ptr[index];\n                        return StackObject.ToObject(esp, null, managedObjs);\n                    }\n                }\n                else\n                {\n                    if (Type.FirstCLRBaseType != null && Type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n                    {\n                        CLRType clrType = type.AppDomain.GetType(((Enviorment.CrossBindingAdaptor)Type.FirstCLRBaseType).BaseCLRType) as CLRType;\n                        return clrType.GetFieldValue(index, clrInstance);\n                    }\n                    else\n                        throw new TypeLoadException();\n                }\n            }\n            set\n            {\n                value = ILIntepreter.CheckAndCloneValueType(value, type.AppDomain);\n                if (index < fields.Length && index >= 0)\n                {\n                    fixed (StackObject* ptr = fields)\n                    {\n                        StackObject* esp = &ptr[index];\n                        if (value != null)\n                        {\n                            if (value.GetType().IsPrimitive)\n                            {\n                                ILIntepreter.UnboxObject(esp, value);\n                            }\n                            else\n                            {\n                                esp->ObjectType = ObjectTypes.Object;\n                                esp->Value = index;\n                                managedObjs[index] = value;\n                            }\n                        }\n                        else\n                            *esp = StackObject.Null;\n                    }\n                }\n                else\n                {\n                    if (Type.FirstCLRBaseType != null && Type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n                    {\n                        CLRType clrType = type.AppDomain.GetType(((Enviorment.CrossBindingAdaptor)Type.FirstCLRBaseType).BaseCLRType) as CLRType;\n                        clrType.SetFieldValue(index, ref clrInstance, value);\n                    }\n                    else\n                        throw new TypeLoadException();\n                }\n            }\n        }\n\n        void InitializeFields(ILType type)\n        {\n            for (int i = 0; i < type.FieldTypes.Length; i++)\n            {\n                var ft = type.FieldTypes[i];\n                StackObject.Initialized(ref fields[type.FieldStartIndex + i], type.FieldStartIndex + i, ft.TypeForCLR, ft, managedObjs);\n            }\n            if (type.BaseType != null && type.BaseType is ILType)\n                InitializeFields((ILType)type.BaseType);\n        }\n\n        internal unsafe void PushFieldAddress(int fieldIdx, StackObject* esp, IList<object> managedStack)\n        {\n            esp->ObjectType = ObjectTypes.FieldReference;\n            esp->Value = managedStack.Count;\n            managedStack.Add(this);\n            esp->ValueLow = fieldIdx;\n        }\n\n        internal unsafe void PushToStack(int fieldIdx, StackObject* esp, Enviorment.AppDomain appdomain, IList<object> managedStack)\n        {\n            if (fieldIdx < fields.Length && fieldIdx >= 0)\n                PushToStackSub(ref fields[fieldIdx], fieldIdx, esp, managedStack);\n            else\n            {\n                if (Type.FirstCLRBaseType != null && Type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n                {\n                    CLRType clrType = appdomain.GetType(((Enviorment.CrossBindingAdaptor)Type.FirstCLRBaseType).BaseCLRType) as CLRType;\n                    ILIntepreter.PushObject(esp, managedStack, clrType.GetFieldValue(fieldIdx, clrInstance));\n                }\n                else\n                    throw new TypeLoadException();\n            }\n        }\n\n        unsafe void PushToStackSub(ref StackObject field, int fieldIdx, StackObject* esp, IList<object> managedStack)\n        {\n            *esp = field;\n            if (field.ObjectType >= ObjectTypes.Object)\n            {\n                esp->Value = managedStack.Count;\n                managedStack.Add(managedObjs[fieldIdx]);\n            }\n        }\n\n        internal unsafe void CopyValueTypeToStack(StackObject* ptr, IList<object> mStack)\n        {\n            ptr->ObjectType = ObjectTypes.ValueTypeDescriptor;\n            ptr->Value = type.GetHashCode();\n            ptr->ValueLow = type.TotalFieldCount;\n            for(int i = 0; i < fields.Length; i++)\n            {\n                var val = ILIntepreter.Minus(ptr, i + 1);\n                switch (val->ObjectType)\n                {\n                    case ObjectTypes.Object:\n                    case ObjectTypes.FieldReference:\n                    case ObjectTypes.ArrayReference:\n                        mStack[val->Value] = managedObjs[i];\n                        val->ValueLow = fields[i].ValueLow;\n                        break;\n                    case ObjectTypes.ValueTypeObjectReference:\n                        {\n                            var obj = managedObjs[i];\n                            var dst = *(StackObject**)&val->Value;\n                            var vt = type.AppDomain.GetType(dst->Value);\n                            if (vt is ILType)\n                            {\n                                ((ILTypeInstance)obj).CopyValueTypeToStack(dst, mStack);\n                            }\n                            else\n                            {\n                                ((CLRType)vt).ValueTypeBinder.CopyValueTypeToStack(obj, dst, mStack);\n                            }\n                        }\n                        break;\n                    default:\n                        *val = fields[i];\n                        break;\n                }                \n            }\n        }\n\n        internal void Clear()\n        {   \n            InitializeFields(type);\n        }\n\n        internal unsafe void AssignFromStack(int fieldIdx, StackObject* esp, Enviorment.AppDomain appdomain, IList<object> managedStack)\n        {\n            if (fieldIdx < fields.Length && fieldIdx >= 0)\n                AssignFromStackSub(ref fields[fieldIdx], fieldIdx, esp, managedStack);\n            else\n            {\n                if (Type.FirstCLRBaseType != null && Type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n                {\n                    CLRType clrType = appdomain.GetType(((Enviorment.CrossBindingAdaptor)Type.FirstCLRBaseType).BaseCLRType) as CLRType;\n                    var field = clrType.GetField(fieldIdx);\n                    clrType.SetFieldValue(fieldIdx, ref clrInstance, field.FieldType.CheckCLRTypes(ILIntepreter.CheckAndCloneValueType(StackObject.ToObject(esp, appdomain, managedStack), appdomain)));\n                }\n                else\n                    throw new TypeLoadException();\n            }\n        }\n\n        internal unsafe void AssignFromStack(StackObject* esp, Enviorment.AppDomain appdomain, IList<object> managedStack)\n        {\n            StackObject* val = *(StackObject**)&esp->Value;\n            int cnt = val->ValueLow;\n            for (int i = 0; i < cnt; i++)\n            {\n                var addr = ILIntepreter.Minus(val, i + 1);\n                AssignFromStack(i, addr, type.AppDomain, managedStack);\n            }\n        }\n\n        unsafe void AssignFromStackSub(ref StackObject field, int fieldIdx, StackObject* esp, IList<object> managedStack)\n        {\n            esp = ILIntepreter.GetObjectAndResolveReference(esp);\n            field = *esp;\n            switch (field.ObjectType)\n            {\n                case ObjectTypes.Object:\n                case ObjectTypes.ArrayReference:\n                case ObjectTypes.FieldReference:\n                    field.Value = fieldIdx;\n                    managedObjs[fieldIdx] = ILIntepreter.CheckAndCloneValueType(managedStack[esp->Value], Type.AppDomain);\n                    break;\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        var domain = type.AppDomain;\n                        field.ObjectType = ObjectTypes.Object;\n                        field.Value = fieldIdx;\n                        var dst = *(StackObject**)&esp->Value;\n                        var vt = domain.GetType(dst->Value);\n                        if(vt is ILType)\n                        {\n                            var ins = managedObjs[fieldIdx];\n                            if (ins == null)\n                                throw new NullReferenceException();\n                            ILTypeInstance child = (ILTypeInstance)ins;\n                            child.AssignFromStack(esp, domain, managedStack);\n                        }\n                        else\n                        {\n                            managedObjs[fieldIdx] = ((CLRType)vt).ValueTypeBinder.ToObject(dst, managedStack);\n                        }\n                        \n                    }\n                    break;\n                default:\n                    if (managedObjs != null)\n                        managedObjs[fieldIdx] = null;\n                    break;\n            }\n        }\n\n        public override string ToString()\n        {\n            IMethod m = type.AppDomain.ObjectType.GetMethod(\"ToString\", 0);\n            m = type.GetVirtualMethod(m);\n            if (m != null)\n            {\n                if (m is ILMethod)\n                {\n                    var res = type.AppDomain.Invoke(m, this, null);\n                    return res.ToString();\n                }\n                else\n                    return clrInstance.ToString();\n            }\n            else\n                return type.FullName;\n        }\n\n        public bool CanAssignTo(IType type)\n        {\n            return this.type.CanAssignTo(type);\n        }\n\n        public ILTypeInstance Clone()\n        {\n            ILTypeInstance ins = new ILTypeInstance(type);\n            for (int i = 0; i < fields.Length; i++)\n            {\n                ins.fields[i] = fields[i];\n                ins.managedObjs[i] = managedObjs[i];\n            }\n            if (type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n            {\n                ins.clrInstance = ((Enviorment.CrossBindingAdaptor)type.FirstCLRBaseType).CreateCLRInstance(type.AppDomain, ins);\n            }\n            else\n            {\n                ins.clrInstance = ins;\n            }\n            return ins;\n        }\n\n        internal IDelegateAdapter GetDelegateAdapter(ILMethod method)\n        {\n            if (delegates == null)\n                delegates = new Dictionary<ILMethod, IDelegateAdapter>();\n\n            IDelegateAdapter res;\n            if (delegates.TryGetValue(method, out res))\n                return res;\n            return null;\n        }\n\n        internal void SetDelegateAdapter(ILMethod method, IDelegateAdapter adapter)\n        {\n            if (!delegates.ContainsKey(method))\n                delegates[method] = adapter;\n            else\n                throw new NotSupportedException();\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Intepreter/OpCodes/OpCode.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.Method;\n\nnamespace ILRuntime.Runtime.Intepreter.OpCodes\n{\n  \n    /// <summary>\n    /// IL指令\n    /// </summary>\n    struct OpCode\n    {\n        /// <summary>\n        /// 当前指令\n        /// </summary>\n        public OpCodeEnum Code;\n\n        /// <summary>\n        ///  Int32 操作数\n        /// </summary>\n        public int TokenInteger;\n\n        /// <summary>\n        /// Int64 操作数\n        /// </summary>\n        public long TokenLong;\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Intepreter/OpCodes/OpCodeEnum.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Intepreter.OpCodes\n{\n    enum OpCodeEnum\n    {\n        /// <summary>\n        /// 如果修补操作码，则填充空间。尽管可能消耗处理周期，但未执行任何有意义的操作。\n        /// </summary>\n        Nop,\n        /// <summary>\n        /// 向公共语言结构 (CLI) 发出信号以通知调试器已撞上了一个断点。\n        /// </summary>\n        Break,\n        /// <summary>\n        /// 将索引为 0 的参数加载到计算堆栈上。\n        /// </summary>\n        Ldarg_0,\n        /// <summary>\n        /// 将索引为 1 的参数加载到计算堆栈上。\n        /// </summary>\n        Ldarg_1,\n        /// <summary>\n        /// 将索引为 2 的参数加载到计算堆栈上。\n        /// </summary>\n        Ldarg_2,\n        /// <summary>\n        /// 将索引为 3 的参数加载到计算堆栈上。\n        /// </summary>\n        Ldarg_3,\n        /// <summary>\n        /// 将索引 0 处的局部变量加载到计算堆栈上。\n        /// </summary>\n        Ldloc_0,\n        /// <summary>\n        /// 将索引 1 处的局部变量加载到计算堆栈上。\n        /// </summary>\n        Ldloc_1,\n        /// <summary>\n        /// 将索引 2 处的局部变量加载到计算堆栈上。\n        /// </summary>\n        Ldloc_2,\n        /// <summary>\n        /// 将索引 3 处的局部变量加载到计算堆栈上。\n        /// </summary>\n        Ldloc_3,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储到索引 0 处的局部变量列表中。\n        /// </summary>\n        Stloc_0,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储到索引 1 处的局部变量列表中。\n        /// </summary>\n        Stloc_1,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储到索引 2 处的局部变量列表中。\n        /// </summary>\n        Stloc_2,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储到索引 3 处的局部变量列表中。\n        /// </summary>\n        Stloc_3,\n        /// <summary>\n        /// 将参数（由指定的短格式索引引用）加载到计算堆栈上。\n        /// </summary>\n        Ldarg_S,\n        /// <summary>\n        /// 以短格式将参数地址加载到计算堆栈上。\n        /// </summary>\n        Ldarga_S,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值存储在参数槽中的指定索引处（短格式）。\n        /// </summary>\n        Starg_S,\n        /// <summary>\n        /// 将特定索引处的局部变量加载到计算堆栈上（短格式）。\n        /// </summary>\n        Ldloc_S,\n        /// <summary>\n        /// 将位于特定索引处的局部变量的地址加载到计算堆栈上（短格式）。\n        /// </summary>\n        Ldloca_S,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储在局部变量列表中的 index 处（短格式）。\n        /// </summary>\n        Stloc_S,\n        /// <summary>\n        /// 将空引用（O 类型）推送到计算堆栈上。\n        /// </summary>\n        Ldnull,\n        /// <summary>\n        /// 将整数值 -1 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_M1,\n        /// <summary>\n        /// 将整数值 0 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_0,\n        /// <summary>\n        /// 将整数值 1 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_1,\n        /// <summary>\n        /// 将整数值 2 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_2,\n        /// <summary>\n        /// 将整数值 3 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_3,\n        /// <summary>\n        /// 将整数值 4 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_4,\n        /// <summary>\n        /// 将整数值 5 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_5,\n        /// <summary>\n        /// 将整数值 6 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_6,\n        /// <summary>\n        /// 将整数值 7 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_7,\n        /// <summary>\n        /// 将整数值 8 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_8,\n        /// <summary>\n        /// 将提供的 int8 值作为 int32 推送到计算堆栈上（短格式）。\n        /// </summary>\n        Ldc_I4_S,\n        /// <summary>\n        /// 将所提供的 int32 类型的值作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4,\n        /// <summary>\n        /// 将所提供的 int64 类型的值作为 int64 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I8,\n        /// <summary>\n        /// 将所提供的 float32 类型的值作为 F (float) 类型推送到计算堆栈上。\n        /// </summary>\n        Ldc_R4,\n        /// <summary>\n        /// 将所提供的 float64 类型的值作为 F (float) 类型推送到计算堆栈上。\n        /// </summary>\n        Ldc_R8,\n        /// <summary>\n        /// 复制计算堆栈上当前最顶端的值，然后将副本推送到计算堆栈上。\n        /// </summary>\n        Dup,\n        /// <summary>\n        /// 移除当前位于计算堆栈顶部的值。\n        /// </summary>\n        Pop,\n        /// <summary>\n        /// 退出当前方法并跳至指定方法。\n        /// </summary>\n        Jmp,\n        /// <summary>\n        /// 调用由传递的方法说明符指示的方法。\n        /// </summary>\n        Call,\n        /// <summary>\n        /// 通过调用约定描述的参数调用在计算堆栈上指示的方法（作为指向入口点的指针）。\n        /// </summary>\n        Calli,\n        /// <summary>\n        /// 从当前方法返回，并将返回值（如果存在）从调用方的计算堆栈推送到被调用方的计算堆栈上。\n        /// </summary>\n        Ret,\n        /// <summary>\n        /// 无条件地将控制转移到目标指令（短格式）。\n        /// </summary>\n        Br_S,\n        /// <summary>\n        /// 如果 value 为 false、空引用或零，则将控制转移到目标指令。\n        /// </summary>\n        Brfalse_S,\n        /// <summary>\n        /// 如果 value 为 true、非空或非零，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Brtrue_S,\n        /// <summary>\n        /// 如果两个值相等，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Beq_S,\n        /// <summary>\n        /// 如果第一个值大于或等于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Bge_S,\n        /// <summary>\n        /// 如果第一个值大于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Bgt_S,\n        /// <summary>\n        /// 如果第一个值小于或等于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Ble_S,\n        /// <summary>\n        /// 如果第一个值小于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Blt_S,\n        /// <summary>\n        /// 当两个无符号整数值或不可排序的浮点型值不相等时，将控制转移到目标指令（短格式）。\n        /// </summary>\n        Bne_Un_S,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值大于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Bge_Un_S,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值大于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Bgt_Un_S,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点值时，如果第一个值小于或等于第二个值，则将控制权转移到目标指令（短格式）。\n        /// </summary>\n        Ble_Un_S,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值小于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Blt_Un_S,\n        /// <summary>\n        /// 无条件地将控制转移到目标指令。\n        /// </summary>\n        Br,\n        /// <summary>\n        /// 如果 value 为 false、空引用（Visual Basic 中的 Nothing）或零，则将控制转移到目标指令。\n        /// </summary>\n        Brfalse,\n        /// <summary>\n        /// 如果 value 为 true、非空或非零，则将控制转移到目标指令。\n        /// </summary>\n        Brtrue,\n        /// <summary>\n        /// 如果两个值相等，则将控制转移到目标指令。\n        /// </summary>\n        Beq,\n        /// <summary>\n        /// 如果第一个值大于或等于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Bge,\n        /// <summary>\n        /// 如果第一个值大于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Bgt,\n        /// <summary>\n        /// 如果第一个值小于或等于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Ble,\n        /// <summary>\n        /// 如果第一个值小于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Blt,\n        /// <summary>\n        /// 当两个无符号整数值或不可排序的浮点型值不相等时，将控制转移到目标指令。\n        /// </summary>\n        Bne_Un,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值大于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Bge_Un,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值大于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Bgt_Un,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值小于或等于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Ble_Un,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值小于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Blt_Un,\n        /// <summary>\n        /// 实现跳转表。\n        /// </summary>\n        Switch,\n        /// <summary>\n        /// 将 int8 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_I1,\n        /// <summary>\n        /// 将 unsigned int8 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_U1,\n        /// <summary>\n        /// 将 int16 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_I2,\n        /// <summary>\n        /// 将 unsigned int16 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_U2,\n        /// <summary>\n        /// 将 int32 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_I4,\n        /// <summary>\n        /// 将 unsigned int32 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_U4,\n        /// <summary>\n        /// 将 int64 类型的值作为 int64 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_I8,\n        /// <summary>\n        /// 将 native int 类型的值作为 native int 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_I,\n        /// <summary>\n        /// 将 float32 类型的值作为 F (float) 类型间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_R4,\n        /// <summary>\n        /// 将 float64 类型的值作为 F (float) 类型间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_R8,\n        /// <summary>\n        /// 将对象引用作为 O（对象引用）类型间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_Ref,\n        /// <summary>\n        /// 存储所提供地址处的对象引用值。\n        /// </summary>\n        Stind_Ref,\n        /// <summary>\n        /// 在所提供的地址存储 int8 类型的值。\n        /// </summary>\n        Stind_I1,\n        /// <summary>\n        /// 在所提供的地址存储 int16 类型的值。\n        /// </summary>\n        Stind_I2,\n        /// <summary>\n        /// 在所提供的地址存储 int32 类型的值。\n        /// </summary>\n        Stind_I4,\n        /// <summary>\n        /// 在所提供的地址存储 int64 类型的值。\n        /// </summary>\n        Stind_I8,\n        /// <summary>\n        /// 在所提供的地址存储 float32 类型的值。\n        /// </summary>\n        Stind_R4,\n        /// <summary>\n        /// 在所提供的地址存储 float64 类型的值。\n        /// </summary>\n        Stind_R8,\n        /// <summary>\n        /// 将两个值相加并将结果推送到计算堆栈上。\n        /// </summary>\n        Add,\n        /// <summary>\n        /// 从其他值中减去一个值并将结果推送到计算堆栈上。\n        /// </summary>\n        Sub,\n        /// <summary>\n        /// 将两个值相乘并将结果推送到计算堆栈上。\n        /// </summary>\n        Mul,\n        /// <summary>\n        /// 将两个值相除并将结果作为浮点（F 类型）或商（int32 类型）推送到计算堆栈上。\n        /// </summary>\n        Div,\n        /// <summary>\n        /// 两个无符号整数值相除并将结果 ( int32 ) 推送到计算堆栈上。\n        /// </summary>\n        Div_Un,\n        /// <summary>\n        /// 将两个值相除并将余数推送到计算堆栈上。\n        /// </summary>\n        Rem,\n        /// <summary>\n        /// 将两个无符号值相除并将余数推送到计算堆栈上。\n        /// </summary>\n        Rem_Un,\n        /// <summary>\n        /// 计算两个值的按位“与”并将结果推送到计算堆栈上。\n        /// </summary>\n        And,\n        /// <summary>\n        /// 计算位于堆栈顶部的两个整数值的按位求补并将结果推送到计算堆栈上。\n        /// </summary>\n        Or,\n        /// <summary>\n        /// 计算位于计算堆栈顶部的两个值的按位异或，并且将结果推送到计算堆栈上。\n        /// </summary>\n        Xor,\n        /// <summary>\n        /// 将整数值左移（用零填充）指定的位数，并将结果推送到计算堆栈上。\n        /// </summary>\n        Shl,\n        /// <summary>\n        /// 将整数值右移（保留符号）指定的位数，并将结果推送到计算堆栈上。\n        /// </summary>\n        Shr,\n        /// <summary>\n        /// 将无符号整数值右移（用零填充）指定的位数，并将结果推送到计算堆栈上。\n        /// </summary>\n        Shr_Un,\n        /// <summary>\n        /// 对一个值执行求反并将结果推送到计算堆栈上。\n        /// </summary>\n        Neg,\n        /// <summary>\n        /// 计算堆栈顶部整数值的按位求补并将结果作为相同的类型推送到计算堆栈上。\n        /// </summary>\n        Not,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 int8，然后将其扩展（填充）为 int32。\n        /// </summary>\n        Conv_I1,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 int16，然后将其扩展（填充）为 int32。\n        /// </summary>\n        Conv_I2,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 int32。\n        /// </summary>\n        Conv_I4,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 int64。\n        /// </summary>\n        Conv_I8,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 float32。\n        /// </summary>\n        Conv_R4,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 float64。\n        /// </summary>\n        Conv_R8,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 unsigned int32，然后将其扩展为 int32。\n        /// </summary>\n        Conv_U4,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 unsigned int64，然后将其扩展为 int64。\n        /// </summary>\n        Conv_U8,\n        /// <summary>\n        /// 对对象调用后期绑定方法，并且将返回值推送到计算堆栈上。\n        /// </summary>\n        Callvirt,\n        /// <summary>\n        /// 将位于对象（&、* 或 native int 类型）地址的值类型复制到目标对象（&、* 或 native int 类型）的地址。\n        /// </summary>\n        Cpobj,\n        /// <summary>\n        /// 将地址指向的值类型对象复制到计算堆栈的顶部。\n        /// </summary>\n        Ldobj,\n        /// <summary>\n        /// 推送对元数据中存储的字符串的新对象引用。\n        /// </summary>\n        Ldstr,\n        /// <summary>\n        /// 创建一个值类型的新对象或新实例，并将对象引用（O 类型）推送到计算堆栈上。\n        /// </summary>\n        Newobj,\n        /// <summary>\n        /// 尝试将引用传递的对象转换为指定的类。\n        /// </summary>\n        Castclass,\n        /// <summary>\n        /// 测试对象引用（O 类型）是否为特定类的实例。\n        /// </summary>\n        Isinst,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号整数值转换为 float32。\n        /// </summary>\n        Conv_R_Un,\n        /// <summary>\n        /// 将值类型的已装箱的表示形式转换为其未装箱的形式。\n        /// </summary>\n        Unbox,\n        /// <summary>\n        /// 引发当前位于计算堆栈上的异常对象。\n        /// </summary>\n        Throw,\n        /// <summary>\n        /// 查找对象中其引用当前位于计算堆栈的字段的值。\n        /// </summary>\n        Ldfld,\n        /// <summary>\n        /// 查找对象中其引用当前位于计算堆栈的字段的地址。\n        /// </summary>\n        Ldflda,\n        /// <summary>\n        /// 用新值替换在对象引用或指针的字段中存储的值。\n        /// </summary>\n        Stfld,\n        /// <summary>\n        /// 将静态字段的值推送到计算堆栈上。\n        /// </summary>\n        Ldsfld,\n        /// <summary>\n        /// 将静态字段的地址推送到计算堆栈上。\n        /// </summary>\n        Ldsflda,\n        /// <summary>\n        /// 用来自计算堆栈的值替换静态字段的值。\n        /// </summary>\n        Stsfld,\n        /// <summary>\n        /// 将指定类型的值从计算堆栈复制到所提供的内存地址中。\n        /// </summary>\n        Stobj,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为有符号 int8 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I1_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为有符号 int16 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I2_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为有符号 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I4_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为有符号 int64，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I8_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为 unsigned int8 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U1_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为 unsigned int16 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U2_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为 unsigned int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U4_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为 unsigned int64，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U8_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为有符号 native int，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为 unsigned native int，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U_Un,\n        /// <summary>\n        /// 将值类转换为对象引用（O 类型）。\n        /// </summary>\n        Box,\n        /// <summary>\n        /// 将对新的从零开始的一维数组（其元素属于特定类型）的对象引用推送到计算堆栈上。\n        /// </summary>\n        Newarr,\n        /// <summary>\n        /// 将从零开始的、一维数组的元素的数目推送到计算堆栈上。\n        /// </summary>\n        Ldlen,\n        /// <summary>\n        /// 将位于指定数组索引的数组元素的地址作为 & 类型（托管指针）加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelema,\n        /// <summary>\n        /// 将位于指定数组索引处的 int8 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_I1,\n        /// <summary>\n        /// 将位于指定数组索引处的 unsigned int8 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_U1,\n        /// <summary>\n        /// 将位于指定数组索引处的 int16 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_I2,\n        /// <summary>\n        /// 将位于指定数组索引处的 unsigned int16 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_U2,\n        /// <summary>\n        /// 将位于指定数组索引处的 int32 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_I4,\n        /// <summary>\n        /// 将位于指定数组索引处的 unsigned int32 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_U4,\n        /// <summary>\n        /// 将位于指定数组索引处的 int64 类型的元素作为 int64 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_I8,\n        /// <summary>\n        /// 将位于指定数组索引处的 native int 类型的元素作为 native int 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_I,\n        /// <summary>\n        /// 将位于指定数组索引处的 float32 类型的元素作为 F 类型（浮点型）加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_R4,\n        /// <summary>\n        /// 将位于指定数组索引处的 float64 类型的元素作为 F 类型（浮点型）加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_R8,\n        /// <summary>\n        /// 将位于指定数组索引处的包含对象引用的元素作为 O 类型（对象引用）加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_Ref,\n        /// <summary>\n        /// 用计算堆栈上的 native int 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_I,\n        /// <summary>\n        /// 用计算堆栈上的 int8 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_I1,\n        /// <summary>\n        /// 用计算堆栈上的 int16 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_I2,\n        /// <summary>\n        /// 用计算堆栈上的 int32 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_I4,\n        /// <summary>\n        /// 用计算堆栈上的 int64 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_I8,\n        /// <summary>\n        /// 用计算堆栈上的 float32 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_R4,\n        /// <summary>\n        /// 用计算堆栈上的 float64 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_R8,\n        /// <summary>\n        /// 用计算堆栈上的对象 ref 值（O 类型）替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_Ref,\n        /// <summary>\n        /// 按照指令中指定的类型，将指定数组索引中的元素加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_Any,\n        /// <summary>\n        /// 用计算堆栈中的值替换给定索引处的数组元素，其类型在指令中指定。\n        /// </summary>\n        Stelem_Any,\n        /// <summary>\n        /// 将指令中指定类型的已装箱的表示形式转换成未装箱形式。\n        /// </summary>\n        Unbox_Any,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为有符号 int8 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I1,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为 unsigned int8 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U1,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为有符号 int16 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I2,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为 unsigned int16 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U2,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为有符号 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I4,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为 unsigned int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U4,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为有符号 int64，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I8,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为 unsigned int64，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U8,\n        /// <summary>\n        /// 检索嵌入在类型化引用内的地址（& 类型）。\n        /// </summary>\n        Refanyval,\n        /// <summary>\n        /// 如果值不是有限数，则引发 ArithmeticException。\n        /// </summary>\n        Ckfinite,\n        /// <summary>\n        /// 将对特定类型实例的类型化引用推送到计算堆栈上。\n        /// </summary>\n        Mkrefany,\n        /// <summary>\n        /// 将元数据标记转换为其运行时表示形式，并将其推送到计算堆栈上。\n        /// </summary>\n        Ldtoken,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 unsigned int16，然后将其扩展为 int32。\n        /// </summary>\n        Conv_U2,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 unsigned int8，然后将其扩展为 int32。\n        /// </summary>\n        Conv_U1,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 native int。\n        /// </summary>\n        Conv_I,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为有符号 native int，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为 unsigned native int，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U,\n        /// <summary>\n        /// 将两个整数相加，执行溢出检查，并且将结果推送到计算堆栈上。\n        /// </summary>\n        Add_Ovf,\n        /// <summary>\n        /// 将两个无符号整数值相加，执行溢出检查，并且将结果推送到计算堆栈上。\n        /// </summary>\n        Add_Ovf_Un,\n        /// <summary>\n        /// 将两个整数值相乘，执行溢出检查，并将结果推送到计算堆栈上。\n        /// </summary>\n        Mul_Ovf,\n        /// <summary>\n        /// 将两个无符号整数值相乘，执行溢出检查，并将结果推送到计算堆栈上。\n        /// </summary>\n        Mul_Ovf_Un,\n        /// <summary>\n        /// 从另一值中减去一个整数值，执行溢出检查，并且将结果推送到计算堆栈上。\n        /// </summary>\n        Sub_Ovf,\n        /// <summary>\n        /// 从另一值中减去一个无符号整数值，执行溢出检查，并且将结果推送到计算堆栈上。\n        /// </summary>\n        Sub_Ovf_Un,\n        /// <summary>\n        /// 将控制从异常块的 fault 或 finally 子句转移回公共语言结构 (CLI) 异常处理程序。\n        /// </summary>\n        Endfinally,\n        /// <summary>\n        /// 退出受保护的代码区域，无条件将控制转移到特定目标指令。\n        /// </summary>\n        Leave,\n        /// <summary>\n        /// 退出受保护的代码区域，无条件将控制转移到目标指令（缩写形式）。\n        /// </summary>\n        Leave_S,\n        /// <summary>\n        /// 在所提供的地址存储 native int 类型的值。\n        /// </summary>\n        Stind_I,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 unsigned native int，然后将其扩展为 native int。\n        /// </summary>\n        Conv_U,\n        /// <summary>\n        /// 返回指向当前方法的参数列表的非托管指针。\n        /// </summary>\n        Arglist,\n        /// <summary>\n        /// 比较两个值。如果这两个值相等，则将整数值 1 (int32) 推送到计算堆栈上；否则，将 0 (int32) 推送到计算堆栈上。\n        /// </summary>\n        Ceq,\n        /// <summary>\n        /// 比较两个值。如果第一个值大于第二个值，则将整数值 1 (int32) 推送到计算堆栈上；反之，将 0 (int32) 推送到计算堆栈上。\n        /// </summary>\n        Cgt,\n        /// <summary>\n        /// 比较两个无符号的或不可排序的值。如果第一个值大于第二个值，则将整数值 1 (int32) 推送到计算堆栈上；反之，将 0 (int32) 推送到计算堆栈上。\n        /// </summary>\n        Cgt_Un,\n        /// <summary>\n        /// 比较两个值。如果第一个值小于第二个值，则将整数值 1 (int32) 推送到计算堆栈上；反之，将 0 (int32) 推送到计算堆栈上。\n        /// </summary>\n        Clt,\n        /// <summary>\n        /// 比较无符号的或不可排序的值 value1 和 value2。如果 value1 小于 value2，则将整数值 1 (int32 ) 推送到计算堆栈上；反之，将 0 ( int32 ) 推送到计算堆栈上。\n        /// </summary>\n        Clt_Un,\n        /// <summary>\n        /// 将指向实现特定方法的本机代码的非托管指针（native int 类型）推送到计算堆栈上。\n        /// </summary>\n        Ldftn,\n        /// <summary>\n        /// 将指向实现与指定对象关联的特定虚方法的本机代码的非托管指针（native int 类型）推送到计算堆栈上。\n        /// </summary>\n        Ldvirtftn,\n        /// <summary>\n        /// 将参数（由指定索引值引用）加载到堆栈上。\n        /// </summary>\n        Ldarg,\n        /// <summary>\n        /// 将参数地址加载到计算堆栈上。\n        /// </summary>\n        Ldarga,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值存储到位于指定索引的参数槽中。\n        /// </summary>\n        Starg,\n        /// <summary>\n        /// 将指定索引处的局部变量加载到计算堆栈上。\n        /// </summary>\n        Ldloc,\n        /// <summary>\n        /// 将位于特定索引处的局部变量的地址加载到计算堆栈上。\n        /// </summary>\n        Ldloca,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储到指定索引处的局部变量列表中。\n        /// </summary>\n        Stloc,\n        /// <summary>\n        /// 从本地动态内存池分配特定数目的字节并将第一个分配的字节的地址（瞬态指针，* 类型）推送到计算堆栈上。\n        /// </summary>\n        Localloc,\n        /// <summary>\n        /// 将控制从异常的 filter 子句转移回公共语言结构 (CLI) 异常处理程序。\n        /// </summary>\n        Endfilter,\n        /// <summary>\n        /// 指示当前位于计算堆栈上的地址可能没有与紧接的 ldind、stind、ldfld、stfld、ldobj、stobj、initblk 或 cpblk 指令的自然大小对齐。\n        /// </summary>\n        Unaligned,\n        /// <summary>\n        /// 指定当前位于计算堆栈顶部的地址可以是易失的，并且读取该位置的结果不能被缓存，或者对该地址的多个存储区不能被取消。\n        /// </summary>\n        Volatile,\n        /// <summary>\n        /// 执行后缀的方法调用指令，以便在执行实际调用指令前移除当前方法的堆栈帧。\n        /// </summary>\n        Tail,\n        /// <summary>\n        /// 将位于指定地址的值类型的每个字段初始化为空引用或适当的基元类型的 0。\n        /// </summary>\n        Initobj,\n        /// <summary>\n        /// 约束要对其进行虚方法调用的类型。\n        /// </summary>\n        Constrained,\n        /// <summary>\n        /// 将指定数目的字节从源地址复制到目标地址。\n        /// </summary>\n        Cpblk,\n        /// <summary>\n        /// 将位于特定地址的内存的指定块初始化为给定大小和初始值。\n        /// </summary>\n        Initblk,\n        No,\n        /// <summary>\n        /// 再次引发当前异常。\n        /// </summary>\n        Rethrow,\n        /// <summary>\n        /// 将提供的值类型的大小（以字节为单位）推送到计算堆栈上。\n        /// </summary>\n        Sizeof,\n        /// <summary>\n        /// 检索嵌入在类型化引用内的类型标记。\n        /// </summary>\n        Refanytype,\n        /// <summary>\n        /// 指定后面的数组地址操作在运行时不执行类型检查，并且返回可变性受限的托管指针。\n        /// </summary>\n        Readonly,\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Stack/RuntimeStack.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Other;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Runtime.Stack\n{\n    unsafe public class RuntimeStack : IDisposable\n    {\n        ILIntepreter intepreter;\n        StackObject* pointer;\n        StackObject* endOfMemory;\n        StackObject* valueTypePtr;\n\n        IntPtr nativePointer;\n\n#if DEBUG\n        IList<object> managedStack = new List<object>(32);\n#else\n        IList<object> managedStack = new UncheckedList<object>(32);\n#endif\n\n        Stack<StackFrame> frames = new Stack<StackFrame>();\n        const int MAXIMAL_STACK_OBJECTS = 1024 * 16;\n\n        public Stack<StackFrame> Frames { get { return frames; } }\n        public RuntimeStack(ILIntepreter intepreter)\n        {\n            this.intepreter = intepreter;\n\n            nativePointer = System.Runtime.InteropServices.Marshal.AllocHGlobal(sizeof(StackObject) * MAXIMAL_STACK_OBJECTS);\n            pointer = (StackObject*)nativePointer.ToPointer();\n            endOfMemory = Add(pointer, MAXIMAL_STACK_OBJECTS);\n            valueTypePtr = endOfMemory - 1;\n        }\n\n        ~RuntimeStack()\n        {\n            Dispose();\n        }\n\n        public StackObject* StackBase\n        {\n            get\n            {\n                return pointer;\n            }\n        }\n\n        public StackObject* ValueTypeStackPointer\n        {\n            get\n            {\n                return valueTypePtr;\n            }\n        }\n\n        public StackObject* ValueTypeStackBase\n        {\n            get\n            {\n                return endOfMemory - 1;\n            }\n        }\n\n        public IList<object> ManagedStack { get { return managedStack; } }\n\n        public void ResetValueTypePointer()\n        {\n            valueTypePtr = endOfMemory - 1;\n        }\n\n        public void InitializeFrame(ILMethod method, StackObject* esp, out StackFrame res)\n        {\n            if (esp < pointer || esp >= endOfMemory)\n                throw new StackOverflowException();\n            if (frames.Count > 0 && frames.Peek().BasePointer > esp)\n                throw new StackOverflowException();\n            res = new StackFrame();\n            res.LocalVarPointer = esp;\n            res.Method = method;\n#if DEBUG\n            res.Address = new IntegerReference();\n            for (int i = 0; i < method.LocalVariableCount; i++)\n            {\n                var p = Add(esp, i);\n                p->ObjectType = ObjectTypes.Null;\n            }\n#endif\n            res.BasePointer = method.LocalVariableCount > 0 ? Add(esp, method.LocalVariableCount + 1) : esp;\n            res.ManagedStackBase = managedStack.Count;\n            res.ValueTypeBasePointer = valueTypePtr;\n            //frames.Push(res);\n        }\n        public void PushFrame(ref StackFrame frame)\n        {\n            frames.Push(frame);\n        }\n\n        public StackObject* PopFrame(ref StackFrame frame, StackObject* esp)\n        {\n            if (frames.Count > 0 && frames.Peek().BasePointer == frame.BasePointer)\n                frames.Pop();\n            else\n                throw new NotSupportedException();\n            StackObject* returnVal = esp - 1;\n            var method = frame.Method;\n            StackObject* ret = ILIntepreter.Minus(frame.LocalVarPointer, method.ParameterCount);\n            int mStackBase = frame.ManagedStackBase;\n            if (method.HasThis)\n                ret--;\n            if(method.ReturnType != intepreter.AppDomain.VoidType)\n            {\n                *ret = *returnVal;\n                if(ret->ObjectType == ObjectTypes.Object)\n                {\n                    ret->Value = mStackBase;\n                    managedStack[mStackBase] = managedStack[returnVal->Value];\n                    mStackBase++;\n                }\n                else if(ret->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                {\n                    StackObject* oriAddr = frame.ValueTypeBasePointer;\n                    RelocateValueType(ret, ref frame.ValueTypeBasePointer, ref mStackBase);\n                    *(StackObject**)&ret->Value = oriAddr;\n                }\n                ret++;\n            }\n#if DEBUG\n            ((List<object>)managedStack).RemoveRange(mStackBase, managedStack.Count - mStackBase);\n#else\n            ((UncheckedList<object>)managedStack).RemoveRange(mStackBase, managedStack.Count - mStackBase);\n#endif\n            valueTypePtr = frame.ValueTypeBasePointer;\n            return ret;\n        }\n\n        void RelocateValueType(StackObject* src, ref StackObject* dst, ref int mStackBase)\n        {\n            StackObject* descriptor = *(StackObject**)&src->Value;\n            if (descriptor > dst)\n                throw new StackOverflowException();\n            *dst = *descriptor;\n            int cnt = descriptor->ValueLow;\n            StackObject* endAddr = ILIntepreter.Minus(dst, cnt + 1);\n            for(int i = 0; i < cnt; i++)\n            {\n                StackObject* addr = ILIntepreter.Minus(descriptor, i + 1);\n                StackObject* tarVal = ILIntepreter.Minus(dst, i + 1);\n                *tarVal = *addr;\n                switch (addr->ObjectType)\n                {\n                    case ObjectTypes.Object:\n                    case ObjectTypes.ArrayReference:\n                    case ObjectTypes.FieldReference:\n                        if (tarVal->Value >= mStackBase)\n                        {\n                            int oldIdx = addr->Value;\n                            tarVal->Value = mStackBase;\n                            managedStack[mStackBase] = managedStack[oldIdx];\n                            mStackBase++;\n                        }\n                        break;\n                    case ObjectTypes.ValueTypeObjectReference:\n                        var newAddr = endAddr;\n                        RelocateValueType(addr, ref endAddr, ref mStackBase);\n                        *(StackObject**)&tarVal->Value = newAddr;\n                        break;\n                }\n            }\n            dst = endAddr;\n        }\n\n        public void AllocValueType(StackObject* ptr, IType type)\n        {\n            if (type.IsValueType)\n            {\n                int fieldCount = 0;\n                if(type is ILType)\n                {\n                    fieldCount = ((ILType)type).TotalFieldCount;\n                }\n                else\n                {\n                    fieldCount = ((CLRType)type).TotalFieldCount;\n                }\n                ptr->ObjectType = ObjectTypes.ValueTypeObjectReference;\n                var dst = valueTypePtr;\n                *(StackObject**)&ptr->Value = dst;\n                dst->ObjectType = ObjectTypes.ValueTypeDescriptor;\n                dst->Value = type.GetHashCode();\n                dst->ValueLow = fieldCount;\n                valueTypePtr = ILIntepreter.Minus(valueTypePtr, fieldCount + 1);\n                if (valueTypePtr <= StackBase)\n                    throw new StackOverflowException();\n                InitializeValueTypeObject(type, dst);\n            }\n            else\n                throw new ArgumentException(type.FullName + \" is not a value type.\", \"type\");\n        }\n\n        void InitializeValueTypeObject(IType type, StackObject* ptr)\n        {\n            if (type is ILType)\n            {\n                ILType t = (ILType)type;\n                for (int i = 0; i < t.FieldTypes.Length; i++)\n                {\n                    var ft = t.FieldTypes[i];\n                    StackObject* val = ILIntepreter.Minus(ptr, t.FieldStartIndex + i + 1);\n                    if (ft.IsPrimitive)\n                        StackObject.Initialized(val, ft);\n                    else\n                    {\n                        if (ft.IsValueType)\n                        {\n                            AllocValueType(val, ft);\n                        }\n                        else\n                        {\n                            val->ObjectType = ObjectTypes.Object;\n                            val->Value = managedStack.Count;\n                            managedStack.Add(null);\n                        }\n                    }\n                }\n                if (type.BaseType != null && type.BaseType is ILType)\n                    InitializeValueTypeObject((ILType)type.BaseType, ptr);\n            }\n            else\n            {\n                CLRType t = (CLRType)type;\n                var cnt = t.TotalFieldCount;\n                for(int i = 0; i < cnt; i++)\n                {\n                    var it = t.OrderedFieldTypes[i] as CLRType;\n                    StackObject* val = ILIntepreter.Minus(ptr, i + 1);\n                    if (it.IsPrimitive)\n                        StackObject.Initialized(val, it);\n                    else\n                    {\n                        if (it.IsValueType)\n                        {\n                            if (it.ValueTypeBinder != null)\n                                AllocValueType(val, it);\n                            else\n                            {\n                                val->ObjectType = ObjectTypes.Object;\n                                val->Value = managedStack.Count;\n                                managedStack.Add(it.CreateDefaultInstance());\n                            }\n                        }\n                        else\n                        {\n                            val->ObjectType = ObjectTypes.Object;\n                            val->Value = managedStack.Count;\n                            managedStack.Add(null);\n                        }\n                    }\n                }\n            }\n        }\n\n        public void ClearValueTypeObject(IType type, StackObject* ptr)\n        {\n            if (type is ILType)\n            {\n                ILType t = (ILType)type;\n                for (int i = 0; i < t.FieldTypes.Length; i++)\n                {\n                    var ft = t.FieldTypes[i];\n                    StackObject* val = ILIntepreter.Minus(ptr, t.FieldStartIndex + i + 1);\n                    if (ft.IsPrimitive)\n                        StackObject.Initialized(val, ft);\n                    else\n                    {\n                        switch (val->ObjectType)\n                        {\n                            case ObjectTypes.ValueTypeObjectReference:\n                                ClearValueTypeObject(ft, *(StackObject**)&val->Value);\n                                break;\n                            default:\n                                if (ft.IsValueType)\n                                {\n                                    if(ft is ILType)\n                                    {\n                                        throw new NotImplementedException();\n                                    }\n                                    else\n                                    {\n                                        managedStack[val->Value] = ((CLRType)ft).CreateDefaultInstance();\n                                    }\n                                }\n                                else\n                                    managedStack[val->Value] = null;\n                                break;\n                        }\n                    }\n                }\n                if (type.BaseType != null && type.BaseType is ILType)\n                    ClearValueTypeObject((ILType)type.BaseType, ptr);\n            }\n            else\n            {\n                CLRType t = (CLRType)type;\n                var cnt = t.TotalFieldCount;\n                for (int i = 0; i < cnt; i++)\n                {\n                    var vt = t.OrderedFieldTypes[i] as CLRType;\n                    StackObject* val = ILIntepreter.Minus(ptr, i + 1);\n                    if (vt.IsPrimitive)\n                        StackObject.Initialized(val, vt);\n                    else\n                    {\n                        switch (val->ObjectType)\n                        {\n                            case ObjectTypes.ValueTypeObjectReference:\n                                {\n                                    var dst = *(StackObject**)&val->Value;\n                                    ClearValueTypeObject(vt, *(StackObject**)&val->Value);\n                                }\n                                break;\n                            default:\n                                if (vt.IsValueType)\n                                {\n                                    managedStack[val->Value] = vt.CreateDefaultInstance();\n                                }\n                                else\n                                    managedStack[val->Value] = null;\n                                break;\n                        }\n                    }\n                }\n            }\n        }\n\n        public void FreeValueTypeObject(StackObject* esp)\n        {\n            int start = int.MaxValue;\n            int end = int.MinValue;\n            StackObject* endAddr;\n            CountValueTypeManaged(esp, ref start, ref end, &endAddr);\n\n            if (endAddr == valueTypePtr)\n                valueTypePtr = *(StackObject**)&esp->Value;\n            else\n                throw new NotSupportedException();\n            if (start != int.MaxValue)\n            {\n                if (end == managedStack.Count - 1)\n                {\n#if DEBUG\n                    ((List<object>)managedStack).RemoveRange(start, managedStack.Count - start);\n#else\n                    ((UncheckedList<object>)managedStack).RemoveRange(start, managedStack.Count - start);\n#endif\n                }\n                else\n                    throw new NotSupportedException();\n            }\n        }\n\n        void CountValueTypeManaged(StackObject* esp, ref int start, ref int end, StackObject** endAddr)\n        {\n            StackObject* descriptor = *(StackObject**)&esp->Value;\n            int cnt = descriptor->ValueLow;\n            *endAddr = ILIntepreter.Minus(descriptor, cnt + 1);\n            for (int i = 0; i < cnt; i++)\n            {\n                StackObject* addr = ILIntepreter.Minus(descriptor, i + 1);\n                switch (addr->ObjectType)\n                {\n                    case ObjectTypes.Object:\n                    case ObjectTypes.ArrayReference:\n                    case ObjectTypes.FieldReference:\n                        {\n                            if (start == int.MaxValue)\n                            {\n                                start = addr->Value;\n                                end = start;\n                            }\n                            else if (addr->Value == end + 1)\n                                end++;\n                            else\n                                throw new NotSupportedException();\n                        }\n                        break;\n                    case ObjectTypes.ValueTypeObjectReference:\n                        CountValueTypeManaged(addr, ref start, ref end, endAddr);\n                        break;\n                }\n\n            }\n        }\n\n        public void Dispose()\n        {\n            if (nativePointer != IntPtr.Zero)\n            {\n                System.Runtime.InteropServices.Marshal.FreeHGlobal(nativePointer);\n                nativePointer = IntPtr.Zero;\n            }\n        }\n\n        StackObject* Add(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a + sizeof(StackObject) * b);\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Stack/StackFrame.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.Method;\n\nnamespace ILRuntime.Runtime.Stack\n{\n    public class IntegerReference\n    {\n        public int Value { get; set; }\n    }\n    unsafe public struct StackFrame\n    {\n        public ILMethod Method;\n        public StackObject* LocalVarPointer;\n        public StackObject* BasePointer;\n        public StackObject* ValueTypeBasePointer;\n        public IntegerReference Address;\n        public int ManagedStackBase;\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime/Runtime/Stack/StackObject.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nnamespace ILRuntime.Runtime.Stack\n{\n    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]\n    public struct StackObject\n    {\n        public static StackObject Null = new StackObject() { ObjectType = ObjectTypes.Null, Value = -1, ValueLow = 0 };\n        public ObjectTypes ObjectType;\n        public int Value;\n        public int ValueLow;\n\n        //IL2CPP can't process esp->ToObject() properly, so I can only use static function for this\n        public static unsafe object ToObject(StackObject* esp, ILRuntime.Runtime.Enviorment.AppDomain appdomain, IList<object> mStack)\n        {\n            switch (esp->ObjectType)\n            {\n                case ObjectTypes.Integer:\n                    return esp->Value;\n                case ObjectTypes.Long:\n                    {\n                        return *(long*)&esp->Value;\n                    }\n                case ObjectTypes.Float:\n                    {\n                        return *(float*)&esp->Value;\n                    }\n                case ObjectTypes.Double:\n                    {\n                        return *(double*)&esp->Value;\n                    }\n                case ObjectTypes.Object:\n                    return mStack[esp->Value];\n                case ObjectTypes.FieldReference:\n                    {\n                        ILTypeInstance instance = mStack[esp->Value] as ILTypeInstance;\n                        if (instance != null)\n                        {\n                            return instance[esp->ValueLow];\n                        }\n                        else\n                        {\n                            var obj = mStack[esp->Value];\n                            IType t = null;\n                            if (obj is CrossBindingAdaptorType)\n                            {\n                                t = appdomain.GetType(((CrossBindingAdaptor)((CrossBindingAdaptorType)obj).ILInstance.Type.FirstCLRBaseType).BaseCLRType);\n                            }\n                            else\n                                t = appdomain.GetType(obj.GetType());\n\n                            return ((CLRType)t).GetFieldValue(esp->ValueLow, obj);\n                        }\n                    }\n                case ObjectTypes.ArrayReference:\n                    {\n                        Array instance = mStack[esp->Value] as Array;\n                        return instance.GetValue(esp->ValueLow);\n                    }\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = appdomain.GetType(esp->Value);\n                        if (t is CLR.TypeSystem.ILType)\n                        {\n                            CLR.TypeSystem.ILType type = (CLR.TypeSystem.ILType)t;\n                            return type.StaticInstance[esp->ValueLow];\n                        }\n                        else\n                        {\n                            CLR.TypeSystem.CLRType type = (CLR.TypeSystem.CLRType)t;\n                            return type.GetFieldValue(esp->ValueLow, null);\n                        }\n                    }\n                case ObjectTypes.StackObjectReference:\n                    {\n                        return ToObject((*(StackObject**)&esp->Value), appdomain, mStack);\n                    }\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        StackObject* dst = *(StackObject**)&esp->Value;\n                        IType type = appdomain.GetType(dst->Value);\n                        if (type is ILType)\n                        {\n                            ILType iltype = (ILType)type;\n                            var ins = iltype.Instantiate(false);\n                            for (int i = 0; i < dst->ValueLow; i++)\n                            {\n                                var addr = ILIntepreter.Minus(dst, i + 1);\n                                ins.AssignFromStack(i, addr, appdomain, mStack);\n                            }\n                            return ins;\n                        }\n                        else\n                        {\n                            return ((CLRType)type).ValueTypeBinder.ToObject(dst, mStack);\n                        }\n                    }\n                case ObjectTypes.Null:\n                    return null;\n                default:\n                    throw new NotImplementedException();\n            }\n        }\n\n        public unsafe static void Initialized(ref StackObject esp, int idx, Type t, IType fieldType, IList<object> mStack)\n        {\n            if (t.IsPrimitive)\n            {\n                if (t == typeof(int) || t == typeof(uint) || t == typeof(short) || t == typeof(ushort) || t == typeof(byte) || t == typeof(sbyte) || t == typeof(char) || t == typeof(bool))\n                {\n                    esp.ObjectType = ObjectTypes.Integer;\n                    esp.Value = 0;\n                    esp.ValueLow = 0;\n                }\n                else if (t == typeof(long) || t == typeof(ulong))\n                {\n                    esp.ObjectType = ObjectTypes.Long;\n                    esp.Value = 0;\n                    esp.ValueLow = 0;\n                }\n                else if (t == typeof(float))\n                {\n                    esp.ObjectType = ObjectTypes.Float;\n                    esp.Value = 0;\n                    esp.ValueLow = 0;\n                }\n                else if (t == typeof(double))\n                {\n                    esp.ObjectType = ObjectTypes.Double;\n                    esp.Value = 0;\n                    esp.ValueLow = 0;\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                if (fieldType.IsValueType)\n                {\n                    esp.ObjectType = ObjectTypes.Object;\n                    esp.Value = idx;\n                    if (fieldType is CLRType)\n                    {\n                        mStack[idx] = ((CLRType)fieldType).CreateDefaultInstance();\n                    }\n                    else\n                    {\n                        mStack[idx] = ((ILType)fieldType).Instantiate();\n                    }\n                }\n                else\n                    esp = Null;\n            }\n        }\n\n        //IL2CPP can't process esp->Initialized() properly, so I can only use static function for this\n        public unsafe static void Initialized(StackObject* esp, IType type)\n        {\n            var t = type.TypeForCLR;\n            if (type.IsPrimitive)\n            {\n                if (t == typeof(int) || t == typeof(uint) || t == typeof(short) || t == typeof(ushort) || t == typeof(byte) || t == typeof(sbyte) || t == typeof(char) || t == typeof(bool))\n                {\n                    esp->ObjectType = ObjectTypes.Integer;\n                    esp->Value = 0;\n                    esp->ValueLow = 0;\n                }\n                else if (t == typeof(long) || t == typeof(ulong))\n                {\n                    esp->ObjectType = ObjectTypes.Long;\n                    esp->Value = 0;\n                    esp->ValueLow = 0;\n                }\n                else if (t == typeof(float))\n                {\n                    esp->ObjectType = ObjectTypes.Float;\n                    esp->Value = 0;\n                    esp->ValueLow = 0;\n                }\n                else if (t == typeof(double))\n                {\n                    esp->ObjectType = ObjectTypes.Double;\n                    esp->Value = 0;\n                    esp->ValueLow = 0;\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                *esp = Null;\n            }\n        }\n    }\n\n    public enum ObjectTypes\n    {\n        Null,\n        Integer,\n        Long,\n        Float,\n        Double,\n        StackObjectReference,//Value = pointer, \n        StaticFieldReference,\n        ValueTypeObjectReference,\n        ValueTypeDescriptor,\n        Object,\n        FieldReference,//Value = objIdx, ValueLow = fieldIdx\n        ArrayReference,//Value = objIdx, ValueLow = elemIdx\n    }\n}\n"
  },
  {
    "path": "ILRuntime/ILRuntime.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{0887056B-2D5E-4FBE-9F15-EFF3E2612CA7}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>ILRuntime</RootNamespace>\n    <AssemblyName>ILRuntime</AssemblyName>\n    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>\n    <TargetFrameworkProfile />\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>..\\Libs\\</OutputPath>\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>0</WarningLevel>\n    <Prefer32Bit>false</Prefer32Bit>\n    <DocumentationFile>\n    </DocumentationFile>\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>..\\Libs\\</OutputPath>\n    <DefineConstants>TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>0</WarningLevel>\n    <Prefer32Bit>false</Prefer32Bit>\n    <DocumentationFile>\n    </DocumentationFile>\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n  </PropertyGroup>\n  <PropertyGroup>\n    <StartupObject />\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"ILRuntime\\Adapters\\Editor\\ILRuntimeCLRBinding.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\Method\\CLRMethod.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\Method\\ExceptionHandler.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\Method\\ILMethod.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\Method\\IMethod.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\TypeSystem\\CLRType.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\TypeSystem\\ILGenericParameterType.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\TypeSystem\\ILType.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\TypeSystem\\IType.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\Utils\\Extensions.cs\" />\n    <Compile Include=\"ILRuntime\\Other\\ByReferenceKeyComparer.cs\" />\n    <Compile Include=\"ILRuntime\\Other\\DelegateExportAttribute.cs\" />\n    <Compile Include=\"ILRuntime\\Other\\NeedAdaptorAttribute.cs\" />\n    <Compile Include=\"ILRuntime\\Other\\ThreadSafeDictionary.cs\" />\n    <Compile Include=\"ILRuntime\\Other\\UncheckedList.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\Extensions.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeConstructorInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeFieldInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeMethodInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeParameterInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimePropertyInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeType.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeWrapperType.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Adaptors\\CLRCrossBindingAdaptors.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\BindingCodeGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\BindingGeneratorExtensions.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\CommonBindingGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\ConstructorBindingGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\FieldBindingGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\MethodBindingGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\ValueTypeBindingGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\BreakPointContext.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\BreakpointInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\DebuggerServer\\DebuggerServer.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\DebugMessageType.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\DebugService.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\DebugSocket.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\CSBindBreakpoint.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\CSDeleteBreakpoint.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\CSExecute.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\CSResolveVariable.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\CSStep.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCAttachResult.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCBindBreakpointResult.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCBreakpointHit.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCModuleLoaded.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCResolveVariableResult.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCStepComplete.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCThreadStarted.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\StackFrameInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\StepTypes.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\VariableInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\AppDomain.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\CLRRedirections.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\CrossBindingAdaptor.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\DelegateManager.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\ILContext.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\ValueTypeBinder.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Extensions.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\DelegateAdapter.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\ILIntepreter.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\ILRuntimeException.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\ILTypeInstance.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\OpCodes\\OpCode.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\OpCodes\\OpCodeEnum.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Stack\\RuntimeStack.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Stack\\StackFrame.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Stack\\StackObject.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\Code.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\CodeReader.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\CodeWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\Document.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\ExceptionHandler.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\ILProcessor.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\Instruction.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\MethodBody.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\OpCode.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\OpCodes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\SequencePoint.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\Symbols.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\VariableDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\VariableReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\BlobHeap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\Buffers.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\CodedIndex.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\ElementType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\GuidHeap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\Heap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\MetadataToken.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\Row.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\StringHeap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\TableHeap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\TokenType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\UserStringHeap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\Utilities.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\BinaryStreamReader.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\BinaryStreamWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\ByteBuffer.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\ByteBufferEqualityComparer.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\DataDirectory.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\Image.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\ImageReader.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\ImageWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\Section.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\TextMap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ArrayType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyFlags.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyHashAlgorithm.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyLinkedResource.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyNameDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyNameReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyReader.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\BaseAssemblyResolver.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\CallSite.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\CustomAttribute.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\DefaultAssemblyResolver.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\EmbeddedResource.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\EventAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\EventDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\EventReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ExportedType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\FieldAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\FieldDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\FieldReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\FileAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\FunctionPointerType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\GenericInstanceMethod.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\GenericInstanceType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\GenericParameter.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\GenericParameterAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IConstantProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ICustomAttributeProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IGenericInstance.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IGenericParameterProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IMarshalInfoProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IMemberDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IMetadataScope.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IMetadataTokenProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IMethodSignature.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\Import.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\LinkedResource.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ManifestResourceAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MarshalInfo.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MemberDefinitionCollection.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MemberReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MetadataResolver.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MetadataSystem.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodCallingConvention.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodImplAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodReturnType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodSemanticsAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodSpecification.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\Modifiers.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ModuleDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ModuleKind.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ModuleReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\NativeType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ParameterAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ParameterDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ParameterDefinitionCollection.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ParameterReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PinnedType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PInvokeAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PInvokeInfo.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PointerType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PropertyAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PropertyDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PropertyReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ReferenceType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\Resource.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\SecurityDeclaration.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\SentinelType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TargetRuntime.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeDefinitionCollection.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeParser.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeSpecification.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeSystem.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\VariantType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Collections.Generic\\Collection.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Collections.Generic\\ReadOnlyCollection.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Security.Cryptography\\CryptoConvert.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Security.Cryptography\\CryptoService.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono\\Actions.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono\\Empty.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono\\Funcs.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\BitAccess.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\BitSet.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\CvInfo.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\DataStream.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\DbiDbgHdr.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\DbiHeader.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\DbiModuleInfo.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\DbiSecCon.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\Interfaces.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\IntHashTable.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\MsfDirectory.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbConstant.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbDebugException.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbException.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbFile.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbFileHeader.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbFunction.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbLine.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbLines.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbReader.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbScope.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbSlot.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbSource.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\SourceLocationProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\ISymUnmanagedDocumentWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\ISymUnmanagedWriter2.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\ModuleMetadata.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\PdbHelper.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\PdbReader.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\PdbWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\SymDocumentWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\SymWriter.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"App.config\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <PropertyGroup>\n    <PostBuildEvent>$(ProjectDir)..\\Libs\\PublishLibrary.bat $(TargetName)</PostBuildEvent>\n  </PropertyGroup>\n</Project>"
  },
  {
    "path": "ILRuntime/ILRuntime.csproj.user",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <PropertyGroup>\n    <ProjectView>ProjectFiles</ProjectView>\n  </PropertyGroup>\n</Project>"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono/Actions.cs",
    "content": "//\n// Actions.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\n#if !NET_3_5 && !NET_4_0\n\nnamespace Mono {\n\t//delegate void Action ();\n    delegate void Action<T1, T2> (T1 arg1, T2 arg2);\n\t//delegate void Action<T1, T2, T3> (T1 arg1, T2 arg2, T3 arg3);\n\t//delegate void Action<T1, T2, T3, T4> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);\n}\n\n#endif\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono/Empty.cs",
    "content": "//\n// Empty.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Collections.Generic;\n\nnamespace Mono {\n\n\tstatic class Empty<T> {\n\n\t\tpublic static readonly T [] Array = new T [0];\n\t}\n}\n\nnamespace Mono.Cecil {\n\n\tstatic partial class Mixin {\n\n\t\tpublic static bool IsNullOrEmpty<T> (T [] self)\n\t\t{\n\t\t\treturn self == null || self.Length == 0;\n\t\t}\n\n\t\tpublic static bool IsNullOrEmpty<T> (Collection<T> self)\n\t\t{\n\t\t\treturn self == null || self.size == 0;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono/Funcs.cs",
    "content": "//\n// Funcs.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\n#if !NET_3_5 && !NET_4_0\n\nnamespace Mono {\n    delegate TResult Func<TResult> ();\n    delegate TResult Func<T, TResult> (T arg1);\n    delegate TResult Func<T1, T2, TResult> (T1 arg1, T2 arg2);\n\t//delegate TResult Func<T1, T2, T3, TResult> (T1 arg1, T2 arg2, T3 arg3);\n\t//delegate TResult Func<T1, T2, T3, T4, TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);\n}\n\n#endif\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ArrayType.cs",
    "content": "//\n// ArrayType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\nusing Mono.Collections.Generic;\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic struct ArrayDimension {\n\n\t\tint? lower_bound;\n\t\tint? upper_bound;\n\n\t\tpublic int? LowerBound {\n\t\t\tget { return lower_bound; }\n\t\t\tset { lower_bound = value; }\n\t\t}\n\n\t\tpublic int? UpperBound {\n\t\t\tget { return upper_bound; }\n\t\t\tset { upper_bound = value; }\n\t\t}\n\n\t\tpublic bool IsSized {\n\t\t\tget { return lower_bound.HasValue || upper_bound.HasValue; }\n\t\t}\n\n\t\tpublic ArrayDimension (int? lowerBound, int? upperBound)\n\t\t{\n\t\t\tthis.lower_bound = lowerBound;\n\t\t\tthis.upper_bound = upperBound;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn !IsSized\n\t\t\t\t? string.Empty\n\t\t\t\t: lower_bound + \"...\" + upper_bound;\n\t\t}\n\t}\n\n\tpublic sealed class ArrayType : TypeSpecification {\n\n\t\tCollection<ArrayDimension> dimensions;\n\n\t\tpublic Collection<ArrayDimension> Dimensions {\n\t\t\tget {\n\t\t\t\tif (dimensions != null)\n\t\t\t\t\treturn dimensions;\n\n\t\t\t\tdimensions = new Collection<ArrayDimension> ();\n\t\t\t\tdimensions.Add (new ArrayDimension ());\n\t\t\t\treturn dimensions;\n\t\t\t}\n\t\t}\n\n\t\tpublic int Rank {\n\t\t\tget { return dimensions == null ? 1 : dimensions.Count; }\n\t\t}\n\n\t\tpublic bool IsVector {\n\t\t\tget {\n\t\t\t\tif (dimensions == null)\n\t\t\t\t\treturn true;\n\n\t\t\t\tif (dimensions.Count > 1)\n\t\t\t\t\treturn false;\n\n\t\t\t\tvar dimension = dimensions [0];\n\n\t\t\t\treturn !dimension.IsSized;\n\t\t\t}\n\t\t}\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return base.Name + Suffix; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return base.FullName + Suffix; }\n\t\t}\n\n\t\tstring Suffix {\n\t\t\tget {\n\t\t\t\tif (IsVector)\n\t\t\t\t\treturn \"[]\";\n\n\t\t\t\tvar suffix = new StringBuilder ();\n\t\t\t\tsuffix.Append (\"[\");\n\t\t\t\tfor (int i = 0; i < dimensions.Count; i++) {\n\t\t\t\t\tif (i > 0)\n\t\t\t\t\t\tsuffix.Append (\",\");\n\n\t\t\t\t\tsuffix.Append (dimensions [i].ToString ());\n\t\t\t\t}\n\t\t\t\tsuffix.Append (\"]\");\n\n\t\t\t\treturn suffix.ToString ();\n\t\t\t}\n\t\t}\n\n\t\tpublic override bool IsArray {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic ArrayType (TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.etype = MD.ElementType.Array;\n\t\t}\n\n\t\tpublic ArrayType (TypeReference type, int rank)\n\t\t\t: this (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\n\t\t\tif (rank == 1)\n\t\t\t\treturn;\n\n\t\t\tdimensions = new Collection<ArrayDimension> (rank);\n\t\t\tfor (int i = 0; i < rank; i++)\n\t\t\t\tdimensions.Add (new ArrayDimension ());\n\t\t\tthis.etype = MD.ElementType.Array;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyDefinition.cs",
    "content": "//\n// AssemblyDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class AssemblyDefinition : ICustomAttributeProvider, ISecurityDeclarationProvider\n    {\n\n        AssemblyNameDefinition name;\n\n        internal ModuleDefinition main_module;\n        Collection<ModuleDefinition> modules;\n        Collection<CustomAttribute> custom_attributes;\n        Collection<SecurityDeclaration> security_declarations;\n\n        public AssemblyNameDefinition Name\n        {\n            get { return name; }\n            set { name = value; }\n        }\n\n        public string FullName\n        {\n            get { return name != null ? name.FullName : string.Empty; }\n        }\n\n        public MetadataToken MetadataToken\n        {\n            get { return new MetadataToken(TokenType.Assembly, 1); }\n            set { }\n        }\n\n        public Collection<ModuleDefinition> Modules\n        {\n            get\n            {\n                if (modules != null)\n                    return modules;\n\n                if (main_module.HasImage)\n                    return main_module.Read(ref modules, this, (_, reader) => reader.ReadModules());\n\n                return modules = new Collection<ModuleDefinition>(1) { main_module };\n            }\n        }\n\n        public ModuleDefinition MainModule\n        {\n            get { return main_module; }\n        }\n\n        public MethodDefinition EntryPoint\n        {\n            get { return main_module.EntryPoint; }\n            set { main_module.EntryPoint = value; }\n        }\n\n        public bool HasCustomAttributes\n        {\n            get\n            {\n                if (custom_attributes != null)\n                    return custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, main_module);\n            }\n        }\n\n        public Collection<CustomAttribute> CustomAttributes\n        {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, main_module)); }\n        }\n\n        public bool HasSecurityDeclarations\n        {\n            get\n            {\n                if (security_declarations != null)\n                    return security_declarations.Count > 0;\n\n                return Mixin.GetHasSecurityDeclarations(this, main_module);\n            }\n        }\n\n        public Collection<SecurityDeclaration> SecurityDeclarations\n        {\n            get { return security_declarations ?? (Mixin.GetSecurityDeclarations(this, ref security_declarations, main_module)); }\n        }\n\n        internal AssemblyDefinition()\n        {\n        }\n\n\n\n        public static AssemblyDefinition ReadAssembly(string fileName)\n        {\n            return ReadAssembly(ModuleDefinition.ReadModule(fileName));\n        }\n\n        public static AssemblyDefinition ReadAssembly(string fileName, ReaderParameters parameters)\n        {\n            return ReadAssembly(ModuleDefinition.ReadModule(fileName, parameters));\n        }\n\n        public static AssemblyDefinition ReadAssembly(Stream stream)\n        {\n            return ReadAssembly(ModuleDefinition.ReadModule(stream));\n        }\n\n        public static AssemblyDefinition ReadAssembly(Stream stream, ReaderParameters parameters)\n        {\n            return ReadAssembly(ModuleDefinition.ReadModule(stream, parameters));\n        }\n\n        static AssemblyDefinition ReadAssembly(ModuleDefinition module)\n        {\n            var assembly = module.Assembly;\n            if (assembly == null)\n                throw new ArgumentException();\n\n            return assembly;\n        }\n\n\n\n        public override string ToString()\n        {\n            return this.FullName;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyFlags.cs",
    "content": "//\n// AssemblyFlags.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum AssemblyAttributes : uint {\n\t\tPublicKey\t\t\t\t\t \t= 0x0001,\n\t\tSideBySideCompatible\t\t\t= 0x0000,\n\t\tRetargetable\t\t\t\t\t= 0x0100,\n\t\tWindowsRuntime\t\t\t\t\t= 0x0200,\n\t\tDisableJITCompileOptimizer\t\t= 0x4000,\n\t\tEnableJITCompileTracking\t\t= 0x8000,\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyHashAlgorithm.cs",
    "content": "//\n// AssemblyHashAlgorithm.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum AssemblyHashAlgorithm : uint {\n\t\tNone\t\t= 0x0000,\n\t\tReserved\t= 0x8003,\t// MD5\n\t\tSHA1\t\t= 0x8004\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyLinkedResource.cs",
    "content": "//\n// AssemblyLinkedResource.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class AssemblyLinkedResource : Resource {\n\n\t\tAssemblyNameReference reference;\n\n\t\tpublic AssemblyNameReference Assembly {\n\t\t\tget { return reference; }\n\t\t\tset { reference = value; }\n\t\t}\n\n\t\tpublic override ResourceType ResourceType {\n\t\t\tget { return ResourceType.AssemblyLinked; }\n\t\t}\n\n\t\tpublic AssemblyLinkedResource (string name, ManifestResourceAttributes flags)\n\t\t\t: base (name, flags)\n\t\t{\n\t\t}\n\n\t\tpublic AssemblyLinkedResource (string name, ManifestResourceAttributes flags, AssemblyNameReference reference)\n\t\t\t: base (name, flags)\n\t\t{\n\t\t\tthis.reference = reference;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyNameDefinition.cs",
    "content": "//\n// AssemblyNameDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class AssemblyNameDefinition : AssemblyNameReference {\n\n\t\tpublic override byte [] Hash {\n\t\t\tget { return Empty<byte>.Array; }\n\t\t}\n\n\t\tinternal AssemblyNameDefinition ()\n\t\t{\n\t\t\tthis.token = new MetadataToken (TokenType.Assembly, 1);\n\t\t}\n\n\t\tpublic AssemblyNameDefinition (string name, Version version)\n\t\t\t: base (name, version)\n\t\t{\n\t\t\tthis.token = new MetadataToken (TokenType.Assembly, 1);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyNameReference.cs",
    "content": "//\n// AssemblyNameReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Globalization;\nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace Mono.Cecil\n{\n\n    public class AssemblyNameReference : IMetadataScope\n    {\n\n        string name;\n        string culture;\n        Version version;\n        uint attributes;\n        byte[] public_key;\n        byte[] public_key_token;\n        AssemblyHashAlgorithm hash_algorithm;\n        byte[] hash;\n\n        internal MetadataToken token;\n\n        string full_name;\n\n        public string Name\n        {\n            get { return name; }\n            set\n            {\n                name = value;\n                full_name = null;\n            }\n        }\n\n        public string Culture\n        {\n            get { return culture; }\n            set\n            {\n                culture = value;\n                full_name = null;\n            }\n        }\n\n        public Version Version\n        {\n            get { return version; }\n            set\n            {\n                version = value;\n                full_name = null;\n            }\n        }\n\n        public AssemblyAttributes Attributes\n        {\n            get { return (AssemblyAttributes)attributes; }\n            set { attributes = (uint)value; }\n        }\n\n        public bool HasPublicKey\n        {\n            get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.PublicKey); }\n            set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.PublicKey, value); }\n        }\n\n        public bool IsSideBySideCompatible\n        {\n            get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.SideBySideCompatible); }\n            set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.SideBySideCompatible, value); }\n        }\n\n        public bool IsRetargetable\n        {\n            get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.Retargetable); }\n            set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.Retargetable, value); }\n        }\n\n        public bool IsWindowsRuntime\n        {\n            get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.WindowsRuntime); }\n            set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.WindowsRuntime, value); }\n        }\n\n        public byte[] PublicKey\n        {\n            get { return public_key ?? Empty<byte>.Array; }\n            set\n            {\n                public_key = value;\n                HasPublicKey = !Mixin.IsNullOrEmpty(public_key);\n                public_key_token = Empty<byte>.Array;\n                full_name = null;\n            }\n        }\n\n        public byte[] PublicKeyToken\n        {\n            get\n            {\n                if (Mixin.IsNullOrEmpty(public_key_token) && !Mixin.IsNullOrEmpty(public_key))\n                {\n                    var hash = HashPublicKey();\n                    // we need the last 8 bytes in reverse order\n                    byte[] local_public_key_token = new byte[8];\n                    Array.Copy(hash, (hash.Length - 8), local_public_key_token, 0, 8);\n                    Array.Reverse(local_public_key_token, 0, 8);\n                    public_key_token = local_public_key_token; // publish only once finished (required for thread-safety)\n                }\n                return public_key_token ?? Empty<byte>.Array;\n            }\n            set\n            {\n                public_key_token = value;\n                full_name = null;\n            }\n        }\n\n        byte[] HashPublicKey()\n        {\n            HashAlgorithm algorithm;\n\n            switch (hash_algorithm)\n            {\n                case AssemblyHashAlgorithm.Reserved:\n\n                    throw new NotSupportedException();\n\n                default:\n                    // None default to SHA1\n                    algorithm = new SHA1Managed();\n                    break;\n\n            }\n\n            using (algorithm)\n                return algorithm.ComputeHash(public_key);\n        }\n\n        public virtual MetadataScopeType MetadataScopeType\n        {\n            get { return MetadataScopeType.AssemblyNameReference; }\n        }\n\n        public string FullName\n        {\n            get\n            {\n                if (full_name != null)\n                    return full_name;\n\n                const string sep = \", \";\n\n                var builder = new StringBuilder();\n                builder.Append(name);\n                if (version != null)\n                {\n                    builder.Append(sep);\n                    builder.Append(\"Version=\");\n                    builder.Append(version.ToString());\n                }\n                builder.Append(sep);\n                builder.Append(\"Culture=\");\n                builder.Append(string.IsNullOrEmpty(culture) ? \"neutral\" : culture);\n                builder.Append(sep);\n                builder.Append(\"PublicKeyToken=\");\n\n                var pk_token = PublicKeyToken;\n                if (!Mixin.IsNullOrEmpty(pk_token) && pk_token.Length > 0)\n                {\n                    for (int i = 0; i < pk_token.Length; i++)\n                    {\n                        builder.Append(pk_token[i].ToString(\"x2\"));\n                    }\n                }\n                else\n                    builder.Append(\"null\");\n\n                return full_name = builder.ToString();\n            }\n        }\n\n        public static AssemblyNameReference Parse(string fullName)\n        {\n            if (fullName == null)\n                throw new ArgumentNullException(\"fullName\");\n            if (fullName.Length == 0)\n                throw new ArgumentException(\"Name can not be empty\");\n\n            var name = new AssemblyNameReference();\n            var tokens = fullName.Split(',');\n            for (int i = 0; i < tokens.Length; i++)\n            {\n                var token = tokens[i].Trim();\n\n                if (i == 0)\n                {\n                    name.Name = token;\n                    continue;\n                }\n\n                var parts = token.Split('=');\n                if (parts.Length != 2)\n                    throw new ArgumentException(\"Malformed name\");\n\n                switch (parts[0].ToLowerInvariant())\n                {\n                    case \"version\":\n                        name.Version = new Version(parts[1]);\n                        break;\n                    case \"culture\":\n                        name.Culture = parts[1];\n                        break;\n                    case \"publickeytoken\":\n                        var pk_token = parts[1];\n                        if (pk_token == \"null\")\n                            break;\n\n                        name.PublicKeyToken = new byte[pk_token.Length / 2];\n                        for (int j = 0; j < name.PublicKeyToken.Length; j++)\n                            name.PublicKeyToken[j] = Byte.Parse(pk_token.Substring(j * 2, 2), NumberStyles.HexNumber);\n\n                        break;\n                }\n            }\n\n            return name;\n        }\n\n        public AssemblyHashAlgorithm HashAlgorithm\n        {\n            get { return hash_algorithm; }\n            set { hash_algorithm = value; }\n        }\n\n        public virtual byte[] Hash\n        {\n            get { return hash; }\n            set { hash = value; }\n        }\n\n        public MetadataToken MetadataToken\n        {\n            get { return token; }\n            set { token = value; }\n        }\n\n        internal AssemblyNameReference()\n        {\n        }\n\n        public AssemblyNameReference(string name, Version version)\n        {\n            if (name == null)\n                throw new ArgumentNullException(\"name\");\n\n            this.name = name;\n            this.version = version;\n            this.hash_algorithm = AssemblyHashAlgorithm.None;\n            this.token = new MetadataToken(TokenType.AssemblyRef);\n        }\n\n        public override string ToString()\n        {\n            return this.FullName;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyReader.cs",
    "content": "//\n// AssemblyReader.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nusing Mono.Collections.Generic;\nusing Mono.Cecil.Cil;\nusing Mono.Cecil.Metadata;\nusing Mono.Cecil.PE;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil\n{\n\n    abstract class ModuleReader\n    {\n\n        readonly protected Image image;\n        readonly protected ModuleDefinition module;\n\n        protected ModuleReader(Image image, ReadingMode mode)\n        {\n            this.image = image;\n            this.module = new ModuleDefinition(image);\n            this.module.ReadingMode = mode;\n        }\n\n        protected abstract void ReadModule();\n\n        protected void ReadModuleManifest(MetadataReader reader)\n        {\n            reader.Populate(module);\n\n            ReadAssembly(reader);\n        }\n\n        void ReadAssembly(MetadataReader reader)\n        {\n            var name = reader.ReadAssemblyNameDefinition();\n            if (name == null)\n            {\n                module.kind = ModuleKind.NetModule;\n                return;\n            }\n\n            var assembly = new AssemblyDefinition();\n            assembly.Name = name;\n\n            module.assembly = assembly;\n            assembly.main_module = module;\n        }\n\n        public static ModuleDefinition CreateModuleFrom(Image image, ReaderParameters parameters)\n        {\n            var module = ReadModule(image, parameters);\n\n            ReadSymbols(module, parameters);\n\n            if (parameters.AssemblyResolver != null)\n                module.assembly_resolver = parameters.AssemblyResolver;\n\n            if (parameters.MetadataResolver != null)\n                module.metadata_resolver = parameters.MetadataResolver;\n\n            return module;\n        }\n\n        static void ReadSymbols(ModuleDefinition module, ReaderParameters parameters)\n        {\n            var symbol_reader_provider = parameters.SymbolReaderProvider;\n\n            if (symbol_reader_provider == null && parameters.ReadSymbols)\n                symbol_reader_provider = SymbolProvider.GetPlatformReaderProvider();\n\n            if (symbol_reader_provider != null)\n            {\n                module.SymbolReaderProvider = symbol_reader_provider;\n\n                var reader = parameters.SymbolStream != null\n                    ? symbol_reader_provider.GetSymbolReader(module, parameters.SymbolStream)\n                    : symbol_reader_provider.GetSymbolReader(module, module.FullyQualifiedName);\n\n                module.ReadSymbols(reader);\n            }\n        }\n\n        static ModuleDefinition ReadModule(Image image, ReaderParameters parameters)\n        {\n            var reader = CreateModuleReader(image, parameters.ReadingMode);\n            reader.ReadModule();\n            return reader.module;\n        }\n\n        static ModuleReader CreateModuleReader(Image image, ReadingMode mode)\n        {\n            switch (mode)\n            {\n                case ReadingMode.Immediate:\n                    return new ImmediateModuleReader(image);\n                case ReadingMode.Deferred:\n                    return new DeferredModuleReader(image);\n                default:\n                    throw new ArgumentException();\n            }\n        }\n    }\n\n    sealed class ImmediateModuleReader : ModuleReader\n    {\n\n        public ImmediateModuleReader(Image image)\n            : base(image, ReadingMode.Immediate)\n        {\n        }\n\n        protected override void ReadModule()\n        {\n            this.module.Read(this.module, (module, reader) =>\n            {\n                ReadModuleManifest(reader);\n                ReadModule(module);\n                return module;\n            });\n        }\n\n        public static void ReadModule(ModuleDefinition module)\n        {\n            if (module.HasAssemblyReferences)\n                Read(module.AssemblyReferences);\n            if (module.HasResources)\n                Read(module.Resources);\n            if (module.HasModuleReferences)\n                Read(module.ModuleReferences);\n            if (module.HasTypes)\n                ReadTypes(module.Types);\n            if (module.HasExportedTypes)\n                Read(module.ExportedTypes);\n            if (module.HasCustomAttributes)\n                Read(module.CustomAttributes);\n\n            var assembly = module.Assembly;\n            if (assembly == null)\n                return;\n\n            if (assembly.HasCustomAttributes)\n                Read(assembly.CustomAttributes);\n            if (assembly.HasSecurityDeclarations)\n                Read(assembly.SecurityDeclarations);\n        }\n\n        static void ReadTypes(Collection<TypeDefinition> types)\n        {\n            for (int i = 0; i < types.Count; i++)\n                ReadType(types[i]);\n        }\n\n        static void ReadType(TypeDefinition type)\n        {\n            ReadGenericParameters(type);\n\n            if (type.HasInterfaces)\n                Read(type.Interfaces);\n\n            if (type.HasNestedTypes)\n                ReadTypes(type.NestedTypes);\n\n            if (type.HasLayoutInfo)\n                Read(type.ClassSize);\n\n            if (type.HasFields)\n                ReadFields(type);\n\n            if (type.HasMethods)\n                ReadMethods(type);\n\n            if (type.HasProperties)\n                ReadProperties(type);\n\n            if (type.HasEvents)\n                ReadEvents(type);\n\n            ReadSecurityDeclarations(type);\n            ReadCustomAttributes(type);\n        }\n\n        static void ReadGenericParameters(IGenericParameterProvider provider)\n        {\n            if (!provider.HasGenericParameters)\n                return;\n\n            var parameters = provider.GenericParameters;\n\n            for (int i = 0; i < parameters.Count; i++)\n            {\n                var parameter = parameters[i];\n\n                if (parameter.HasConstraints)\n                    Read(parameter.Constraints);\n\n                if (parameter.HasCustomAttributes)\n                    Read(parameter.CustomAttributes);\n            }\n        }\n\n        static void ReadSecurityDeclarations(ISecurityDeclarationProvider provider)\n        {\n            if (provider.HasSecurityDeclarations)\n                Read(provider.SecurityDeclarations);\n        }\n\n        static void ReadCustomAttributes(ICustomAttributeProvider provider)\n        {\n            if (provider.HasCustomAttributes)\n                Read(provider.CustomAttributes);\n        }\n\n        static void ReadFields(TypeDefinition type)\n        {\n            var fields = type.Fields;\n\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var field = fields[i];\n\n                if (field.HasConstant)\n                    Read(field.Constant);\n\n                if (field.HasLayoutInfo)\n                    Read(field.Offset);\n\n                if (field.RVA > 0)\n                    Read(field.InitialValue);\n\n                if (field.HasMarshalInfo)\n                    Read(field.MarshalInfo);\n\n                ReadCustomAttributes(field);\n            }\n        }\n\n        static void ReadMethods(TypeDefinition type)\n        {\n            var methods = type.Methods;\n\n            for (int i = 0; i < methods.Count; i++)\n            {\n                var method = methods[i];\n\n                ReadGenericParameters(method);\n\n                if (method.HasParameters)\n                    ReadParameters(method);\n\n                if (method.HasOverrides)\n                    Read(method.Overrides);\n\n                if (method.IsPInvokeImpl)\n                    Read(method.PInvokeInfo);\n\n                ReadSecurityDeclarations(method);\n                ReadCustomAttributes(method);\n\n                var return_type = method.MethodReturnType;\n                if (return_type.HasConstant)\n                    Read(return_type.Constant);\n\n                if (return_type.HasMarshalInfo)\n                    Read(return_type.MarshalInfo);\n\n                ReadCustomAttributes(return_type);\n            }\n        }\n\n        static void ReadParameters(MethodDefinition method)\n        {\n            var parameters = method.Parameters;\n\n            for (int i = 0; i < parameters.Count; i++)\n            {\n                var parameter = parameters[i];\n\n                if (parameter.HasConstant)\n                    Read(parameter.Constant);\n\n                if (parameter.HasMarshalInfo)\n                    Read(parameter.MarshalInfo);\n\n                ReadCustomAttributes(parameter);\n            }\n        }\n\n        static void ReadProperties(TypeDefinition type)\n        {\n            var properties = type.Properties;\n\n            for (int i = 0; i < properties.Count; i++)\n            {\n                var property = properties[i];\n\n                Read(property.GetMethod);\n\n                if (property.HasConstant)\n                    Read(property.Constant);\n\n                ReadCustomAttributes(property);\n            }\n        }\n\n        static void ReadEvents(TypeDefinition type)\n        {\n            var events = type.Events;\n\n            for (int i = 0; i < events.Count; i++)\n            {\n                var @event = events[i];\n\n                Read(@event.AddMethod);\n\n                ReadCustomAttributes(@event);\n            }\n        }\n\n        static void Read(object collection)\n        {\n        }\n    }\n\n    sealed class DeferredModuleReader : ModuleReader\n    {\n\n        public DeferredModuleReader(Image image)\n            : base(image, ReadingMode.Deferred)\n        {\n        }\n\n        protected override void ReadModule()\n        {\n            this.module.Read(this.module, (module, reader) =>\n            {\n                ReadModuleManifest(reader);\n                return module;\n            });\n        }\n    }\n\n    sealed class MetadataReader : ByteBuffer\n    {\n\n        readonly internal Image image;\n        readonly internal ModuleDefinition module;\n        readonly internal MetadataSystem metadata;\n\n        internal IGenericContext context;\n        internal CodeReader code;\n\n        uint Position\n        {\n            get { return (uint)base.position; }\n            set { base.position = (int)value; }\n        }\n\n        public MetadataReader(ModuleDefinition module)\n            : base(module.Image.MetadataSection.Data)\n        {\n            this.image = module.Image;\n            this.module = module;\n            this.metadata = module.MetadataSystem;\n            this.code = new CodeReader(image.MetadataSection, this);\n        }\n\n        int GetCodedIndexSize(CodedIndex index)\n        {\n            return image.GetCodedIndexSize(index);\n        }\n\n        uint ReadByIndexSize(int size)\n        {\n            if (size == 4)\n                return ReadUInt32();\n            else\n                return ReadUInt16();\n        }\n\n        byte[] ReadBlob()\n        {\n            var blob_heap = image.BlobHeap;\n            if (blob_heap == null)\n            {\n                position += 2;\n                return Empty<byte>.Array;\n            }\n\n            return blob_heap.Read(ReadBlobIndex());\n        }\n\n        byte[] ReadBlob(uint signature)\n        {\n            var blob_heap = image.BlobHeap;\n            if (blob_heap == null)\n                return Empty<byte>.Array;\n\n            return blob_heap.Read(signature);\n        }\n\n        uint ReadBlobIndex()\n        {\n            var blob_heap = image.BlobHeap;\n            return ReadByIndexSize(blob_heap != null ? blob_heap.IndexSize : 2);\n        }\n\n        string ReadString()\n        {\n            return image.StringHeap.Read(ReadByIndexSize(image.StringHeap.IndexSize));\n        }\n\n        uint ReadStringIndex()\n        {\n            return ReadByIndexSize(image.StringHeap.IndexSize);\n        }\n\n        uint ReadTableIndex(Table table)\n        {\n            return ReadByIndexSize(image.GetTableIndexSize(table));\n        }\n\n        MetadataToken ReadMetadataToken(CodedIndex index)\n        {\n            return Mixin.GetMetadataToken(index, ReadByIndexSize(GetCodedIndexSize(index)));\n        }\n\n        int MoveTo(Table table)\n        {\n            var info = image.TableHeap[table];\n            if (info.Length != 0)\n                Position = info.Offset;\n\n            return (int)info.Length;\n        }\n\n        bool MoveTo(Table table, uint row)\n        {\n            var info = image.TableHeap[table];\n            var length = info.Length;\n            if (length == 0 || row > length)\n                return false;\n\n            Position = info.Offset + (info.RowSize * (row - 1));\n            return true;\n        }\n\n        public AssemblyNameDefinition ReadAssemblyNameDefinition()\n        {\n            if (MoveTo(Table.Assembly) == 0)\n                return null;\n\n            var name = new AssemblyNameDefinition();\n\n            name.HashAlgorithm = (AssemblyHashAlgorithm)ReadUInt32();\n\n            PopulateVersionAndFlags(name);\n\n            name.PublicKey = ReadBlob();\n\n            PopulateNameAndCulture(name);\n\n            return name;\n        }\n\n        public ModuleDefinition Populate(ModuleDefinition module)\n        {\n            if (MoveTo(Table.Module) == 0)\n                return module;\n\n            Advance(2); // Generation\n\n            module.Name = ReadString();\n            module.Mvid = image.GuidHeap.Read(ReadByIndexSize(image.GuidHeap.IndexSize));\n\n            return module;\n        }\n\n        void InitializeAssemblyReferences()\n        {\n            if (metadata.AssemblyReferences != null)\n                return;\n\n            int length = MoveTo(Table.AssemblyRef);\n            var references = metadata.AssemblyReferences = new AssemblyNameReference[length];\n\n            for (uint i = 0; i < length; i++)\n            {\n                var reference = new AssemblyNameReference();\n                reference.token = new MetadataToken(TokenType.AssemblyRef, i + 1);\n\n                PopulateVersionAndFlags(reference);\n\n                var key_or_token = ReadBlob();\n\n                if (reference.HasPublicKey)\n                    reference.PublicKey = key_or_token;\n                else\n                    reference.PublicKeyToken = key_or_token;\n\n                PopulateNameAndCulture(reference);\n\n                reference.Hash = ReadBlob();\n\n                references[i] = reference;\n            }\n        }\n\n        public Collection<AssemblyNameReference> ReadAssemblyReferences()\n        {\n            InitializeAssemblyReferences();\n\n            return new Collection<AssemblyNameReference>(metadata.AssemblyReferences);\n        }\n\n        public MethodDefinition ReadEntryPoint()\n        {\n            if (module.Image.EntryPointToken == 0)\n                return null;\n\n            var token = new MetadataToken(module.Image.EntryPointToken);\n            return GetMethodDefinition(token.RID);\n        }\n\n        public Collection<ModuleDefinition> ReadModules()\n        {\n            var modules = new Collection<ModuleDefinition>(1);\n            modules.Add(this.module);\n\n            int length = MoveTo(Table.File);\n            for (uint i = 1; i <= length; i++)\n            {\n                var attributes = (FileAttributes)ReadUInt32();\n                var name = ReadString();\n                ReadBlobIndex();\n\n                if (attributes != FileAttributes.ContainsMetaData)\n                    continue;\n\n                var parameters = new ReaderParameters\n                {\n                    ReadingMode = module.ReadingMode,\n                    SymbolReaderProvider = module.SymbolReaderProvider,\n                };\n\n                modules.Add(ModuleDefinition.ReadModule(\n                    GetModuleFileName(name), parameters));\n            }\n\n            return modules;\n        }\n\n        string GetModuleFileName(string name)\n        {\n            if (module.FullyQualifiedName == null)\n                throw new NotSupportedException();\n\n            var path = Path.GetDirectoryName(module.FullyQualifiedName);\n            return Path.Combine(path, name);\n        }\n\n        void InitializeModuleReferences()\n        {\n            if (metadata.ModuleReferences != null)\n                return;\n\n            int length = MoveTo(Table.ModuleRef);\n            var references = metadata.ModuleReferences = new ModuleReference[length];\n\n            for (uint i = 0; i < length; i++)\n            {\n                var reference = new ModuleReference(ReadString());\n                reference.token = new MetadataToken(TokenType.ModuleRef, i + 1);\n\n                references[i] = reference;\n            }\n        }\n\n        public Collection<ModuleReference> ReadModuleReferences()\n        {\n            InitializeModuleReferences();\n\n            return new Collection<ModuleReference>(metadata.ModuleReferences);\n        }\n\n        public bool HasFileResource()\n        {\n            int length = MoveTo(Table.File);\n            if (length == 0)\n                return false;\n\n            for (uint i = 1; i <= length; i++)\n                if (ReadFileRecord(i).Col1 == FileAttributes.ContainsNoMetaData)\n                    return true;\n\n            return false;\n        }\n\n        public Collection<Resource> ReadResources()\n        {\n            int length = MoveTo(Table.ManifestResource);\n            var resources = new Collection<Resource>(length);\n\n            for (int i = 1; i <= length; i++)\n            {\n                var offset = ReadUInt32();\n                var flags = (ManifestResourceAttributes)ReadUInt32();\n                var name = ReadString();\n                var implementation = ReadMetadataToken(CodedIndex.Implementation);\n\n                Resource resource;\n\n                if (implementation.RID == 0)\n                {\n                    resource = new EmbeddedResource(name, flags, offset, this);\n                }\n                else if (implementation.TokenType == TokenType.AssemblyRef)\n                {\n                    resource = new AssemblyLinkedResource(name, flags)\n                    {\n                        Assembly = (AssemblyNameReference)GetTypeReferenceScope(implementation),\n                    };\n                }\n                else if (implementation.TokenType == TokenType.File)\n                {\n                    var file_record = ReadFileRecord(implementation.RID);\n\n                    resource = new LinkedResource(name, flags)\n                    {\n                        File = file_record.Col2,\n                        hash = ReadBlob(file_record.Col3)\n                    };\n                }\n                else\n                    throw new NotSupportedException();\n\n                resources.Add(resource);\n            }\n\n            return resources;\n        }\n\n        Row<FileAttributes, string, uint> ReadFileRecord(uint rid)\n        {\n            var position = this.position;\n\n            if (!MoveTo(Table.File, rid))\n                throw new ArgumentException();\n\n            var record = new Row<FileAttributes, string, uint>(\n                (FileAttributes)ReadUInt32(),\n                ReadString(),\n                ReadBlobIndex());\n\n            this.position = position;\n\n            return record;\n        }\n\n        public MemoryStream GetManagedResourceStream(uint offset)\n        {\n            var rva = image.Resources.VirtualAddress;\n            var section = image.GetSectionAtVirtualAddress(rva);\n            var position = (rva - section.VirtualAddress) + offset;\n            var buffer = section.Data;\n\n            var length = buffer[position]\n                | (buffer[position + 1] << 8)\n                | (buffer[position + 2] << 16)\n                | (buffer[position + 3] << 24);\n\n            return new MemoryStream(buffer, (int)position + 4, length);\n        }\n\n        void PopulateVersionAndFlags(AssemblyNameReference name)\n        {\n            name.Version = new Version(\n                ReadUInt16(),\n                ReadUInt16(),\n                ReadUInt16(),\n                ReadUInt16());\n\n            name.Attributes = (AssemblyAttributes)ReadUInt32();\n        }\n\n        void PopulateNameAndCulture(AssemblyNameReference name)\n        {\n            name.Name = ReadString();\n            name.Culture = ReadString();\n        }\n\n        public TypeDefinitionCollection ReadTypes()\n        {\n            InitializeTypeDefinitions();\n            var mtypes = metadata.Types;\n            var type_count = mtypes.Length - metadata.NestedTypes.Count;\n            var types = new TypeDefinitionCollection(module, type_count);\n\n            for (int i = 0; i < mtypes.Length; i++)\n            {\n                var type = mtypes[i];\n                if (IsNested(type.Attributes))\n                    continue;\n\n                types.Add(type);\n            }\n\n            if (image.HasTable(Table.MethodPtr) || image.HasTable(Table.FieldPtr))\n                CompleteTypes();\n\n            return types;\n        }\n\n        void CompleteTypes()\n        {\n            var types = metadata.Types;\n\n            for (int i = 0; i < types.Length; i++)\n            {\n                var type = types[i];\n\n                InitializeCollection(type.Fields);\n                InitializeCollection(type.Methods);\n            }\n        }\n\n        void InitializeTypeDefinitions()\n        {\n            if (metadata.Types != null)\n                return;\n\n            InitializeNestedTypes();\n            InitializeFields();\n            InitializeMethods();\n\n            int length = MoveTo(Table.TypeDef);\n            var types = metadata.Types = new TypeDefinition[length];\n\n            for (uint i = 0; i < length; i++)\n            {\n                if (types[i] != null)\n                    continue;\n\n                types[i] = ReadType(i + 1);\n            }\n        }\n\n        static bool IsNested(TypeAttributes attributes)\n        {\n            switch (attributes & TypeAttributes.VisibilityMask)\n            {\n                case TypeAttributes.NestedAssembly:\n                case TypeAttributes.NestedFamANDAssem:\n                case TypeAttributes.NestedFamily:\n                case TypeAttributes.NestedFamORAssem:\n                case TypeAttributes.NestedPrivate:\n                case TypeAttributes.NestedPublic:\n                    return true;\n                default:\n                    return false;\n            }\n        }\n\n        public bool HasNestedTypes(TypeDefinition type)\n        {\n            uint[] mapping;\n            InitializeNestedTypes();\n\n            if (!metadata.TryGetNestedTypeMapping(type, out mapping))\n                return false;\n\n            return mapping.Length > 0;\n        }\n\n        public Collection<TypeDefinition> ReadNestedTypes(TypeDefinition type)\n        {\n            InitializeNestedTypes();\n            uint[] mapping;\n            if (!metadata.TryGetNestedTypeMapping(type, out mapping))\n                return new MemberDefinitionCollection<TypeDefinition>(type);\n\n            var nested_types = new MemberDefinitionCollection<TypeDefinition>(type, mapping.Length);\n\n            for (int i = 0; i < mapping.Length; i++)\n            {\n                var nested_type = GetTypeDefinition(mapping[i]);\n\n                if (nested_type != null)\n                    nested_types.Add(nested_type);\n            }\n\n            metadata.RemoveNestedTypeMapping(type);\n\n            return nested_types;\n        }\n\n        void InitializeNestedTypes()\n        {\n            if (metadata.NestedTypes != null)\n                return;\n\n            var length = MoveTo(Table.NestedClass);\n\n            metadata.NestedTypes = new Dictionary<uint, uint[]>(length);\n            metadata.ReverseNestedTypes = new Dictionary<uint, uint>(length);\n\n            if (length == 0)\n                return;\n\n            for (int i = 1; i <= length; i++)\n            {\n                var nested = ReadTableIndex(Table.TypeDef);\n                var declaring = ReadTableIndex(Table.TypeDef);\n\n                AddNestedMapping(declaring, nested);\n            }\n        }\n\n        void AddNestedMapping(uint declaring, uint nested)\n        {\n            metadata.SetNestedTypeMapping(declaring, AddMapping(metadata.NestedTypes, declaring, nested));\n            metadata.SetReverseNestedTypeMapping(nested, declaring);\n        }\n\n        static TValue[] AddMapping<TKey, TValue>(Dictionary<TKey, TValue[]> cache, TKey key, TValue value)\n        {\n            TValue[] mapped;\n            if (!cache.TryGetValue(key, out mapped))\n            {\n                mapped = new[] { value };\n                return mapped;\n            }\n\n            var new_mapped = new TValue[mapped.Length + 1];\n            Array.Copy(mapped, new_mapped, mapped.Length);\n            new_mapped[mapped.Length] = value;\n            return new_mapped;\n        }\n\n        TypeDefinition ReadType(uint rid)\n        {\n            if (!MoveTo(Table.TypeDef, rid))\n                return null;\n\n            var attributes = (TypeAttributes)ReadUInt32();\n            var name = ReadString();\n            var @namespace = ReadString();\n            var type = new TypeDefinition(@namespace, name, attributes);\n            type.token = new MetadataToken(TokenType.TypeDef, rid);\n            type.scope = module;\n            type.module = module;\n\n            metadata.AddTypeDefinition(type);\n\n            this.context = type;\n\n            type.BaseType = GetTypeDefOrRef(ReadMetadataToken(CodedIndex.TypeDefOrRef));\n\n            type.fields_range = ReadFieldsRange(rid);\n            type.methods_range = ReadMethodsRange(rid);\n\n            if (IsNested(attributes))\n                type.DeclaringType = GetNestedTypeDeclaringType(type);\n\n            return type;\n        }\n\n        TypeDefinition GetNestedTypeDeclaringType(TypeDefinition type)\n        {\n            uint declaring_rid;\n            if (!metadata.TryGetReverseNestedTypeMapping(type, out declaring_rid))\n                return null;\n\n            metadata.RemoveReverseNestedTypeMapping(type);\n            return GetTypeDefinition(declaring_rid);\n        }\n\n        Range ReadFieldsRange(uint type_index)\n        {\n            return ReadListRange(type_index, Table.TypeDef, Table.Field);\n        }\n\n        Range ReadMethodsRange(uint type_index)\n        {\n            return ReadListRange(type_index, Table.TypeDef, Table.Method);\n        }\n\n        Range ReadListRange(uint current_index, Table current, Table target)\n        {\n            var list = new Range();\n\n            list.Start = ReadTableIndex(target);\n\n            uint next_index;\n            var current_table = image.TableHeap[current];\n\n            if (current_index == current_table.Length)\n                next_index = image.TableHeap[target].Length + 1;\n            else\n            {\n                var position = Position;\n                Position += (uint)(current_table.RowSize - image.GetTableIndexSize(target));\n                next_index = ReadTableIndex(target);\n                Position = position;\n            }\n\n            list.Length = next_index - list.Start;\n\n            return list;\n        }\n\n        public Row<short, int> ReadTypeLayout(TypeDefinition type)\n        {\n            InitializeTypeLayouts();\n            Row<ushort, uint> class_layout;\n            var rid = type.token.RID;\n            if (!metadata.ClassLayouts.TryGetValue(rid, out class_layout))\n                return new Row<short, int>(Mixin.NoDataMarker, Mixin.NoDataMarker);\n\n            type.PackingSize = (short)class_layout.Col1;\n            type.ClassSize = (int)class_layout.Col2;\n\n            metadata.ClassLayouts.Remove(rid);\n\n            return new Row<short, int>((short)class_layout.Col1, (int)class_layout.Col2);\n        }\n\n        void InitializeTypeLayouts()\n        {\n            if (metadata.ClassLayouts != null)\n                return;\n\n            int length = MoveTo(Table.ClassLayout);\n\n            var class_layouts = metadata.ClassLayouts = new Dictionary<uint, Row<ushort, uint>>(length);\n\n            for (uint i = 0; i < length; i++)\n            {\n                var packing_size = ReadUInt16();\n                var class_size = ReadUInt32();\n\n                var parent = ReadTableIndex(Table.TypeDef);\n\n                class_layouts.Add(parent, new Row<ushort, uint>(packing_size, class_size));\n            }\n        }\n\n        public TypeReference GetTypeDefOrRef(MetadataToken token)\n        {\n            return (TypeReference)LookupToken(token);\n        }\n\n        public TypeDefinition GetTypeDefinition(uint rid)\n        {\n            InitializeTypeDefinitions();\n\n            var type = metadata.GetTypeDefinition(rid);\n            if (type != null)\n                return type;\n\n            return ReadTypeDefinition(rid);\n        }\n\n        TypeDefinition ReadTypeDefinition(uint rid)\n        {\n            if (!MoveTo(Table.TypeDef, rid))\n                return null;\n\n            return ReadType(rid);\n        }\n\n        void InitializeTypeReferences()\n        {\n            if (metadata.TypeReferences != null)\n                return;\n\n            metadata.TypeReferences = new TypeReference[image.GetTableLength(Table.TypeRef)];\n        }\n\n        public TypeReference GetTypeReference(string scope, string full_name)\n        {\n            InitializeTypeReferences();\n\n            var length = metadata.TypeReferences.Length;\n\n            for (uint i = 1; i <= length; i++)\n            {\n                var type = GetTypeReference(i);\n\n                if (type.FullName != full_name)\n                    continue;\n\n                if (string.IsNullOrEmpty(scope))\n                    return type;\n\n                if (type.Scope.Name == scope)\n                    return type;\n            }\n\n            return null;\n        }\n\n        TypeReference GetTypeReference(uint rid)\n        {\n            InitializeTypeReferences();\n\n            var type = metadata.GetTypeReference(rid);\n            if (type != null)\n                return type;\n\n            return ReadTypeReference(rid);\n        }\n\n        TypeReference ReadTypeReference(uint rid)\n        {\n            if (!MoveTo(Table.TypeRef, rid))\n                return null;\n\n            TypeReference declaring_type = null;\n            IMetadataScope scope;\n\n            var scope_token = ReadMetadataToken(CodedIndex.ResolutionScope);\n\n            var name = ReadString();\n            var @namespace = ReadString();\n\n            var type = new TypeReference(\n                @namespace,\n                name,\n                module,\n                null);\n\n            type.token = new MetadataToken(TokenType.TypeRef, rid);\n\n            metadata.AddTypeReference(type);\n\n            if (scope_token.TokenType == TokenType.TypeRef)\n            {\n                declaring_type = GetTypeDefOrRef(scope_token);\n\n                scope = declaring_type != null\n                    ? declaring_type.Scope\n                    : module;\n            }\n            else\n                scope = GetTypeReferenceScope(scope_token);\n\n            type.scope = scope;\n            type.DeclaringType = declaring_type;\n\n            MetadataSystem.TryProcessPrimitiveTypeReference(type);\n\n            return type;\n        }\n\n        IMetadataScope GetTypeReferenceScope(MetadataToken scope)\n        {\n            switch (scope.TokenType)\n            {\n                case TokenType.AssemblyRef:\n                    InitializeAssemblyReferences();\n                    return metadata.AssemblyReferences[(int)scope.RID - 1];\n                case TokenType.ModuleRef:\n                    InitializeModuleReferences();\n                    return metadata.ModuleReferences[(int)scope.RID - 1];\n                case TokenType.Module:\n                    return module;\n                default:\n                    throw new NotSupportedException();\n            }\n        }\n\n        public IEnumerable<TypeReference> GetTypeReferences()\n        {\n            InitializeTypeReferences();\n\n            var length = image.GetTableLength(Table.TypeRef);\n\n            var type_references = new TypeReference[length];\n\n            for (uint i = 1; i <= length; i++)\n                type_references[i - 1] = GetTypeReference(i);\n\n            return type_references;\n        }\n\n        TypeReference GetTypeSpecification(uint rid)\n        {\n            if (!MoveTo(Table.TypeSpec, rid))\n                return null;\n\n            var reader = ReadSignature(ReadBlobIndex());\n            var type = reader.ReadTypeSignature();\n            if (type.token.RID == 0)\n                type.token = new MetadataToken(TokenType.TypeSpec, rid);\n\n            return type;\n        }\n\n        SignatureReader ReadSignature(uint signature)\n        {\n            return new SignatureReader(signature, this);\n        }\n\n        public bool HasInterfaces(TypeDefinition type)\n        {\n            InitializeInterfaces();\n            MetadataToken[] mapping;\n\n            return metadata.TryGetInterfaceMapping(type, out mapping);\n        }\n\n        public Collection<TypeReference> ReadInterfaces(TypeDefinition type)\n        {\n            InitializeInterfaces();\n            MetadataToken[] mapping;\n\n            if (!metadata.TryGetInterfaceMapping(type, out mapping))\n                return new Collection<TypeReference>();\n\n            var interfaces = new Collection<TypeReference>(mapping.Length);\n\n            this.context = type;\n\n            for (int i = 0; i < mapping.Length; i++)\n                interfaces.Add(GetTypeDefOrRef(mapping[i]));\n\n            metadata.RemoveInterfaceMapping(type);\n\n            return interfaces;\n        }\n\n        void InitializeInterfaces()\n        {\n            if (metadata.Interfaces != null)\n                return;\n\n            int length = MoveTo(Table.InterfaceImpl);\n\n            metadata.Interfaces = new Dictionary<uint, MetadataToken[]>(length);\n\n            for (int i = 0; i < length; i++)\n            {\n                var type = ReadTableIndex(Table.TypeDef);\n                var @interface = ReadMetadataToken(CodedIndex.TypeDefOrRef);\n\n                AddInterfaceMapping(type, @interface);\n            }\n        }\n\n        void AddInterfaceMapping(uint type, MetadataToken @interface)\n        {\n            metadata.SetInterfaceMapping(type, AddMapping(metadata.Interfaces, type, @interface));\n        }\n\n        public Collection<FieldDefinition> ReadFields(TypeDefinition type)\n        {\n            var fields_range = type.fields_range;\n            if (fields_range.Length == 0)\n                return new MemberDefinitionCollection<FieldDefinition>(type);\n\n            var fields = new MemberDefinitionCollection<FieldDefinition>(type, (int)fields_range.Length);\n            this.context = type;\n\n            if (!MoveTo(Table.FieldPtr, fields_range.Start))\n            {\n                if (!MoveTo(Table.Field, fields_range.Start))\n                    return fields;\n\n                for (uint i = 0; i < fields_range.Length; i++)\n                    ReadField(fields_range.Start + i, fields);\n            }\n            else\n                ReadPointers(Table.FieldPtr, Table.Field, fields_range, fields, ReadField);\n\n            return fields;\n        }\n\n        void ReadField(uint field_rid, Collection<FieldDefinition> fields)\n        {\n            var attributes = (FieldAttributes)ReadUInt16();\n            var name = ReadString();\n            var signature = ReadBlobIndex();\n\n            var field = new FieldDefinition(name, attributes, ReadFieldType(signature));\n            field.token = new MetadataToken(TokenType.Field, field_rid);\n            metadata.AddFieldDefinition(field);\n\n            if (IsDeleted(field))\n                return;\n\n            fields.Add(field);\n        }\n\n        void InitializeFields()\n        {\n            if (metadata.Fields != null)\n                return;\n\n            metadata.Fields = new FieldDefinition[image.GetTableLength(Table.Field)];\n        }\n\n        TypeReference ReadFieldType(uint signature)\n        {\n            var reader = ReadSignature(signature);\n\n            const byte field_sig = 0x6;\n\n            if (reader.ReadByte() != field_sig)\n                throw new NotSupportedException();\n\n            return reader.ReadTypeSignature();\n        }\n\n        public int ReadFieldRVA(FieldDefinition field)\n        {\n            InitializeFieldRVAs();\n            var rid = field.token.RID;\n\n            RVA rva;\n            if (!metadata.FieldRVAs.TryGetValue(rid, out rva))\n                return 0;\n\n            var size = GetFieldTypeSize(field.FieldType);\n\n            if (size == 0 || rva == 0)\n                return 0;\n\n            metadata.FieldRVAs.Remove(rid);\n\n            field.InitialValue = GetFieldInitializeValue(size, rva);\n\n            return (int)rva;\n        }\n\n        byte[] GetFieldInitializeValue(int size, RVA rva)\n        {\n            var section = image.GetSectionAtVirtualAddress(rva);\n            if (section == null)\n                return Empty<byte>.Array;\n\n            var value = new byte[size];\n            Buffer.BlockCopy(section.Data, (int)(rva - section.VirtualAddress), value, 0, size);\n            return value;\n        }\n\n        static int GetFieldTypeSize(TypeReference type)\n        {\n            int size = 0;\n\n            switch (type.etype)\n            {\n                case ElementType.Boolean:\n                case ElementType.U1:\n                case ElementType.I1:\n                    size = 1;\n                    break;\n                case ElementType.U2:\n                case ElementType.I2:\n                case ElementType.Char:\n                    size = 2;\n                    break;\n                case ElementType.U4:\n                case ElementType.I4:\n                case ElementType.R4:\n                    size = 4;\n                    break;\n                case ElementType.U8:\n                case ElementType.I8:\n                case ElementType.R8:\n                    size = 8;\n                    break;\n                case ElementType.Ptr:\n                case ElementType.FnPtr:\n                    size = IntPtr.Size;\n                    break;\n                case ElementType.CModOpt:\n                case ElementType.CModReqD:\n                    return GetFieldTypeSize(((IModifierType)type).ElementType);\n                default:\n                    var field_type = Mixin.CheckedResolve(type);\n                    if (field_type.HasLayoutInfo)\n                        size = field_type.ClassSize;\n\n                    break;\n            }\n\n            return size;\n        }\n\n        void InitializeFieldRVAs()\n        {\n            if (metadata.FieldRVAs != null)\n                return;\n\n            int length = MoveTo(Table.FieldRVA);\n\n            var field_rvas = metadata.FieldRVAs = new Dictionary<uint, uint>(length);\n\n            for (int i = 0; i < length; i++)\n            {\n                var rva = ReadUInt32();\n                var field = ReadTableIndex(Table.Field);\n\n                field_rvas.Add(field, rva);\n            }\n        }\n\n        public int ReadFieldLayout(FieldDefinition field)\n        {\n            InitializeFieldLayouts();\n            var rid = field.token.RID;\n            uint offset;\n            if (!metadata.FieldLayouts.TryGetValue(rid, out offset))\n                return Mixin.NoDataMarker;\n\n            metadata.FieldLayouts.Remove(rid);\n\n            return (int)offset;\n        }\n\n        void InitializeFieldLayouts()\n        {\n            if (metadata.FieldLayouts != null)\n                return;\n\n            int length = MoveTo(Table.FieldLayout);\n\n            var field_layouts = metadata.FieldLayouts = new Dictionary<uint, uint>(length);\n\n            for (int i = 0; i < length; i++)\n            {\n                var offset = ReadUInt32();\n                var field = ReadTableIndex(Table.Field);\n\n                field_layouts.Add(field, offset);\n            }\n        }\n\n        public bool HasEvents(TypeDefinition type)\n        {\n            InitializeEvents();\n\n            Range range;\n            if (!metadata.TryGetEventsRange(type, out range))\n                return false;\n\n            return range.Length > 0;\n        }\n\n        public Collection<EventDefinition> ReadEvents(TypeDefinition type)\n        {\n            InitializeEvents();\n            Range range;\n\n            if (!metadata.TryGetEventsRange(type, out range))\n                return new MemberDefinitionCollection<EventDefinition>(type);\n\n            var events = new MemberDefinitionCollection<EventDefinition>(type, (int)range.Length);\n\n            metadata.RemoveEventsRange(type);\n\n            if (range.Length == 0)\n                return events;\n\n            this.context = type;\n\n            if (!MoveTo(Table.EventPtr, range.Start))\n            {\n                if (!MoveTo(Table.Event, range.Start))\n                    return events;\n\n                for (uint i = 0; i < range.Length; i++)\n                    ReadEvent(range.Start + i, events);\n            }\n            else\n                ReadPointers(Table.EventPtr, Table.Event, range, events, ReadEvent);\n\n            return events;\n        }\n\n        void ReadEvent(uint event_rid, Collection<EventDefinition> events)\n        {\n            var attributes = (EventAttributes)ReadUInt16();\n            var name = ReadString();\n            var event_type = GetTypeDefOrRef(ReadMetadataToken(CodedIndex.TypeDefOrRef));\n\n            var @event = new EventDefinition(name, attributes, event_type);\n            @event.token = new MetadataToken(TokenType.Event, event_rid);\n\n            if (IsDeleted(@event))\n                return;\n\n            events.Add(@event);\n        }\n\n        void InitializeEvents()\n        {\n            if (metadata.Events != null)\n                return;\n\n            int length = MoveTo(Table.EventMap);\n\n            metadata.Events = new Dictionary<uint, Range>(length);\n\n            for (uint i = 1; i <= length; i++)\n            {\n                var type_rid = ReadTableIndex(Table.TypeDef);\n                Range events_range = ReadEventsRange(i);\n                metadata.AddEventsRange(type_rid, events_range);\n            }\n        }\n\n        Range ReadEventsRange(uint rid)\n        {\n            return ReadListRange(rid, Table.EventMap, Table.Event);\n        }\n\n        public bool HasProperties(TypeDefinition type)\n        {\n            InitializeProperties();\n\n            Range range;\n            if (!metadata.TryGetPropertiesRange(type, out range))\n                return false;\n\n            return range.Length > 0;\n        }\n\n        public Collection<PropertyDefinition> ReadProperties(TypeDefinition type)\n        {\n            InitializeProperties();\n\n            Range range;\n\n            if (!metadata.TryGetPropertiesRange(type, out range))\n                return new MemberDefinitionCollection<PropertyDefinition>(type);\n\n            metadata.RemovePropertiesRange(type);\n\n            var properties = new MemberDefinitionCollection<PropertyDefinition>(type, (int)range.Length);\n\n            if (range.Length == 0)\n                return properties;\n\n            this.context = type;\n\n            if (!MoveTo(Table.PropertyPtr, range.Start))\n            {\n                if (!MoveTo(Table.Property, range.Start))\n                    return properties;\n                for (uint i = 0; i < range.Length; i++)\n                    ReadProperty(range.Start + i, properties);\n            }\n            else\n                ReadPointers(Table.PropertyPtr, Table.Property, range, properties, ReadProperty);\n\n            return properties;\n        }\n\n        void ReadProperty(uint property_rid, Collection<PropertyDefinition> properties)\n        {\n            var attributes = (PropertyAttributes)ReadUInt16();\n            var name = ReadString();\n            var signature = ReadBlobIndex();\n\n            var reader = ReadSignature(signature);\n            const byte property_signature = 0x8;\n\n            var calling_convention = reader.ReadByte();\n\n            if ((calling_convention & property_signature) == 0)\n                throw new NotSupportedException();\n\n            var has_this = (calling_convention & 0x20) != 0;\n\n            reader.ReadCompressedUInt32(); // count\n\n            var property = new PropertyDefinition(name, attributes, reader.ReadTypeSignature());\n            property.HasThis = has_this;\n            property.token = new MetadataToken(TokenType.Property, property_rid);\n\n            if (IsDeleted(property))\n                return;\n\n            properties.Add(property);\n        }\n\n        void InitializeProperties()\n        {\n            if (metadata.Properties != null)\n                return;\n\n            int length = MoveTo(Table.PropertyMap);\n\n            metadata.Properties = new Dictionary<uint, Range>(length);\n\n            for (uint i = 1; i <= length; i++)\n            {\n                var type_rid = ReadTableIndex(Table.TypeDef);\n                var properties_range = ReadPropertiesRange(i);\n                metadata.AddPropertiesRange(type_rid, properties_range);\n            }\n        }\n\n        Range ReadPropertiesRange(uint rid)\n        {\n            return ReadListRange(rid, Table.PropertyMap, Table.Property);\n        }\n\n        MethodSemanticsAttributes ReadMethodSemantics(MethodDefinition method)\n        {\n            InitializeMethodSemantics();\n            Row<MethodSemanticsAttributes, MetadataToken> row;\n            if (!metadata.Semantics.TryGetValue(method.token.RID, out row))\n                return MethodSemanticsAttributes.None;\n\n            var type = method.DeclaringType;\n\n            switch (row.Col1)\n            {\n                case MethodSemanticsAttributes.AddOn:\n                    GetEvent(type, row.Col2).add_method = method;\n                    break;\n                case MethodSemanticsAttributes.Fire:\n                    GetEvent(type, row.Col2).invoke_method = method;\n                    break;\n                case MethodSemanticsAttributes.RemoveOn:\n                    GetEvent(type, row.Col2).remove_method = method;\n                    break;\n                case MethodSemanticsAttributes.Getter:\n                    GetProperty(type, row.Col2).get_method = method;\n                    break;\n                case MethodSemanticsAttributes.Setter:\n                    GetProperty(type, row.Col2).set_method = method;\n                    break;\n                case MethodSemanticsAttributes.Other:\n                    switch (row.Col2.TokenType)\n                    {\n                        case TokenType.Event:\n                            {\n                                var @event = GetEvent(type, row.Col2);\n                                if (@event.other_methods == null)\n                                    @event.other_methods = new Collection<MethodDefinition>();\n\n                                @event.other_methods.Add(method);\n                                break;\n                            }\n                        case TokenType.Property:\n                            {\n                                var property = GetProperty(type, row.Col2);\n                                if (property.other_methods == null)\n                                    property.other_methods = new Collection<MethodDefinition>();\n\n                                property.other_methods.Add(method);\n\n                                break;\n                            }\n                        default:\n                            throw new NotSupportedException();\n                    }\n                    break;\n                default:\n                    throw new NotSupportedException();\n            }\n\n            metadata.Semantics.Remove(method.token.RID);\n\n            return row.Col1;\n        }\n\n        static EventDefinition GetEvent(TypeDefinition type, MetadataToken token)\n        {\n            if (token.TokenType != TokenType.Event)\n                throw new ArgumentException();\n\n            return GetMember(type.Events, token);\n        }\n\n        static PropertyDefinition GetProperty(TypeDefinition type, MetadataToken token)\n        {\n            if (token.TokenType != TokenType.Property)\n                throw new ArgumentException();\n\n            return GetMember(type.Properties, token);\n        }\n\n        static TMember GetMember<TMember>(Collection<TMember> members, MetadataToken token) where TMember : IMemberDefinition\n        {\n            for (int i = 0; i < members.Count; i++)\n            {\n                var member = members[i];\n                if (member.MetadataToken == token)\n                    return member;\n            }\n\n            throw new ArgumentException();\n        }\n\n        void InitializeMethodSemantics()\n        {\n            if (metadata.Semantics != null)\n                return;\n\n            int length = MoveTo(Table.MethodSemantics);\n\n            var semantics = metadata.Semantics = new Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>>(0);\n\n            for (uint i = 0; i < length; i++)\n            {\n                var attributes = (MethodSemanticsAttributes)ReadUInt16();\n                var method_rid = ReadTableIndex(Table.Method);\n                var association = ReadMetadataToken(CodedIndex.HasSemantics);\n\n                semantics[method_rid] = new Row<MethodSemanticsAttributes, MetadataToken>(attributes, association);\n            }\n        }\n\n        public PropertyDefinition ReadMethods(PropertyDefinition property)\n        {\n            ReadAllSemantics(property.DeclaringType);\n            return property;\n        }\n\n        public EventDefinition ReadMethods(EventDefinition @event)\n        {\n            ReadAllSemantics(@event.DeclaringType);\n            return @event;\n        }\n\n        public MethodSemanticsAttributes ReadAllSemantics(MethodDefinition method)\n        {\n            ReadAllSemantics(method.DeclaringType);\n\n            return method.SemanticsAttributes;\n        }\n\n        void ReadAllSemantics(TypeDefinition type)\n        {\n            var methods = type.Methods;\n            for (int i = 0; i < methods.Count; i++)\n            {\n                var method = methods[i];\n                if (method.sem_attrs_ready)\n                    continue;\n\n                method.sem_attrs = ReadMethodSemantics(method);\n                method.sem_attrs_ready = true;\n            }\n        }\n\n        Range ReadParametersRange(uint method_rid)\n        {\n            return ReadListRange(method_rid, Table.Method, Table.Param);\n        }\n\n        public Collection<MethodDefinition> ReadMethods(TypeDefinition type)\n        {\n            var methods_range = type.methods_range;\n            if (methods_range.Length == 0)\n                return new MemberDefinitionCollection<MethodDefinition>(type);\n\n            var methods = new MemberDefinitionCollection<MethodDefinition>(type, (int)methods_range.Length);\n            if (!MoveTo(Table.MethodPtr, methods_range.Start))\n            {\n                if (!MoveTo(Table.Method, methods_range.Start))\n                    return methods;\n\n                for (uint i = 0; i < methods_range.Length; i++)\n                    ReadMethod(methods_range.Start + i, methods);\n            }\n            else\n                ReadPointers(Table.MethodPtr, Table.Method, methods_range, methods, ReadMethod);\n\n            return methods;\n        }\n\n        void ReadPointers<TMember>(Table ptr, Table table, Range range, Collection<TMember> members, Action<uint, Collection<TMember>> reader)\n            where TMember : IMemberDefinition\n        {\n            for (uint i = 0; i < range.Length; i++)\n            {\n                MoveTo(ptr, range.Start + i);\n\n                var rid = ReadTableIndex(table);\n                MoveTo(table, rid);\n\n                reader(rid, members);\n            }\n        }\n\n        static bool IsDeleted(IMemberDefinition member)\n        {\n            return member.IsSpecialName && member.Name == \"_Deleted\";\n        }\n\n        void InitializeMethods()\n        {\n            if (metadata.Methods != null)\n                return;\n\n            metadata.Methods = new MethodDefinition[image.GetTableLength(Table.Method)];\n        }\n\n        void ReadMethod(uint method_rid, Collection<MethodDefinition> methods)\n        {\n            var method = new MethodDefinition();\n            method.rva = ReadUInt32();\n            method.ImplAttributes = (MethodImplAttributes)ReadUInt16();\n            method.Attributes = (MethodAttributes)ReadUInt16();\n            method.Name = ReadString();\n            method.token = new MetadataToken(TokenType.Method, method_rid);\n\n            if (IsDeleted(method))\n                return;\n\n            methods.Add(method); // attach method\n\n            var signature = ReadBlobIndex();\n            var param_range = ReadParametersRange(method_rid);\n\n            this.context = method;\n\n            ReadMethodSignature(signature, method);\n            metadata.AddMethodDefinition(method);\n\n            if (param_range.Length == 0)\n                return;\n\n            var position = base.position;\n            ReadParameters(method, param_range);\n            base.position = position;\n        }\n\n        void ReadParameters(MethodDefinition method, Range param_range)\n        {\n            if (!MoveTo(Table.ParamPtr, param_range.Start))\n            {\n                if (!MoveTo(Table.Param, param_range.Start))\n                    return;\n\n                for (uint i = 0; i < param_range.Length; i++)\n                    ReadParameter(param_range.Start + i, method);\n            }\n            else\n                ReadParameterPointers(method, param_range);\n        }\n\n        void ReadParameterPointers(MethodDefinition method, Range range)\n        {\n            for (uint i = 0; i < range.Length; i++)\n            {\n                MoveTo(Table.ParamPtr, range.Start + i);\n\n                var rid = ReadTableIndex(Table.Param);\n\n                MoveTo(Table.Param, rid);\n\n                ReadParameter(rid, method);\n            }\n        }\n\n        void ReadParameter(uint param_rid, MethodDefinition method)\n        {\n            var attributes = (ParameterAttributes)ReadUInt16();\n            var sequence = ReadUInt16();\n            var name = ReadString();\n\n            var parameter = sequence == 0\n                ? method.MethodReturnType.Parameter\n                : method.Parameters[sequence - 1];\n\n            parameter.token = new MetadataToken(TokenType.Param, param_rid);\n            parameter.Name = name;\n            parameter.Attributes = attributes;\n        }\n\n        void ReadMethodSignature(uint signature, IMethodSignature method)\n        {\n            var reader = ReadSignature(signature);\n            reader.ReadMethodSignature(method);\n        }\n\n        public PInvokeInfo ReadPInvokeInfo(MethodDefinition method)\n        {\n            InitializePInvokes();\n            Row<PInvokeAttributes, uint, uint> row;\n\n            var rid = method.token.RID;\n\n            if (!metadata.PInvokes.TryGetValue(rid, out row))\n                return null;\n\n            metadata.PInvokes.Remove(rid);\n\n            return new PInvokeInfo(\n                row.Col1,\n                image.StringHeap.Read(row.Col2),\n                module.ModuleReferences[(int)row.Col3 - 1]);\n        }\n\n        void InitializePInvokes()\n        {\n            if (metadata.PInvokes != null)\n                return;\n\n            int length = MoveTo(Table.ImplMap);\n\n            var pinvokes = metadata.PInvokes = new Dictionary<uint, Row<PInvokeAttributes, uint, uint>>(length);\n\n            for (int i = 1; i <= length; i++)\n            {\n                var attributes = (PInvokeAttributes)ReadUInt16();\n                var method = ReadMetadataToken(CodedIndex.MemberForwarded);\n                var name = ReadStringIndex();\n                var scope = ReadTableIndex(Table.File);\n\n                if (method.TokenType != TokenType.Method)\n                    continue;\n\n                pinvokes.Add(method.RID, new Row<PInvokeAttributes, uint, uint>(attributes, name, scope));\n            }\n        }\n\n        public bool HasGenericParameters(IGenericParameterProvider provider)\n        {\n            InitializeGenericParameters();\n\n            Range range;\n            if (!metadata.TryGetGenericParameterRange(provider, out range))\n                return false;\n\n            return range.Length > 0;\n        }\n\n        public Collection<GenericParameter> ReadGenericParameters(IGenericParameterProvider provider)\n        {\n            InitializeGenericParameters();\n\n            Range range;\n            if (!metadata.TryGetGenericParameterRange(provider, out range)\n                || !MoveTo(Table.GenericParam, range.Start))\n                return new GenericParameterCollection(provider);\n\n            metadata.RemoveGenericParameterRange(provider);\n\n            var generic_parameters = new GenericParameterCollection(provider, (int)range.Length);\n\n            for (uint i = 0; i < range.Length; i++)\n            {\n                ReadUInt16(); // index\n                var flags = (GenericParameterAttributes)ReadUInt16();\n                ReadMetadataToken(CodedIndex.TypeOrMethodDef);\n                var name = ReadString();\n\n                var parameter = new GenericParameter(name, provider);\n                parameter.token = new MetadataToken(TokenType.GenericParam, range.Start + i);\n                parameter.Attributes = flags;\n\n                generic_parameters.Add(parameter);\n            }\n\n            return generic_parameters;\n        }\n\n        void InitializeGenericParameters()\n        {\n            if (metadata.GenericParameters != null)\n                return;\n\n            metadata.GenericParameters = InitializeRanges(\n                Table.GenericParam, () =>\n                {\n                    Advance(4);\n                    var next = ReadMetadataToken(CodedIndex.TypeOrMethodDef);\n                    ReadStringIndex();\n                    return next;\n                });\n        }\n\n        Dictionary<MetadataToken, Range> InitializeRanges(Table table, Func<MetadataToken> get_next)\n        {\n            int length = MoveTo(table);\n            var ranges = new Dictionary<MetadataToken, Range>(length);\n\n            if (length == 0)\n                return ranges;\n\n            MetadataToken owner = MetadataToken.Zero;\n            Range range = new Range(1, 0);\n\n            for (uint i = 1; i <= length; i++)\n            {\n                var next = get_next();\n\n                if (i == 1)\n                {\n                    owner = next;\n                    range.Length++;\n                }\n                else if (next != owner)\n                {\n                    if (owner.RID != 0)\n                        ranges.Add(owner, range);\n                    range = new Range(i, 1);\n                    owner = next;\n                }\n                else\n                    range.Length++;\n            }\n\n            if (owner != MetadataToken.Zero && !ranges.ContainsKey(owner))\n                ranges.Add(owner, range);\n\n            return ranges;\n        }\n\n        public bool HasGenericConstraints(GenericParameter generic_parameter)\n        {\n            InitializeGenericConstraints();\n\n            MetadataToken[] mapping;\n            if (!metadata.TryGetGenericConstraintMapping(generic_parameter, out mapping))\n                return false;\n\n            return mapping.Length > 0;\n        }\n\n        public Collection<TypeReference> ReadGenericConstraints(GenericParameter generic_parameter)\n        {\n            InitializeGenericConstraints();\n\n            MetadataToken[] mapping;\n            if (!metadata.TryGetGenericConstraintMapping(generic_parameter, out mapping))\n                return new Collection<TypeReference>();\n\n            var constraints = new Collection<TypeReference>(mapping.Length);\n\n            this.context = (IGenericContext)generic_parameter.Owner;\n\n            for (int i = 0; i < mapping.Length; i++)\n                constraints.Add(GetTypeDefOrRef(mapping[i]));\n\n            metadata.RemoveGenericConstraintMapping(generic_parameter);\n\n            return constraints;\n        }\n\n        void InitializeGenericConstraints()\n        {\n            if (metadata.GenericConstraints != null)\n                return;\n\n            var length = MoveTo(Table.GenericParamConstraint);\n\n            metadata.GenericConstraints = new Dictionary<uint, MetadataToken[]>(length);\n\n            for (int i = 1; i <= length; i++)\n                AddGenericConstraintMapping(\n                    ReadTableIndex(Table.GenericParam),\n                    ReadMetadataToken(CodedIndex.TypeDefOrRef));\n        }\n\n        void AddGenericConstraintMapping(uint generic_parameter, MetadataToken constraint)\n        {\n            metadata.SetGenericConstraintMapping(\n                generic_parameter,\n                AddMapping(metadata.GenericConstraints, generic_parameter, constraint));\n        }\n\n        public bool HasOverrides(MethodDefinition method)\n        {\n            InitializeOverrides();\n            MetadataToken[] mapping;\n\n            if (!metadata.TryGetOverrideMapping(method, out mapping))\n                return false;\n\n            return mapping.Length > 0;\n        }\n\n        public Collection<MethodReference> ReadOverrides(MethodDefinition method)\n        {\n            InitializeOverrides();\n\n            MetadataToken[] mapping;\n            if (!metadata.TryGetOverrideMapping(method, out mapping))\n                return new Collection<MethodReference>();\n\n            var overrides = new Collection<MethodReference>(mapping.Length);\n\n            this.context = method;\n\n            for (int i = 0; i < mapping.Length; i++)\n                overrides.Add((MethodReference)LookupToken(mapping[i]));\n\n            metadata.RemoveOverrideMapping(method);\n\n            return overrides;\n        }\n\n        void InitializeOverrides()\n        {\n            if (metadata.Overrides != null)\n                return;\n\n            var length = MoveTo(Table.MethodImpl);\n\n            metadata.Overrides = new Dictionary<uint, MetadataToken[]>(length);\n\n            for (int i = 1; i <= length; i++)\n            {\n                ReadTableIndex(Table.TypeDef);\n\n                var method = ReadMetadataToken(CodedIndex.MethodDefOrRef);\n                if (method.TokenType != TokenType.Method)\n                    throw new NotSupportedException();\n\n                var @override = ReadMetadataToken(CodedIndex.MethodDefOrRef);\n\n                AddOverrideMapping(method.RID, @override);\n            }\n        }\n\n        void AddOverrideMapping(uint method_rid, MetadataToken @override)\n        {\n            metadata.SetOverrideMapping(\n                method_rid,\n                AddMapping(metadata.Overrides, method_rid, @override));\n        }\n\n        public MethodBody ReadMethodBody(MethodDefinition method)\n        {\n            return code.ReadMethodBody(method);\n        }\n\n        public CallSite ReadCallSite(MetadataToken token)\n        {\n            if (!MoveTo(Table.StandAloneSig, token.RID))\n                return null;\n\n            var signature = ReadBlobIndex();\n\n            var call_site = new CallSite();\n\n            ReadMethodSignature(signature, call_site);\n\n            call_site.MetadataToken = token;\n\n            return call_site;\n        }\n\n        public VariableDefinitionCollection ReadVariables(MetadataToken local_var_token)\n        {\n            if (!MoveTo(Table.StandAloneSig, local_var_token.RID))\n                return null;\n\n            var reader = ReadSignature(ReadBlobIndex());\n            const byte local_sig = 0x7;\n\n            if (reader.ReadByte() != local_sig)\n                throw new NotSupportedException();\n\n            var count = reader.ReadCompressedUInt32();\n            if (count == 0)\n                return null;\n\n            var variables = new VariableDefinitionCollection((int)count);\n\n            for (int i = 0; i < count; i++)\n                variables.Add(new VariableDefinition(reader.ReadTypeSignature()));\n\n            return variables;\n        }\n\n        public IMetadataTokenProvider LookupToken(MetadataToken token)\n        {\n            var rid = token.RID;\n\n            if (rid == 0)\n                return null;\n\n            IMetadataTokenProvider element;\n            var position = this.position;\n            var context = this.context;\n\n            switch (token.TokenType)\n            {\n                case TokenType.TypeDef:\n                    element = GetTypeDefinition(rid);\n                    break;\n                case TokenType.TypeRef:\n                    element = GetTypeReference(rid);\n                    break;\n                case TokenType.TypeSpec:\n                    element = GetTypeSpecification(rid);\n                    break;\n                case TokenType.Field:\n                    element = GetFieldDefinition(rid);\n                    break;\n                case TokenType.Method:\n                    element = GetMethodDefinition(rid);\n                    break;\n                case TokenType.MemberRef:\n                    element = GetMemberReference(rid);\n                    break;\n                case TokenType.MethodSpec:\n                    element = GetMethodSpecification(rid);\n                    break;\n                default:\n                    return null;\n            }\n\n            this.position = position;\n            this.context = context;\n\n            return element;\n        }\n\n        public FieldDefinition GetFieldDefinition(uint rid)\n        {\n            InitializeTypeDefinitions();\n\n            var field = metadata.GetFieldDefinition(rid);\n            if (field != null)\n                return field;\n\n            return LookupField(rid);\n        }\n\n        FieldDefinition LookupField(uint rid)\n        {\n            var type = metadata.GetFieldDeclaringType(rid);\n            if (type == null)\n                return null;\n\n            InitializeCollection(type.Fields);\n\n            return metadata.GetFieldDefinition(rid);\n        }\n\n        public MethodDefinition GetMethodDefinition(uint rid)\n        {\n            InitializeTypeDefinitions();\n\n            var method = metadata.GetMethodDefinition(rid);\n            if (method != null)\n                return method;\n\n            return LookupMethod(rid);\n        }\n\n        MethodDefinition LookupMethod(uint rid)\n        {\n            var type = metadata.GetMethodDeclaringType(rid);\n            if (type == null)\n                return null;\n\n            InitializeCollection(type.Methods);\n\n            return metadata.GetMethodDefinition(rid);\n        }\n\n        MethodSpecification GetMethodSpecification(uint rid)\n        {\n            if (!MoveTo(Table.MethodSpec, rid))\n                return null;\n\n            var element_method = (MethodReference)LookupToken(\n                ReadMetadataToken(CodedIndex.MethodDefOrRef));\n            var signature = ReadBlobIndex();\n\n            var method_spec = ReadMethodSpecSignature(signature, element_method);\n            method_spec.token = new MetadataToken(TokenType.MethodSpec, rid);\n            return method_spec;\n        }\n\n        MethodSpecification ReadMethodSpecSignature(uint signature, MethodReference method)\n        {\n            var reader = ReadSignature(signature);\n            const byte methodspec_sig = 0x0a;\n\n            var call_conv = reader.ReadByte();\n\n            if (call_conv != methodspec_sig)\n                throw new NotSupportedException();\n\n            var instance = new GenericInstanceMethod(method);\n\n            reader.ReadGenericInstanceSignature(method, instance);\n\n            return instance;\n        }\n\n        MemberReference GetMemberReference(uint rid)\n        {\n            InitializeMemberReferences();\n\n            var member = metadata.GetMemberReference(rid);\n            if (member != null)\n                return member;\n\n            member = ReadMemberReference(rid);\n            if (member != null && !member.ContainsGenericParameter)\n                metadata.AddMemberReference(member);\n            return member;\n        }\n\n        MemberReference ReadMemberReference(uint rid)\n        {\n            if (!MoveTo(Table.MemberRef, rid))\n                return null;\n\n            var token = ReadMetadataToken(CodedIndex.MemberRefParent);\n            var name = ReadString();\n            var signature = ReadBlobIndex();\n\n            MemberReference member;\n\n            switch (token.TokenType)\n            {\n                case TokenType.TypeDef:\n                case TokenType.TypeRef:\n                case TokenType.TypeSpec:\n                    member = ReadTypeMemberReference(token, name, signature);\n                    break;\n                case TokenType.Method:\n                    member = ReadMethodMemberReference(token, name, signature);\n                    break;\n                default:\n                    throw new NotSupportedException();\n            }\n\n            member.token = new MetadataToken(TokenType.MemberRef, rid);\n\n            return member;\n        }\n\n        MemberReference ReadTypeMemberReference(MetadataToken type, string name, uint signature)\n        {\n            var declaring_type = GetTypeDefOrRef(type);\n\n            if (!declaring_type.IsArray)\n                this.context = declaring_type;\n\n            var member = ReadMemberReferenceSignature(signature, declaring_type);\n            member.Name = name;\n\n            return member;\n        }\n\n        MemberReference ReadMemberReferenceSignature(uint signature, TypeReference declaring_type)\n        {\n            var reader = ReadSignature(signature);\n            const byte field_sig = 0x6;\n\n            if (reader.buffer[reader.position] == field_sig)\n            {\n                reader.position++;\n                var field = new FieldReference();\n                field.DeclaringType = declaring_type;\n                field.FieldType = reader.ReadTypeSignature();\n                return field;\n            }\n            else\n            {\n                var method = new MethodReference();\n                method.DeclaringType = declaring_type;\n                reader.ReadMethodSignature(method);\n                return method;\n            }\n        }\n\n        MemberReference ReadMethodMemberReference(MetadataToken token, string name, uint signature)\n        {\n            var method = GetMethodDefinition(token.RID);\n\n            this.context = method;\n\n            var member = ReadMemberReferenceSignature(signature, method.DeclaringType);\n            member.Name = name;\n\n            return member;\n        }\n\n        void InitializeMemberReferences()\n        {\n            if (metadata.MemberReferences != null)\n                return;\n\n            metadata.MemberReferences = new MemberReference[image.GetTableLength(Table.MemberRef)];\n        }\n\n        public IEnumerable<MemberReference> GetMemberReferences()\n        {\n            InitializeMemberReferences();\n\n            var length = image.GetTableLength(Table.MemberRef);\n\n            var type_system = module.TypeSystem;\n\n            var context = new MethodReference(string.Empty, type_system.Void);\n            context.DeclaringType = new TypeReference(string.Empty, string.Empty, module, type_system.Corlib);\n\n            var member_references = new MemberReference[length];\n\n            for (uint i = 1; i <= length; i++)\n            {\n                this.context = context;\n                member_references[i - 1] = GetMemberReference(i);\n            }\n\n            return member_references;\n        }\n\n        void InitializeConstants()\n        {\n            if (metadata.Constants != null)\n                return;\n\n            var length = MoveTo(Table.Constant);\n\n            var constants = metadata.Constants = new Dictionary<MetadataToken, Row<ElementType, uint>>(length);\n\n            for (uint i = 1; i <= length; i++)\n            {\n                var type = (ElementType)ReadUInt16();\n                var owner = ReadMetadataToken(CodedIndex.HasConstant);\n                var signature = ReadBlobIndex();\n\n                constants.Add(owner, new Row<ElementType, uint>(type, signature));\n            }\n        }\n\n        public object ReadConstant(IConstantProvider owner)\n        {\n            InitializeConstants();\n\n            Row<ElementType, uint> row;\n            if (!metadata.Constants.TryGetValue(owner.MetadataToken, out row))\n                return Mixin.NoValue;\n\n            metadata.Constants.Remove(owner.MetadataToken);\n\n            switch (row.Col1)\n            {\n                case ElementType.Class:\n                case ElementType.Object:\n                    return null;\n                case ElementType.String:\n                    return ReadConstantString(ReadBlob(row.Col2));\n                default:\n                    return ReadConstantPrimitive(row.Col1, row.Col2);\n            }\n        }\n\n        static string ReadConstantString(byte[] blob)\n        {\n            var length = blob.Length;\n            if ((length & 1) == 1)\n                length--;\n\n            return Encoding.Unicode.GetString(blob, 0, length);\n        }\n\n        object ReadConstantPrimitive(ElementType type, uint signature)\n        {\n            var reader = ReadSignature(signature);\n            return reader.ReadConstantSignature(type);\n        }\n\n        void InitializeCustomAttributes()\n        {\n            if (metadata.CustomAttributes != null)\n                return;\n\n            metadata.CustomAttributes = InitializeRanges(\n                Table.CustomAttribute, () =>\n                {\n                    var next = ReadMetadataToken(CodedIndex.HasCustomAttribute);\n                    ReadMetadataToken(CodedIndex.CustomAttributeType);\n                    ReadBlobIndex();\n                    return next;\n                });\n        }\n\n        public bool HasCustomAttributes(ICustomAttributeProvider owner)\n        {\n            InitializeCustomAttributes();\n\n            Range range;\n            if (!metadata.TryGetCustomAttributeRange(owner, out range))\n                return false;\n\n            return range.Length > 0;\n        }\n\n        public Collection<CustomAttribute> ReadCustomAttributes(ICustomAttributeProvider owner)\n        {\n            InitializeCustomAttributes();\n\n            Range range;\n            if (!metadata.TryGetCustomAttributeRange(owner, out range)\n                || !MoveTo(Table.CustomAttribute, range.Start))\n                return new Collection<CustomAttribute>();\n\n            var custom_attributes = new Collection<CustomAttribute>((int)range.Length);\n\n            for (int i = 0; i < range.Length; i++)\n            {\n                ReadMetadataToken(CodedIndex.HasCustomAttribute);\n\n                var constructor = (MethodReference)LookupToken(\n                    ReadMetadataToken(CodedIndex.CustomAttributeType));\n\n                var signature = ReadBlobIndex();\n\n                custom_attributes.Add(new CustomAttribute(signature, constructor));\n            }\n\n            metadata.RemoveCustomAttributeRange(owner);\n\n            return custom_attributes;\n        }\n\n        public byte[] ReadCustomAttributeBlob(uint signature)\n        {\n            return ReadBlob(signature);\n        }\n\n        public void ReadCustomAttributeSignature(CustomAttribute attribute)\n        {\n            var reader = ReadSignature(attribute.signature);\n\n            if (!reader.CanReadMore())\n                return;\n\n            if (reader.ReadUInt16() != 0x0001)\n                throw new InvalidOperationException();\n\n            var constructor = attribute.Constructor;\n            if (constructor.HasParameters)\n                reader.ReadCustomAttributeConstructorArguments(attribute, constructor.Parameters);\n\n            if (!reader.CanReadMore())\n                return;\n\n            var named = reader.ReadUInt16();\n\n            if (named == 0)\n                return;\n\n            reader.ReadCustomAttributeNamedArguments(named, ref attribute.fields, ref attribute.properties);\n        }\n\n        void InitializeMarshalInfos()\n        {\n            if (metadata.FieldMarshals != null)\n                return;\n\n            var length = MoveTo(Table.FieldMarshal);\n\n            var marshals = metadata.FieldMarshals = new Dictionary<MetadataToken, uint>(length);\n\n            for (int i = 0; i < length; i++)\n            {\n                var token = ReadMetadataToken(CodedIndex.HasFieldMarshal);\n                var signature = ReadBlobIndex();\n                if (token.RID == 0)\n                    continue;\n\n                marshals.Add(token, signature);\n            }\n        }\n\n        public bool HasMarshalInfo(IMarshalInfoProvider owner)\n        {\n            InitializeMarshalInfos();\n\n            return metadata.FieldMarshals.ContainsKey(owner.MetadataToken);\n        }\n\n        public MarshalInfo ReadMarshalInfo(IMarshalInfoProvider owner)\n        {\n            InitializeMarshalInfos();\n\n            uint signature;\n            if (!metadata.FieldMarshals.TryGetValue(owner.MetadataToken, out signature))\n                return null;\n\n            var reader = ReadSignature(signature);\n\n            metadata.FieldMarshals.Remove(owner.MetadataToken);\n\n            return reader.ReadMarshalInfo();\n        }\n\n        void InitializeSecurityDeclarations()\n        {\n            if (metadata.SecurityDeclarations != null)\n                return;\n\n            metadata.SecurityDeclarations = InitializeRanges(\n                Table.DeclSecurity, () =>\n                {\n                    ReadUInt16();\n                    var next = ReadMetadataToken(CodedIndex.HasDeclSecurity);\n                    ReadBlobIndex();\n                    return next;\n                });\n        }\n\n        public bool HasSecurityDeclarations(ISecurityDeclarationProvider owner)\n        {\n            InitializeSecurityDeclarations();\n\n            Range range;\n            if (!metadata.TryGetSecurityDeclarationRange(owner, out range))\n                return false;\n\n            return range.Length > 0;\n        }\n\n        public Collection<SecurityDeclaration> ReadSecurityDeclarations(ISecurityDeclarationProvider owner)\n        {\n            InitializeSecurityDeclarations();\n\n            Range range;\n            if (!metadata.TryGetSecurityDeclarationRange(owner, out range)\n                || !MoveTo(Table.DeclSecurity, range.Start))\n                return new Collection<SecurityDeclaration>();\n\n            var security_declarations = new Collection<SecurityDeclaration>((int)range.Length);\n\n            for (int i = 0; i < range.Length; i++)\n            {\n                var action = (SecurityAction)ReadUInt16();\n                ReadMetadataToken(CodedIndex.HasDeclSecurity);\n                var signature = ReadBlobIndex();\n\n                security_declarations.Add(new SecurityDeclaration(action, signature, module));\n            }\n\n            metadata.RemoveSecurityDeclarationRange(owner);\n\n            return security_declarations;\n        }\n\n        public byte[] ReadSecurityDeclarationBlob(uint signature)\n        {\n            return ReadBlob(signature);\n        }\n\n        public void ReadSecurityDeclarationSignature(SecurityDeclaration declaration)\n        {\n            var signature = declaration.signature;\n            var reader = ReadSignature(signature);\n\n            if (reader.buffer[reader.position] != '.')\n            {\n                ReadXmlSecurityDeclaration(signature, declaration);\n                return;\n            }\n\n            reader.position++;\n            var count = reader.ReadCompressedUInt32();\n            var attributes = new Collection<SecurityAttribute>((int)count);\n\n            for (int i = 0; i < count; i++)\n                attributes.Add(reader.ReadSecurityAttribute());\n\n            declaration.security_attributes = attributes;\n        }\n\n        void ReadXmlSecurityDeclaration(uint signature, SecurityDeclaration declaration)\n        {\n            var blob = ReadBlob(signature);\n            var attributes = new Collection<SecurityAttribute>(1);\n\n            var attribute = new SecurityAttribute(\n                module.TypeSystem.LookupType(\"System.Security.Permissions\", \"PermissionSetAttribute\"));\n\n            attribute.properties = new Collection<CustomAttributeNamedArgument>(1);\n            attribute.properties.Add(\n                new CustomAttributeNamedArgument(\n                    \"XML\",\n                    new CustomAttributeArgument(\n                        module.TypeSystem.String,\n                        Encoding.Unicode.GetString(blob, 0, blob.Length))));\n\n            attributes.Add(attribute);\n\n            declaration.security_attributes = attributes;\n        }\n\n        public Collection<ExportedType> ReadExportedTypes()\n        {\n            var length = MoveTo(Table.ExportedType);\n            if (length == 0)\n                return new Collection<ExportedType>();\n\n            var exported_types = new Collection<ExportedType>(length);\n\n            for (int i = 1; i <= length; i++)\n            {\n                var attributes = (TypeAttributes)ReadUInt32();\n                var identifier = ReadUInt32();\n                var name = ReadString();\n                var @namespace = ReadString();\n                var implementation = ReadMetadataToken(CodedIndex.Implementation);\n\n                ExportedType declaring_type = null;\n                IMetadataScope scope = null;\n\n                switch (implementation.TokenType)\n                {\n                    case TokenType.AssemblyRef:\n                    case TokenType.File:\n                        scope = GetExportedTypeScope(implementation);\n                        break;\n                    case TokenType.ExportedType:\n                        // FIXME: if the table is not properly sorted\n                        declaring_type = exported_types[(int)implementation.RID - 1];\n                        break;\n                }\n\n                var exported_type = new ExportedType(@namespace, name, module, scope)\n                {\n                    Attributes = attributes,\n                    Identifier = (int)identifier,\n                    DeclaringType = declaring_type,\n                };\n                exported_type.token = new MetadataToken(TokenType.ExportedType, i);\n\n                exported_types.Add(exported_type);\n            }\n\n            return exported_types;\n        }\n\n        IMetadataScope GetExportedTypeScope(MetadataToken token)\n        {\n            var position = this.position;\n            IMetadataScope scope;\n\n            switch (token.TokenType)\n            {\n                case TokenType.AssemblyRef:\n                    InitializeAssemblyReferences();\n                    scope = metadata.AssemblyReferences[(int)token.RID - 1];\n                    break;\n                case TokenType.File:\n                    InitializeModuleReferences();\n                    scope = GetModuleReferenceFromFile(token);\n                    break;\n                default:\n                    throw new NotSupportedException();\n            }\n\n            this.position = position;\n            return scope;\n        }\n\n        ModuleReference GetModuleReferenceFromFile(MetadataToken token)\n        {\n            if (!MoveTo(Table.File, token.RID))\n                return null;\n\n            ReadUInt32();\n            var file_name = ReadString();\n            var modules = module.ModuleReferences;\n\n            ModuleReference reference;\n            for (int i = 0; i < modules.Count; i++)\n            {\n                reference = modules[i];\n                if (reference.Name == file_name)\n                    return reference;\n            }\n\n            reference = new ModuleReference(file_name);\n            modules.Add(reference);\n            return reference;\n        }\n\n        static void InitializeCollection(object o)\n        {\n        }\n    }\n\n    sealed class SignatureReader : ByteBuffer\n    {\n\n        readonly MetadataReader reader;\n        readonly uint start, sig_length;\n\n        TypeSystem TypeSystem\n        {\n            get { return reader.module.TypeSystem; }\n        }\n\n        public SignatureReader(uint blob, MetadataReader reader)\n            : base(reader.buffer)\n        {\n            this.reader = reader;\n\n            MoveToBlob(blob);\n\n            this.sig_length = ReadCompressedUInt32();\n            this.start = (uint)position;\n        }\n\n        void MoveToBlob(uint blob)\n        {\n            position = (int)(reader.image.BlobHeap.Offset + blob);\n        }\n\n        MetadataToken ReadTypeTokenSignature()\n        {\n            return Mixin.GetMetadataToken(CodedIndex.TypeDefOrRef, ReadCompressedUInt32());\n        }\n\n        GenericParameter GetGenericParameter(GenericParameterType type, uint var)\n        {\n            var context = reader.context;\n            int index = (int)var;\n\n            if (context == null)\n                return GetUnboundGenericParameter(type, index);\n\n            IGenericParameterProvider provider;\n\n            switch (type)\n            {\n                case GenericParameterType.Type:\n                    provider = context.Type;\n                    break;\n                case GenericParameterType.Method:\n                    provider = context.Method;\n                    break;\n                default:\n                    throw new NotSupportedException();\n            }\n\n            if (!context.IsDefinition)\n                CheckGenericContext(provider, index);\n\n            if (index >= provider.GenericParameters.Count)\n                return GetUnboundGenericParameter(type, index);\n\n            return provider.GenericParameters[index];\n        }\n\n        GenericParameter GetUnboundGenericParameter(GenericParameterType type, int index)\n        {\n            return new GenericParameter(index, type, reader.module);\n        }\n\n        static void CheckGenericContext(IGenericParameterProvider owner, int index)\n        {\n            var owner_parameters = owner.GenericParameters;\n\n            for (int i = owner_parameters.Count; i <= index; i++)\n                owner_parameters.Add(new GenericParameter(owner));\n        }\n\n        public void ReadGenericInstanceSignature(IGenericParameterProvider provider, IGenericInstance instance)\n        {\n            var arity = ReadCompressedUInt32();\n\n            if (!provider.IsDefinition)\n                CheckGenericContext(provider, (int)arity - 1);\n\n            var instance_arguments = instance.GenericArguments;\n\n            for (int i = 0; i < arity; i++)\n                instance_arguments.Add(ReadTypeSignature());\n        }\n\n        ArrayType ReadArrayTypeSignature()\n        {\n            var array = new ArrayType(ReadTypeSignature());\n\n            var rank = ReadCompressedUInt32();\n\n            var sizes = new uint[ReadCompressedUInt32()];\n            for (int i = 0; i < sizes.Length; i++)\n                sizes[i] = ReadCompressedUInt32();\n\n            var low_bounds = new int[ReadCompressedUInt32()];\n            for (int i = 0; i < low_bounds.Length; i++)\n                low_bounds[i] = ReadCompressedInt32();\n\n            array.Dimensions.Clear();\n\n            for (int i = 0; i < rank; i++)\n            {\n                int? lower = null, upper = null;\n\n                if (i < low_bounds.Length)\n                    lower = low_bounds[i];\n\n                if (i < sizes.Length)\n                    upper = lower + (int)sizes[i] - 1;\n\n                array.Dimensions.Add(new ArrayDimension(lower, upper));\n            }\n\n            return array;\n        }\n\n        TypeReference GetTypeDefOrRef(MetadataToken token)\n        {\n            return reader.GetTypeDefOrRef(token);\n        }\n\n        public TypeReference ReadTypeSignature()\n        {\n            return ReadTypeSignature((ElementType)ReadByte());\n        }\n\n        TypeReference ReadTypeSignature(ElementType etype)\n        {\n            switch (etype)\n            {\n                case ElementType.ValueType:\n                    {\n                        var value_type = GetTypeDefOrRef(ReadTypeTokenSignature());\n                        value_type.IsValueType = true;\n                        return value_type;\n                    }\n                case ElementType.Class:\n                    return GetTypeDefOrRef(ReadTypeTokenSignature());\n                case ElementType.Ptr:\n                    return new PointerType(ReadTypeSignature());\n                case ElementType.FnPtr:\n                    {\n                        var fptr = new FunctionPointerType();\n                        ReadMethodSignature(fptr);\n                        return fptr;\n                    }\n                case ElementType.ByRef:\n                    return new ByReferenceType(ReadTypeSignature());\n                case ElementType.Pinned:\n                    return new PinnedType(ReadTypeSignature());\n                case ElementType.SzArray:\n                    return new ArrayType(ReadTypeSignature());\n                case ElementType.Array:\n                    return ReadArrayTypeSignature();\n                case ElementType.CModOpt:\n                    return new OptionalModifierType(\n                        GetTypeDefOrRef(ReadTypeTokenSignature()), ReadTypeSignature());\n                case ElementType.CModReqD:\n                    return new RequiredModifierType(\n                        GetTypeDefOrRef(ReadTypeTokenSignature()), ReadTypeSignature());\n                case ElementType.Sentinel:\n                    return new SentinelType(ReadTypeSignature());\n                case ElementType.Var:\n                    return GetGenericParameter(GenericParameterType.Type, ReadCompressedUInt32());\n                case ElementType.MVar:\n                    return GetGenericParameter(GenericParameterType.Method, ReadCompressedUInt32());\n                case ElementType.GenericInst:\n                    {\n                        var is_value_type = ReadByte() == (byte)ElementType.ValueType;\n                        var element_type = GetTypeDefOrRef(ReadTypeTokenSignature());\n                        var generic_instance = new GenericInstanceType(element_type);\n\n                        ReadGenericInstanceSignature(element_type, generic_instance);\n\n                        if (is_value_type)\n                        {\n                            generic_instance.IsValueType = true;\n                            element_type.GetElementType().IsValueType = true;\n                        }\n\n                        return generic_instance;\n                    }\n                case ElementType.Object: return TypeSystem.Object;\n                case ElementType.Void: return TypeSystem.Void;\n                case ElementType.TypedByRef: return TypeSystem.TypedReference;\n                case ElementType.I: return TypeSystem.IntPtr;\n                case ElementType.U: return TypeSystem.UIntPtr;\n                default: return GetPrimitiveType(etype);\n            }\n        }\n\n        public void ReadMethodSignature(IMethodSignature method)\n        {\n            var calling_convention = ReadByte();\n\n            const byte has_this = 0x20;\n            const byte explicit_this = 0x40;\n\n            if ((calling_convention & has_this) != 0)\n            {\n                method.HasThis = true;\n                calling_convention = (byte)(calling_convention & ~has_this);\n            }\n\n            if ((calling_convention & explicit_this) != 0)\n            {\n                method.ExplicitThis = true;\n                calling_convention = (byte)(calling_convention & ~explicit_this);\n            }\n\n            method.CallingConvention = (MethodCallingConvention)calling_convention;\n\n            var generic_context = method as MethodReference;\n            if (generic_context != null && !generic_context.DeclaringType.IsArray)\n                reader.context = generic_context;\n\n            if ((calling_convention & 0x10) != 0)\n            {\n                var arity = ReadCompressedUInt32();\n\n                if (generic_context != null && !generic_context.IsDefinition)\n                    CheckGenericContext(generic_context, (int)arity - 1);\n            }\n\n            var param_count = ReadCompressedUInt32();\n\n            method.MethodReturnType.ReturnType = ReadTypeSignature();\n\n            if (param_count == 0)\n                return;\n\n            Collection<ParameterDefinition> parameters;\n\n            var method_ref = method as MethodReference;\n            if (method_ref != null)\n                parameters = method_ref.parameters = new ParameterDefinitionCollection(method, (int)param_count);\n            else\n                parameters = method.Parameters;\n\n            for (int i = 0; i < param_count; i++)\n                parameters.Add(new ParameterDefinition(ReadTypeSignature()));\n        }\n\n        public object ReadConstantSignature(ElementType type)\n        {\n            return ReadPrimitiveValue(type);\n        }\n\n        public void ReadCustomAttributeConstructorArguments(CustomAttribute attribute, Collection<ParameterDefinition> parameters)\n        {\n            var count = parameters.Count;\n            if (count == 0)\n                return;\n\n            attribute.arguments = new Collection<CustomAttributeArgument>(count);\n\n            for (int i = 0; i < count; i++)\n                attribute.arguments.Add(\n                    ReadCustomAttributeFixedArgument(parameters[i].ParameterType));\n        }\n\n        CustomAttributeArgument ReadCustomAttributeFixedArgument(TypeReference type)\n        {\n            if (type.IsArray)\n                return ReadCustomAttributeFixedArrayArgument((ArrayType)type);\n\n            return ReadCustomAttributeElement(type);\n        }\n\n        public void ReadCustomAttributeNamedArguments(ushort count, ref Collection<CustomAttributeNamedArgument> fields, ref Collection<CustomAttributeNamedArgument> properties)\n        {\n            for (int i = 0; i < count; i++)\n                ReadCustomAttributeNamedArgument(ref fields, ref properties);\n        }\n\n        void ReadCustomAttributeNamedArgument(ref Collection<CustomAttributeNamedArgument> fields, ref Collection<CustomAttributeNamedArgument> properties)\n        {\n            var kind = ReadByte();\n            var type = ReadCustomAttributeFieldOrPropType();\n            var name = ReadUTF8String();\n\n            Collection<CustomAttributeNamedArgument> container;\n            switch (kind)\n            {\n                case 0x53:\n                    container = GetCustomAttributeNamedArgumentCollection(ref fields);\n                    break;\n                case 0x54:\n                    container = GetCustomAttributeNamedArgumentCollection(ref properties);\n                    break;\n                default:\n                    throw new NotSupportedException();\n            }\n\n            container.Add(new CustomAttributeNamedArgument(name, ReadCustomAttributeFixedArgument(type)));\n        }\n\n        static Collection<CustomAttributeNamedArgument> GetCustomAttributeNamedArgumentCollection(ref Collection<CustomAttributeNamedArgument> collection)\n        {\n            if (collection != null)\n                return collection;\n\n            return collection = new Collection<CustomAttributeNamedArgument>();\n        }\n\n        CustomAttributeArgument ReadCustomAttributeFixedArrayArgument(ArrayType type)\n        {\n            var length = ReadUInt32();\n\n            if (length == 0xffffffff)\n                return new CustomAttributeArgument(type, null);\n\n            if (length == 0)\n                return new CustomAttributeArgument(type, Empty<CustomAttributeArgument>.Array);\n\n            var arguments = new CustomAttributeArgument[length];\n            var element_type = type.ElementType;\n\n            for (int i = 0; i < length; i++)\n                arguments[i] = ReadCustomAttributeElement(element_type);\n\n            return new CustomAttributeArgument(type, arguments);\n        }\n\n        CustomAttributeArgument ReadCustomAttributeElement(TypeReference type)\n        {\n            if (type.IsArray)\n                return ReadCustomAttributeFixedArrayArgument((ArrayType)type);\n\n            return new CustomAttributeArgument(\n                type,\n                type.etype == ElementType.Object\n                    ? ReadCustomAttributeElement(ReadCustomAttributeFieldOrPropType())\n                    : ReadCustomAttributeElementValue(type));\n        }\n\n        object ReadCustomAttributeElementValue(TypeReference type)\n        {\n            var etype = type.etype;\n\n            switch (etype)\n            {\n                case ElementType.String:\n                    return ReadUTF8String();\n                case ElementType.None:\n                    if (Mixin.IsTypeOf(type,\"System\", \"Type\"))\n                        return ReadTypeReference();\n\n                    return ReadCustomAttributeEnum(type);\n                default:\n                    return ReadPrimitiveValue(etype);\n            }\n        }\n\n        object ReadPrimitiveValue(ElementType type)\n        {\n            switch (type)\n            {\n                case ElementType.Boolean:\n                    return ReadByte() == 1;\n                case ElementType.I1:\n                    return (sbyte)ReadByte();\n                case ElementType.U1:\n                    return ReadByte();\n                case ElementType.Char:\n                    return (char)ReadUInt16();\n                case ElementType.I2:\n                    return ReadInt16();\n                case ElementType.U2:\n                    return ReadUInt16();\n                case ElementType.I4:\n                    return ReadInt32();\n                case ElementType.U4:\n                    return ReadUInt32();\n                case ElementType.I8:\n                    return ReadInt64();\n                case ElementType.U8:\n                    return ReadUInt64();\n                case ElementType.R4:\n                    return ReadSingle();\n                case ElementType.R8:\n                    return ReadDouble();\n                default:\n                    throw new NotImplementedException(type.ToString());\n            }\n        }\n\n        TypeReference GetPrimitiveType(ElementType etype)\n        {\n            switch (etype)\n            {\n                case ElementType.Boolean:\n                    return TypeSystem.Boolean;\n                case ElementType.Char:\n                    return TypeSystem.Char;\n                case ElementType.I1:\n                    return TypeSystem.SByte;\n                case ElementType.U1:\n                    return TypeSystem.Byte;\n                case ElementType.I2:\n                    return TypeSystem.Int16;\n                case ElementType.U2:\n                    return TypeSystem.UInt16;\n                case ElementType.I4:\n                    return TypeSystem.Int32;\n                case ElementType.U4:\n                    return TypeSystem.UInt32;\n                case ElementType.I8:\n                    return TypeSystem.Int64;\n                case ElementType.U8:\n                    return TypeSystem.UInt64;\n                case ElementType.R4:\n                    return TypeSystem.Single;\n                case ElementType.R8:\n                    return TypeSystem.Double;\n                case ElementType.String:\n                    return TypeSystem.String;\n                default:\n                    throw new NotImplementedException(etype.ToString());\n            }\n        }\n\n        TypeReference ReadCustomAttributeFieldOrPropType()\n        {\n            var etype = (ElementType)ReadByte();\n\n            switch (etype)\n            {\n                case ElementType.Boxed:\n                    return TypeSystem.Object;\n                case ElementType.SzArray:\n                    return new ArrayType(ReadCustomAttributeFieldOrPropType());\n                case ElementType.Enum:\n                    return ReadTypeReference();\n                case ElementType.Type:\n                    return TypeSystem.LookupType(\"System\", \"Type\");\n                default:\n                    return GetPrimitiveType(etype);\n            }\n        }\n\n        public TypeReference ReadTypeReference()\n        {\n            return TypeParser.ParseType(reader.module, ReadUTF8String());\n        }\n\n        object ReadCustomAttributeEnum(TypeReference enum_type)\n        {\n            try\n            {\n                TypeDefinition type = null;\n                type = Mixin.CheckedResolve(enum_type);\n                if (!type.IsEnum)\n                    throw new ArgumentException();\n                return ReadCustomAttributeElementValue(Mixin.GetEnumUnderlyingType(type));\n            }\n            catch\n            {\n                //Resolve failed\n                string name = enum_type.FullName + \", \" + enum_type.scope.Name;\n                Type type = Type.GetType(name);\n                if (type == null || !type.IsEnum)\n                    return new ArgumentException();\n                var fields = type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);\n                Type eType = null;\n                foreach(var i in fields)\n                {\n                    eType = i.FieldType;\n                    break;\n                }\n\n                object val;\n                if(eType == typeof(int))\n                {\n                    val = ReadPrimitiveValue(ElementType.I4);\n                }\n                else if (eType == typeof(long))\n                {\n                    val = ReadPrimitiveValue(ElementType.I8);\n                }\n                else if (eType == typeof(short))\n                {\n                    val = ReadPrimitiveValue(ElementType.I2);\n                }\n                else if (eType == typeof(byte))\n                {\n                    val = ReadPrimitiveValue(ElementType.U1);\n                }\n                else if (eType == typeof(uint))\n                {\n                    val = ReadPrimitiveValue(ElementType.U4);\n                }\n                else if (eType == typeof(ulong))\n                {\n                    val = ReadPrimitiveValue(ElementType.U8);\n                }\n                else if (eType == typeof(ushort))\n                {\n                    val = ReadPrimitiveValue(ElementType.U2);\n                }\n                else\n                {\n                    val = ReadPrimitiveValue(ElementType.Void);\n                }\n\n                return Enum.ToObject(type, val);\n            }\n            \n        }\n\n        public SecurityAttribute ReadSecurityAttribute()\n        {\n            var attribute = new SecurityAttribute(ReadTypeReference());\n\n            ReadCompressedUInt32();\n\n            ReadCustomAttributeNamedArguments(\n                (ushort)ReadCompressedUInt32(),\n                ref attribute.fields,\n                ref attribute.properties);\n\n            return attribute;\n        }\n\n        public MarshalInfo ReadMarshalInfo()\n        {\n            var native = ReadNativeType();\n            switch (native)\n            {\n                case NativeType.Array:\n                    {\n                        var array = new ArrayMarshalInfo();\n                        if (CanReadMore())\n                            array.element_type = ReadNativeType();\n                        if (CanReadMore())\n                            array.size_parameter_index = (int)ReadCompressedUInt32();\n                        if (CanReadMore())\n                            array.size = (int)ReadCompressedUInt32();\n                        if (CanReadMore())\n                            array.size_parameter_multiplier = (int)ReadCompressedUInt32();\n                        return array;\n                    }\n                case NativeType.SafeArray:\n                    {\n                        var array = new SafeArrayMarshalInfo();\n                        if (CanReadMore())\n                            array.element_type = ReadVariantType();\n                        return array;\n                    }\n                case NativeType.FixedArray:\n                    {\n                        var array = new FixedArrayMarshalInfo();\n                        if (CanReadMore())\n                            array.size = (int)ReadCompressedUInt32();\n                        if (CanReadMore())\n                            array.element_type = ReadNativeType();\n                        return array;\n                    }\n                case NativeType.FixedSysString:\n                    {\n                        var sys_string = new FixedSysStringMarshalInfo();\n                        if (CanReadMore())\n                            sys_string.size = (int)ReadCompressedUInt32();\n                        return sys_string;\n                    }\n                case NativeType.CustomMarshaler:\n                    {\n                        var marshaler = new CustomMarshalInfo();\n                        var guid_value = ReadUTF8String();\n                        marshaler.guid = !string.IsNullOrEmpty(guid_value) ? new Guid(guid_value) : Guid.Empty;\n                        marshaler.unmanaged_type = ReadUTF8String();\n                        marshaler.managed_type = ReadTypeReference();\n                        marshaler.cookie = ReadUTF8String();\n                        return marshaler;\n                    }\n                default:\n                    return new MarshalInfo(native);\n            }\n        }\n\n        NativeType ReadNativeType()\n        {\n            return (NativeType)ReadByte();\n        }\n\n        VariantType ReadVariantType()\n        {\n            return (VariantType)ReadByte();\n        }\n\n        string ReadUTF8String()\n        {\n            if (buffer[position] == 0xff)\n            {\n                position++;\n                return null;\n            }\n\n            var length = (int)ReadCompressedUInt32();\n            if (length == 0)\n                return string.Empty;\n\n            var @string = Encoding.UTF8.GetString(buffer, position,\n                buffer[position + length - 1] == 0 ? length - 1 : length);\n\n            position += length;\n            return @string;\n        }\n\n        public bool CanReadMore()\n        {\n            return position - start < sig_length;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyWriter.cs",
    "content": "//\n// AssemblyWriter.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nusing Mono.Collections.Generic;\nusing Mono.Cecil.Cil;\nusing Mono.Cecil.Metadata;\nusing Mono.Cecil.PE;\n\nusing RVA = System.UInt32;\nusing RID = System.UInt32;\nusing CodedRID = System.UInt32;\nusing StringIndex = System.UInt32;\nusing BlobIndex = System.UInt32;\n\nnamespace Mono.Cecil {\n\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/BaseAssemblyResolver.cs",
    "content": "//\n// BaseAssemblyResolver.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic delegate AssemblyDefinition AssemblyResolveEventHandler (object sender, AssemblyNameReference reference);\n\n\tpublic sealed class AssemblyResolveEventArgs : EventArgs {\n\n\t\treadonly AssemblyNameReference reference;\n\n\t\tpublic AssemblyNameReference AssemblyReference {\n\t\t\tget { return reference; }\n\t\t}\n\n\t\tpublic AssemblyResolveEventArgs (AssemblyNameReference reference)\n\t\t{\n\t\t\tthis.reference = reference;\n\t\t}\n\t}\n\n\n\tpublic class AssemblyResolutionException : FileNotFoundException {\n\n\t\treadonly AssemblyNameReference reference;\n\n\t\tpublic AssemblyNameReference AssemblyReference {\n\t\t\tget { return reference; }\n\t\t}\n\n\t\tpublic AssemblyResolutionException (AssemblyNameReference reference)\n\t\t\t: base (string.Format (\"Failed to resolve assembly: '{0}'\", reference))\n\t\t{\n\t\t\tthis.reference = reference;\n\t\t}\n\n\n\t}\n\n\tpublic abstract class BaseAssemblyResolver : IAssemblyResolver {\n\n\t\tstatic readonly bool on_mono = Type.GetType (\"Mono.Runtime\") != null;\n\n\t\treadonly Collection<string> directories;\n\n\n\n\t\tpublic void AddSearchDirectory (string directory)\n\t\t{\n\t\t\tdirectories.Add (directory);\n\t\t}\n\n\t\tpublic void RemoveSearchDirectory (string directory)\n\t\t{\n\t\t\tdirectories.Remove (directory);\n\t\t}\n\n\t\tpublic string [] GetSearchDirectories ()\n\t\t{\n\t\t\tvar directories = new string [this.directories.size];\n\t\t\tArray.Copy (this.directories.items, directories, directories.Length);\n\t\t\treturn directories;\n\t\t}\n\n\t\tpublic virtual AssemblyDefinition Resolve (string fullName)\n\t\t{\n\t\t\treturn Resolve (fullName, new ReaderParameters ());\n\t\t}\n\n\t\tpublic virtual AssemblyDefinition Resolve (string fullName, ReaderParameters parameters)\n\t\t{\n\t\t\tif (fullName == null)\n\t\t\t\tthrow new ArgumentNullException (\"fullName\");\n\n\t\t\treturn Resolve (AssemblyNameReference.Parse (fullName), parameters);\n\t\t}\n\n\t\tpublic event AssemblyResolveEventHandler ResolveFailure;\n\n\t\tprotected BaseAssemblyResolver ()\n\t\t{\n\t\t\tdirectories = new Collection<string> (2) { \".\", \"bin\" };\n\t\t}\n\n\t\tAssemblyDefinition GetAssembly (string file, ReaderParameters parameters)\n\t\t{\n\t\t\tif (parameters.AssemblyResolver == null)\n\t\t\t\tparameters.AssemblyResolver = this;\n\n\t\t\treturn ModuleDefinition.ReadModule (file, parameters).Assembly;\n\t\t}\n\n\t\tpublic virtual AssemblyDefinition Resolve (AssemblyNameReference name)\n\t\t{\n\t\t\treturn Resolve (name, new ReaderParameters ());\n\t\t}\n\n\t\tpublic virtual AssemblyDefinition Resolve (AssemblyNameReference name, ReaderParameters parameters)\n\t\t{\n\t\t\tif (name == null)\n\t\t\t\tthrow new ArgumentNullException (\"name\");\n            if (parameters == null)\n\t\t\t\tparameters = new ReaderParameters ();\n\n\t\t\tvar assembly = SearchDirectory (name, directories, parameters);\n\t\t\tif (assembly != null)\n\t\t\t\treturn assembly;\n\n\n\n\t\t\tif (ResolveFailure != null) {\n\t\t\t\tassembly = ResolveFailure (this, name);\n\t\t\t\tif (assembly != null)\n\t\t\t\t\treturn assembly;\n\t\t\t}\n\n\t\t\tthrow new AssemblyResolutionException (name);\n\t\t}\n\n\t\tAssemblyDefinition SearchDirectory (AssemblyNameReference name, IEnumerable<string> directories, ReaderParameters parameters)\n\t\t{\n\t\t\tvar extensions = new [] { \".exe\", \".dll\" };\n\t\t\tforeach (var directory in directories) {\n\t\t\t\tforeach (var extension in extensions) {\n\t\t\t\t\tstring file = Path.Combine (directory, name.Name + extension);\n\t\t\t\t\tif (File.Exists (file))\n\t\t\t\t\t\treturn GetAssembly (file, parameters);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\n\t\tstatic bool IsZero (Version version)\n\t\t{\n\t\t\treturn version == null || (version.Major == 0 && version.Minor == 0 && version.Build == 0 && version.Revision == 0);\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/CallSite.cs",
    "content": "//\n// CallSite.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class CallSite : IMethodSignature {\n\n\t\treadonly MethodReference signature;\n\n\t\tpublic bool HasThis {\n\t\t\tget { return signature.HasThis; }\n\t\t\tset { signature.HasThis = value; }\n\t\t}\n\n\t\tpublic bool ExplicitThis {\n\t\t\tget { return signature.ExplicitThis; }\n\t\t\tset { signature.ExplicitThis = value; }\n\t\t}\n\n\t\tpublic MethodCallingConvention CallingConvention {\n\t\t\tget { return signature.CallingConvention; }\n\t\t\tset { signature.CallingConvention = value; }\n\t\t}\n\n\t\tpublic bool HasParameters {\n\t\t\tget { return signature.HasParameters; }\n\t\t}\n\n\t\tpublic Collection<ParameterDefinition> Parameters {\n\t\t\tget { return signature.Parameters; }\n\t\t}\n\n\t\tpublic TypeReference ReturnType {\n\t\t\tget { return signature.MethodReturnType.ReturnType; }\n\t\t\tset { signature.MethodReturnType.ReturnType = value; }\n\t\t}\n\n\t\tpublic MethodReturnType MethodReturnType {\n\t\t\tget { return signature.MethodReturnType; }\n\t\t}\n\n\t\tpublic string Name {\n\t\t\tget { return string.Empty; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic string Namespace {\n\t\t\tget { return string.Empty; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic ModuleDefinition Module {\n\t\t\tget { return ReturnType.Module; }\n\t\t}\n\n\t\tpublic IMetadataScope Scope {\n\t\t\tget { return signature.ReturnType.Scope; }\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return signature.token; }\n\t\t\tset { signature.token = value; }\n\t\t}\n\n\t\tpublic string FullName {\n\t\t\tget {\n\t\t\t\tvar signature = new StringBuilder ();\n\t\t\t\tsignature.Append (ReturnType.FullName);\n\t\t\t\tMixin.MethodSignatureFullName (this,signature);\n\t\t\t\treturn signature.ToString ();\n\t\t\t}\n\t\t}\n\n\t\tinternal CallSite ()\n\t\t{\n\t\t\tthis.signature = new MethodReference ();\n\t\t\tthis.signature.token = new MetadataToken (TokenType.Signature, 0);\n\t\t}\n\n\t\tpublic CallSite (TypeReference returnType)\n\t\t\t: this ()\n\t\t{\n\t\t\tif (returnType == null)\n\t\t\t\tthrow new ArgumentNullException (\"returnType\");\n\n\t\t\tthis.signature.ReturnType = returnType;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn FullName;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/CustomAttribute.cs",
    "content": "//\n// CustomAttribute.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic struct CustomAttributeArgument {\n\n\t\treadonly TypeReference type;\n\t\treadonly object value;\n\n\t\tpublic TypeReference Type {\n\t\t\tget { return type; }\n\t\t}\n\n\t\tpublic object Value {\n\t\t\tget { return value; }\n\t\t}\n\n\t\tpublic CustomAttributeArgument (TypeReference type, object value)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.type = type;\n\t\t\tthis.value = value;\n\t\t}\n\t}\n\n\tpublic struct CustomAttributeNamedArgument {\n\n\t\treadonly string name;\n\t\treadonly CustomAttributeArgument argument;\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t}\n\n\t\tpublic CustomAttributeArgument Argument {\n\t\t\tget { return argument; }\n\t\t}\n\n\t\tpublic CustomAttributeNamedArgument (string name, CustomAttributeArgument argument)\n\t\t{\n\t\t\tMixin.CheckName (name);\n\t\t\tthis.name = name;\n\t\t\tthis.argument = argument;\n\t\t}\n\t}\n\n\tpublic interface ICustomAttribute {\n\n\t\tTypeReference AttributeType { get; }\n\n\t\tbool HasFields { get; }\n\t\tbool HasProperties { get; }\n\t\tCollection<CustomAttributeNamedArgument> Fields { get; }\n\t\tCollection<CustomAttributeNamedArgument> Properties { get; }\n\t}\n\n\tpublic sealed class CustomAttribute : ICustomAttribute {\n\n\t\treadonly internal uint signature;\n\t\tinternal bool resolved;\n\t\tMethodReference constructor;\n\t\tbyte [] blob;\n\t\tinternal Collection<CustomAttributeArgument> arguments;\n\t\tinternal Collection<CustomAttributeNamedArgument> fields;\n\t\tinternal Collection<CustomAttributeNamedArgument> properties;\n\n\t\tpublic MethodReference Constructor {\n\t\t\tget { return constructor; }\n\t\t\tset { constructor = value; }\n\t\t}\n\n\t\tpublic TypeReference AttributeType {\n\t\t\tget { return constructor.DeclaringType; }\n\t\t}\n\n\t\tpublic bool IsResolved {\n\t\t\tget { return resolved; }\n\t\t}\n\n\t\tpublic bool HasConstructorArguments {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn !Mixin.IsNullOrEmpty (arguments);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttributeArgument> ConstructorArguments {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn arguments ?? (arguments = new Collection<CustomAttributeArgument> ());\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasFields {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn !Mixin.IsNullOrEmpty (fields);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttributeNamedArgument> Fields {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn fields ?? (fields = new Collection<CustomAttributeNamedArgument> ());\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasProperties {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn !Mixin.IsNullOrEmpty (properties);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttributeNamedArgument> Properties {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn properties ?? (properties = new Collection<CustomAttributeNamedArgument> ());\n\t\t\t}\n\t\t}\n\n\t\tinternal bool HasImage {\n\t\t\tget { return constructor != null && constructor.HasImage; }\n\t\t}\n\n\t\tinternal ModuleDefinition Module {\n\t\t\tget { return constructor.Module; }\n\t\t}\n\n\t\tinternal CustomAttribute (uint signature, MethodReference constructor)\n\t\t{\n\t\t\tthis.signature = signature;\n\t\t\tthis.constructor = constructor;\n\t\t\tthis.resolved = false;\n\t\t}\n\n\t\tpublic CustomAttribute (MethodReference constructor)\n\t\t{\n\t\t\tthis.constructor = constructor;\n\t\t\tthis.resolved = true;\n\t\t}\n\n\t\tpublic CustomAttribute (MethodReference constructor, byte [] blob)\n\t\t{\n\t\t\tthis.constructor = constructor;\n\t\t\tthis.resolved = false;\n\t\t\tthis.blob = blob;\n\t\t}\n\n\t\tpublic byte [] GetBlob ()\n\t\t{\n\t\t\tif (blob != null)\n\t\t\t\treturn blob;\n\n\t\t\tif (!HasImage)\n\t\t\t\tthrow new NotSupportedException ();\n\n\t\t\treturn Module.Read (ref blob, this, (attribute, reader) => reader.ReadCustomAttributeBlob (attribute.signature));\n\t\t}\n\n\t\tvoid Resolve ()\n\t\t{\n\t\t\tif (resolved || !HasImage)\n\t\t\t\treturn;\n\n\t\t\tModule.Read (this, (attribute, reader) => {\n\t\t\t\ttry {\n\t\t\t\t\treader.ReadCustomAttributeSignature (attribute);\n\t\t\t\t\tresolved = true;\n\t\t\t\t} catch (ResolutionException) {\n\t\t\t\t\tif (arguments != null)\n\t\t\t\t\t\targuments.Clear ();\n\t\t\t\t\tif (fields != null)\n\t\t\t\t\t\tfields.Clear ();\n\t\t\t\t\tif (properties != null)\n\t\t\t\t\t\tproperties.Clear ();\n\n\t\t\t\t\tresolved = false;\n\t\t\t\t}\n\t\t\t\treturn this;\n\t\t\t});\n\t\t}\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic static void CheckName (string name)\n\t\t{\n\t\t\tif (name == null)\n\t\t\t\tthrow new ArgumentNullException (\"name\");\n\t\t\tif (name.Length == 0)\n\t\t\t\tthrow new ArgumentException (\"Empty name\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/DefaultAssemblyResolver.cs",
    "content": "//\n// DefaultAssemblyResolver.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic class DefaultAssemblyResolver : BaseAssemblyResolver {\n\n\t\treadonly IDictionary<string, AssemblyDefinition> cache;\n\n\t\tpublic DefaultAssemblyResolver ()\n\t\t{\n\t\t\tcache = new Dictionary<string, AssemblyDefinition> (StringComparer.Ordinal);\n\t\t}\n\n\t\tpublic override AssemblyDefinition Resolve (AssemblyNameReference name)\n\t\t{\n\t\t\tif (name == null)\n\t\t\t\tthrow new ArgumentNullException (\"name\");\n\n\t\t\tAssemblyDefinition assembly;\n\t\t\tif (cache.TryGetValue (name.FullName, out assembly))\n\t\t\t\treturn assembly;\n\n\t\t\tassembly = base.Resolve (name);\n\t\t\tcache [name.FullName] = assembly;\n\n\t\t\treturn assembly;\n\t\t}\n\n\t\tprotected void RegisterAssembly (AssemblyDefinition assembly)\n\t\t{\n\t\t\tif (assembly == null)\n\t\t\t\tthrow new ArgumentNullException (\"assembly\");\n\n\t\t\tvar name = assembly.Name.FullName;\n\t\t\tif (cache.ContainsKey (name))\n\t\t\t\treturn;\n\n\t\t\tcache [name] = assembly;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/EmbeddedResource.cs",
    "content": "//\n// EmbeddedResource.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class EmbeddedResource : Resource {\n\n\t\treadonly MetadataReader reader;\n\n\t\tuint? offset;\n\t\tbyte [] data;\n\t\tStream stream;\n\n\t\tpublic override ResourceType ResourceType {\n\t\t\tget { return ResourceType.Embedded; }\n\t\t}\n\n\t\tpublic EmbeddedResource (string name, ManifestResourceAttributes attributes, byte [] data) :\n\t\t\tbase (name, attributes)\n\t\t{\n\t\t\tthis.data = data;\n\t\t}\n\n\t\tpublic EmbeddedResource (string name, ManifestResourceAttributes attributes, Stream stream) :\n\t\t\tbase (name, attributes)\n\t\t{\n\t\t\tthis.stream = stream;\n\t\t}\n\n\t\tinternal EmbeddedResource (string name, ManifestResourceAttributes attributes, uint offset, MetadataReader reader)\n\t\t\t: base (name, attributes)\n\t\t{\n\t\t\tthis.offset = offset;\n\t\t\tthis.reader = reader;\n\t\t}\n\n\t\tpublic Stream GetResourceStream ()\n\t\t{\n\t\t\tif (stream != null)\n\t\t\t\treturn stream;\n\n\t\t\tif (data != null)\n\t\t\t\treturn new MemoryStream (data);\n\n\t\t\tif (offset.HasValue)\n\t\t\t\treturn reader.GetManagedResourceStream (offset.Value);\n\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tpublic byte [] GetResourceData ()\n\t\t{\n\t\t\tif (stream != null)\n\t\t\t\treturn ReadStream (stream);\n\n\t\t\tif (data != null)\n\t\t\t\treturn data;\n\n\t\t\tif (offset.HasValue)\n\t\t\t\treturn reader.GetManagedResourceStream (offset.Value).ToArray ();\n\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tstatic byte [] ReadStream (Stream stream)\n\t\t{\n\t\t\tvar length = (int) stream.Length;\n\t\t\tvar data = new byte [length];\n\t\t\tint offset = 0, read;\n\n\t\t\twhile ((read = stream.Read (data, offset, length - offset)) > 0)\n\t\t\t\toffset += read;\n\n\t\t\treturn data;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/EventAttributes.cs",
    "content": "//\n// EventAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum EventAttributes : ushort {\n\t\tNone\t\t\t= 0x0000,\n\t\tSpecialName\t\t= 0x0200,\t// Event is special\n\t\tRTSpecialName\t= 0x0400\t // CLI provides 'special' behavior, depending upon the name of the event\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/EventDefinition.cs",
    "content": "//\n// EventDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class EventDefinition : EventReference, IMemberDefinition {\n\n\t\tushort attributes;\n\n\t\tCollection<CustomAttribute> custom_attributes;\n\n\t\tinternal MethodDefinition add_method;\n\t\tinternal MethodDefinition invoke_method;\n\t\tinternal MethodDefinition remove_method;\n\t\tinternal Collection<MethodDefinition> other_methods;\n\n\t\tpublic EventAttributes Attributes {\n\t\t\tget { return (EventAttributes) attributes; }\n\t\t\tset { attributes = (ushort) value; }\n\t\t}\n\n\t\tpublic MethodDefinition AddMethod {\n\t\t\tget {\n\t\t\t\tif (add_method != null)\n\t\t\t\t\treturn add_method;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn add_method;\n\t\t\t}\n\t\t\tset { add_method = value; }\n\t\t}\n\n\t\tpublic MethodDefinition InvokeMethod {\n\t\t\tget {\n\t\t\t\tif (invoke_method != null)\n\t\t\t\t\treturn invoke_method;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn invoke_method;\n\t\t\t}\n\t\t\tset { invoke_method = value; }\n\t\t}\n\n\t\tpublic MethodDefinition RemoveMethod {\n\t\t\tget {\n\t\t\t\tif (remove_method != null)\n\t\t\t\t\treturn remove_method;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn remove_method;\n\t\t\t}\n\t\t\tset { remove_method = value; }\n\t\t}\n\n\t\tpublic bool HasOtherMethods {\n\t\t\tget {\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods.Count > 0;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn !Mixin.IsNullOrEmpty (other_methods);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<MethodDefinition> OtherMethods {\n\t\t\tget {\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods;\n\n\t\t\t\tInitializeMethods ();\n\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods;\n\n\t\t\t\treturn other_methods = new Collection<MethodDefinition> ();\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasCustomAttributes {\n\t\t\tget {\n\t\t\t\tif (custom_attributes != null)\n\t\t\t\t\treturn custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttribute> CustomAttributes {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n\t\t}\n\n\t\t#region EventAttributes\n\n\t\tpublic bool IsSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) EventAttributes.SpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) EventAttributes.SpecialName, value); }\n\t\t}\n\n\t\tpublic bool IsRuntimeSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.RTSpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.RTSpecialName, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic new TypeDefinition DeclaringType {\n\t\t\tget { return (TypeDefinition) base.DeclaringType; }\n\t\t\tset { base.DeclaringType = value; }\n\t\t}\n\n\t\tpublic override bool IsDefinition {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic EventDefinition (string name, EventAttributes attributes, TypeReference eventType)\n\t\t\t: base (name, eventType)\n\t\t{\n\t\t\tthis.attributes = (ushort) attributes;\n\t\t\tthis.token = new MetadataToken (TokenType.Event);\n\t\t}\n\n\t\tvoid InitializeMethods ()\n\t\t{\n\t\t\tvar module = this.Module;\n\t\t\tlock (module.SyncRoot) {\n\t\t\t\tif (add_method != null\n\t\t\t\t\t|| invoke_method != null\n\t\t\t\t\t|| remove_method != null)\n\t\t\t\t\treturn;\n\n                if (!Mixin.HasImage(module))\n\t\t\t\t\treturn;\n\n\t\t\t\tmodule.Read (this, (@event, reader) => reader.ReadMethods (@event));\n\t\t\t}\n\t\t}\n\n\t\tpublic override EventDefinition Resolve ()\n\t\t{\n\t\t\treturn this;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/EventReference.cs",
    "content": "//\n// EventReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class EventReference : MemberReference {\n\n\t\tTypeReference event_type;\n\n\t\tpublic TypeReference EventType {\n\t\t\tget { return event_type; }\n\t\t\tset { event_type = value; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return event_type.FullName + \" \" + MemberFullName (); }\n\t\t}\n\n\t\tprotected EventReference (string name, TypeReference eventType)\n\t\t\t: base (name)\n\t\t{\n\t\t\tif (eventType == null)\n\t\t\t\tthrow new ArgumentNullException (\"eventType\");\n\n\t\t\tevent_type = eventType;\n\t\t}\n\n\t\tpublic abstract EventDefinition Resolve ();\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ExportedType.cs",
    "content": "//\n// ExportedType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic class ExportedType : IMetadataTokenProvider {\n\n\t\tstring @namespace;\n\t\tstring name;\n\t\tuint attributes;\n\t\tIMetadataScope scope;\n\t\tModuleDefinition module;\n\t\tint identifier;\n\t\tExportedType declaring_type;\n\t\tinternal MetadataToken token;\n\n\t\tpublic string Namespace {\n\t\t\tget { return @namespace; }\n\t\t\tset { @namespace = value; }\n\t\t}\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic TypeAttributes Attributes {\n\t\t\tget { return (TypeAttributes) attributes; }\n\t\t\tset { attributes = (uint) value; }\n\t\t}\n\n\t\tpublic IMetadataScope Scope {\n\t\t\tget {\n\t\t\t\tif (declaring_type != null)\n\t\t\t\t\treturn declaring_type.Scope;\n\n\t\t\t\treturn scope;\n\t\t\t}\n\t\t}\n\n\t\tpublic ExportedType DeclaringType {\n\t\t\tget { return declaring_type; }\n\t\t\tset { declaring_type = value; }\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return token; }\n\t\t\tset { token = value; }\n\t\t}\n\n\t\tpublic int Identifier {\n\t\t\tget { return identifier; }\n\t\t\tset { identifier = value; }\n\t\t}\n\n\t\t#region TypeAttributes\n\n\t\tpublic bool IsNotPublic {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); }\n\t\t}\n\n\t\tpublic bool IsPublic {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); }\n\t\t}\n\n\t\tpublic bool IsNestedPublic {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); }\n\t\t}\n\n\t\tpublic bool IsNestedPrivate {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); }\n\t\t}\n\n\t\tpublic bool IsNestedFamily {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); }\n\t\t}\n\n\t\tpublic bool IsNestedAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); }\n\t\t}\n\n\t\tpublic bool IsNestedFamilyAndAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); }\n\t\t}\n\n\t\tpublic bool IsNestedFamilyOrAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); }\n\t\t}\n\n\t\tpublic bool IsAutoLayout {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); }\n\t\t}\n\n\t\tpublic bool IsSequentialLayout {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); }\n\t\t}\n\n\t\tpublic bool IsExplicitLayout {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); }\n\t\t}\n\n\t\tpublic bool IsClass {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); }\n\t\t}\n\n\t\tpublic bool IsInterface {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); }\n\t\t}\n\n\t\tpublic bool IsAbstract {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.Abstract); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.Abstract, value); }\n\t\t}\n\n\t\tpublic bool IsSealed {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.Sealed); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.Sealed, value); }\n\t\t}\n\n\t\tpublic bool IsSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.SpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.SpecialName, value); }\n\t\t}\n\n\t\tpublic bool IsImport {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.Import); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.Import, value); }\n\t\t}\n\n\t\tpublic bool IsSerializable {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.Serializable); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.Serializable, value); }\n\t\t}\n\n\t\tpublic bool IsAnsiClass {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); }\n\t\t}\n\n\t\tpublic bool IsUnicodeClass {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); }\n\t\t}\n\n\t\tpublic bool IsAutoClass {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); }\n\t\t}\n\n\t\tpublic bool IsBeforeFieldInit {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.BeforeFieldInit); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.BeforeFieldInit, value); }\n\t\t}\n\n\t\tpublic bool IsRuntimeSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.RTSpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.RTSpecialName, value); }\n\t\t}\n\n\t\tpublic bool HasSecurity {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.HasSecurity); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.HasSecurity, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic bool IsForwarder {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.Forwarder); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.Forwarder, value); }\n\t\t}\n\n\t\tpublic string FullName {\n\t\t\tget {\n\t\t\t\tif (declaring_type != null)\n\t\t\t\t\treturn declaring_type.FullName + \"/\" + name;\n\n\t\t\t\tif (string.IsNullOrEmpty (@namespace))\n\t\t\t\t\treturn name;\n\n\t\t\t\treturn @namespace + \".\" + name;\n\t\t\t}\n\t\t}\n\n\t\tpublic ExportedType (string @namespace, string name, ModuleDefinition module, IMetadataScope scope)\n\t\t{\n\t\t\tthis.@namespace = @namespace;\n\t\t\tthis.name = name;\n\t\t\tthis.scope = scope;\n\t\t\tthis.module = module;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn FullName;\n\t\t}\n\n\t\tpublic TypeDefinition Resolve ()\n\t\t{\n\t\t\treturn module.Resolve (CreateReference ());\n\t\t}\n\n\t\tinternal TypeReference CreateReference ()\n\t\t{\n\t\t\treturn new TypeReference (@namespace, name, module, scope) {\n\t\t\t\tDeclaringType = declaring_type != null ? declaring_type.CreateReference () : null,\n\t\t\t};\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/FieldAttributes.cs",
    "content": "//\n// FieldAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum FieldAttributes : ushort {\n\t\tFieldAccessMask\t\t= 0x0007,\n\t\tCompilerControlled\t= 0x0000,\t// Member not referenceable\n\t\tPrivate\t\t\t\t= 0x0001,\t// Accessible only by the parent type\n\t\tFamANDAssem\t\t\t= 0x0002,\t// Accessible by sub-types only in this assembly\n\t\tAssembly\t\t\t= 0x0003,\t// Accessible by anyone in the Assembly\n\t\tFamily\t\t\t\t= 0x0004,\t// Accessible only by type and sub-types\n\t\tFamORAssem\t\t\t= 0x0005,\t// Accessible by sub-types anywhere, plus anyone in the assembly\n\t\tPublic\t\t\t\t= 0x0006,\t// Accessible by anyone who has visibility to this scope field contract attributes\n\n\t\tStatic\t\t\t\t= 0x0010,\t// Defined on type, else per instance\n\t\tInitOnly\t\t\t= 0x0020,\t// Field may only be initialized, not written after init\n\t\tLiteral\t\t\t\t= 0x0040,\t// Value is compile time constant\n\t\tNotSerialized\t\t= 0x0080,\t// Field does not have to be serialized when type is remoted\n\t\tSpecialName\t\t\t= 0x0200,\t// Field is special\n\n\t\t// Interop Attributes\n\t\tPInvokeImpl\t\t\t= 0x2000,\t// Implementation is forwarded through PInvoke\n\n\t\t// Additional flags\n\t\tRTSpecialName\t\t= 0x0400,\t// CLI provides 'special' behavior, depending upon the name of the field\n\t\tHasFieldMarshal\t\t= 0x1000,\t// Field has marshalling information\n\t\tHasDefault\t\t\t= 0x8000,\t// Field has default\n\t\tHasFieldRVA\t\t\t= 0x0100\t // Field has RVA\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/FieldDefinition.cs",
    "content": "//\n// FieldDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class FieldDefinition : FieldReference, IMemberDefinition, IConstantProvider, IMarshalInfoProvider {\n\n\t\tushort attributes;\n\t\tCollection<CustomAttribute> custom_attributes;\n\n\t\tint offset = Mixin.NotResolvedMarker;\n\n\t\tinternal int rva = Mixin.NotResolvedMarker;\n\t\tbyte [] initial_value;\n\n\t\tobject constant = Mixin.NotResolved;\n\n\t\tMarshalInfo marshal_info;\n\n\t\tvoid ResolveLayout ()\n\t\t{\n\t\t\tif (offset != Mixin.NotResolvedMarker)\n\t\t\t\treturn;\n\n\t\t\tif (!HasImage) {\n\t\t\t\toffset = Mixin.NoDataMarker;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\toffset = Module.Read (this, (field, reader) => reader.ReadFieldLayout (field));\n\t\t}\n\n\t\tpublic bool HasLayoutInfo {\n\t\t\tget {\n\t\t\t\tif (offset >= 0)\n\t\t\t\t\treturn true;\n\n\t\t\t\tResolveLayout ();\n\n\t\t\t\treturn offset >= 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic int Offset {\n\t\t\tget {\n\t\t\t\tif (offset >= 0)\n\t\t\t\t\treturn offset;\n\n\t\t\t\tResolveLayout ();\n\n\t\t\t\treturn offset >= 0 ? offset : -1;\n\t\t\t}\n\t\t\tset { offset = value; }\n\t\t}\n\n\t\tvoid ResolveRVA ()\n\t\t{\n\t\t\tif (rva != Mixin.NotResolvedMarker)\n\t\t\t\treturn;\n\n\t\t\tif (!HasImage)\n\t\t\t\treturn;\n\n\t\t\trva = Module.Read (this, (field, reader) => reader.ReadFieldRVA (field));\n\t\t}\n\n\t\tpublic int RVA {\n\t\t\tget {\n\t\t\t\tif (rva > 0)\n\t\t\t\t\treturn rva;\n\n\t\t\t\tResolveRVA ();\n\n\t\t\t\treturn rva > 0 ? rva : 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic byte [] InitialValue {\n\t\t\tget {\n\t\t\t\tif (initial_value != null)\n\t\t\t\t\treturn initial_value;\n\n\t\t\t\tResolveRVA ();\n\n\t\t\t\tif (initial_value == null)\n\t\t\t\t\tinitial_value = Empty<byte>.Array;\n\n\t\t\t\treturn initial_value;\n\t\t\t}\n\t\t\tset { initial_value = value; }\n\t\t}\n\n\t\tpublic FieldAttributes Attributes {\n\t\t\tget { return (FieldAttributes) attributes; }\n\t\t\tset { attributes = (ushort) value; }\n\t\t}\n\n\t\tpublic bool HasConstant {\n\t\t\tget {\n                Mixin.ResolveConstant(this, ref constant, Module);\n\n\t\t\t\treturn constant != Mixin.NoValue;\n\t\t\t}\n\t\t\tset { if (!value) constant = Mixin.NoValue; }\n\t\t}\n\n\t\tpublic object Constant {\n\t\t\tget { return HasConstant ? constant : null;\t}\n\t\t\tset { constant = value; }\n\t\t}\n\n\t\tpublic bool HasCustomAttributes {\n\t\t\tget {\n\t\t\t\tif (custom_attributes != null)\n\t\t\t\t\treturn custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttribute> CustomAttributes {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n\t\t}\n\n\t\tpublic bool HasMarshalInfo {\n\t\t\tget {\n\t\t\t\tif (marshal_info != null)\n\t\t\t\t\treturn true;\n\n                return Mixin.GetHasMarshalInfo(this, Module);\n\t\t\t}\n\t\t}\n\n\t\tpublic MarshalInfo MarshalInfo {\n            get { return marshal_info ?? (Mixin.GetMarshalInfo(this, ref marshal_info, Module)); }\n\t\t\tset { marshal_info = value; }\n\t\t}\n\n\t\t#region FieldAttributes\n\n\t\tpublic bool IsCompilerControlled {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled, value); }\n\t\t}\n\n\t\tpublic bool IsPrivate {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private, value); }\n\t\t}\n\n\t\tpublic bool IsFamilyAndAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem, value); }\n\t\t}\n\n\t\tpublic bool IsAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly, value); }\n\t\t}\n\n\t\tpublic bool IsFamily {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family, value); }\n\t\t}\n\n\t\tpublic bool IsFamilyOrAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem, value); }\n\t\t}\n\n\t\tpublic bool IsPublic {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public, value); }\n\t\t}\n\n\t\tpublic bool IsStatic {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.Static); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.Static, value); }\n\t\t}\n\n\t\tpublic bool IsInitOnly {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.InitOnly); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.InitOnly, value); }\n\t\t}\n\n\t\tpublic bool IsLiteral {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.Literal); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.Literal, value); }\n\t\t}\n\n\t\tpublic bool IsNotSerialized {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.NotSerialized); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.NotSerialized, value); }\n\t\t}\n\n\t\tpublic bool IsSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.SpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.SpecialName, value); }\n\t\t}\n\n\t\tpublic bool IsPInvokeImpl {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.PInvokeImpl); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.PInvokeImpl, value); }\n\t\t}\n\n\t\tpublic bool IsRuntimeSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.RTSpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.RTSpecialName, value); }\n\t\t}\n\n\t\tpublic bool HasDefault {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.HasDefault); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.HasDefault, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic override bool IsDefinition {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic new TypeDefinition DeclaringType {\n\t\t\tget { return (TypeDefinition) base.DeclaringType; }\n\t\t\tset { base.DeclaringType = value; }\n\t\t}\n\n\t\tpublic FieldDefinition (string name, FieldAttributes attributes, TypeReference fieldType)\n\t\t\t: base (name, fieldType)\n\t\t{\n\t\t\tthis.attributes = (ushort) attributes;\n\t\t}\n\n\t\tpublic override FieldDefinition Resolve ()\n\t\t{\n\t\t\treturn this;\n\t\t}\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic const int NotResolvedMarker = -2;\n\t\tpublic const int NoDataMarker = -1;\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/FieldReference.cs",
    "content": "//\n// FieldReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic class FieldReference : MemberReference {\n\n\t\tTypeReference field_type;\n\n\t\tpublic TypeReference FieldType {\n\t\t\tget { return field_type; }\n\t\t\tset { field_type = value; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return field_type.FullName + \" \" + MemberFullName (); }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return field_type.ContainsGenericParameter || base.ContainsGenericParameter; }\n\t\t}\n\n\t\tinternal FieldReference ()\n\t\t{\n\t\t\tthis.token = new MetadataToken (TokenType.MemberRef);\n\t\t}\n\n\t\tpublic FieldReference (string name, TypeReference fieldType)\n\t\t\t: base (name)\n\t\t{\n\t\t\tif (fieldType == null)\n\t\t\t\tthrow new ArgumentNullException (\"fieldType\");\n\n\t\t\tthis.field_type = fieldType;\n\t\t\tthis.token = new MetadataToken (TokenType.MemberRef);\n\t\t}\n\n\t\tpublic FieldReference (string name, TypeReference fieldType, TypeReference declaringType)\n\t\t\t: this (name, fieldType)\n\t\t{\n\t\t\tif (declaringType == null)\n\t\t\t\tthrow new ArgumentNullException(\"declaringType\");\n\n\t\t\tthis.DeclaringType = declaringType;\n\t\t}\n\n\t\tpublic virtual FieldDefinition Resolve ()\n\t\t{\n\t\t\tvar module = this.Module;\n\t\t\tif (module == null)\n\t\t\t\tthrow new NotSupportedException ();\n\n\t\t\treturn module.Resolve (this);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/FileAttributes.cs",
    "content": "//\n// FileAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tenum FileAttributes : uint {\n\t\tContainsMetaData\t= 0x0000,\t// This is not a resource file\n\t\tContainsNoMetaData  = 0x0001,\t// This is a resource file or other non-metadata-containing file\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/FunctionPointerType.cs",
    "content": "//\n// FunctionPointerType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\nusing Mono.Collections.Generic;\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class FunctionPointerType : TypeSpecification, IMethodSignature {\n\n\t\treadonly MethodReference function;\n\n\t\tpublic bool HasThis {\n\t\t\tget { return function.HasThis; }\n\t\t\tset { function.HasThis = value; }\n\t\t}\n\n\t\tpublic bool ExplicitThis {\n\t\t\tget { return function.ExplicitThis; }\n\t\t\tset { function.ExplicitThis = value; }\n\t\t}\n\n\t\tpublic MethodCallingConvention CallingConvention {\n\t\t\tget { return function.CallingConvention; }\n\t\t\tset { function.CallingConvention = value; }\n\t\t}\n\n\t\tpublic bool HasParameters {\n\t\t\tget { return function.HasParameters; }\n\t\t}\n\n\t\tpublic Collection<ParameterDefinition> Parameters {\n\t\t\tget { return function.Parameters; }\n\t\t}\n\n\t\tpublic TypeReference ReturnType {\n\t\t\tget { return function.MethodReturnType.ReturnType; }\n\t\t\tset { function.MethodReturnType.ReturnType = value; }\n\t\t}\n\n\t\tpublic MethodReturnType MethodReturnType {\n\t\t\tget { return function.MethodReturnType; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return function.Name; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override string Namespace {\n\t\t\tget { return string.Empty; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override ModuleDefinition Module {\n\t\t\tget { return ReturnType.Module; }\n\t\t}\n\n\t\tpublic override IMetadataScope Scope {\n\t\t\tget { return function.ReturnType.Scope; }\n\t\t}\n\n\t\tpublic override bool IsFunctionPointer {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return function.ContainsGenericParameter; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget {\n\t\t\t\tvar signature = new StringBuilder ();\n\t\t\t\tsignature.Append (function.Name);\n\t\t\t\tsignature.Append (\" \");\n\t\t\t\tsignature.Append (function.ReturnType.FullName);\n\t\t\t\tsignature.Append (\" *\");\n\t\t\t\tMixin.MethodSignatureFullName (this,signature);\n\t\t\t\treturn signature.ToString ();\n\t\t\t}\n\t\t}\n\n\t\tpublic FunctionPointerType ()\n\t\t\t: base (null)\n\t\t{\n\t\t\tthis.function = new MethodReference ();\n\t\t\tthis.function.Name = \"method\";\n\t\t\tthis.etype = MD.ElementType.FnPtr;\n\t\t}\n\n\t\tpublic override TypeDefinition Resolve ()\n\t\t{\n\t\t\treturn null;\n\t\t}\n\n\t\tpublic override TypeReference GetElementType ()\n\t\t{\n\t\t\treturn this;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/GenericInstanceMethod.cs",
    "content": "//\n// GenericInstanceMethod.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class GenericInstanceMethod : MethodSpecification, IGenericInstance, IGenericContext\n    {\n\n        Collection<TypeReference> arguments;\n\n        public bool HasGenericArguments\n        {\n            get { return !Mixin.IsNullOrEmpty(arguments); }\n        }\n\n        public Collection<TypeReference> GenericArguments\n        {\n            get { return arguments ?? (arguments = new Collection<TypeReference>()); }\n        }\n\n        public override bool IsGenericInstance\n        {\n            get { return true; }\n        }\n\n        IGenericParameterProvider IGenericContext.Method\n        {\n            get { return ElementMethod; }\n        }\n\n        IGenericParameterProvider IGenericContext.Type\n        {\n            get { return ElementMethod.DeclaringType; }\n        }\n\n        internal override bool ContainsGenericParameter\n        {\n            get { return Mixin.ContainsGenericParameter(this) || base.ContainsGenericParameter; }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                var signature = new StringBuilder();\n                var method = this.ElementMethod;\n                signature.Append(method.ReturnType.FullName)\n                    .Append(\" \")\n                    .Append(method.DeclaringType.FullName)\n                    .Append(\"::\")\n                    .Append(method.Name);\n                Mixin.GenericInstanceFullName(this, signature);\n                Mixin.MethodSignatureFullName(this, signature);\n                return signature.ToString();\n\n            }\n        }\n\n        public GenericInstanceMethod(MethodReference method)\n            : base(method)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/GenericInstanceType.cs",
    "content": "//\n// GenericInstanceType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class GenericInstanceType : TypeSpecification, IGenericInstance, IGenericContext\n    {\n\n        Collection<TypeReference> arguments;\n\n        public bool HasGenericArguments\n        {\n            get { return !Mixin.IsNullOrEmpty(arguments); }\n        }\n\n        public Collection<TypeReference> GenericArguments\n        {\n            get { return arguments ?? (arguments = new Collection<TypeReference>()); }\n        }\n\n        public override TypeReference DeclaringType\n        {\n            get { return ElementType.DeclaringType; }\n            set { throw new NotSupportedException(); }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                var name = new StringBuilder();\n                name.Append(base.FullName);\n                Mixin.GenericInstanceFullName(this, name);\n                return name.ToString();\n            }\n        }\n\n        public override bool IsGenericInstance\n        {\n            get { return true; }\n        }\n\n        internal override bool ContainsGenericParameter\n        {\n            get { return Mixin.ContainsGenericParameter(this) || base.ContainsGenericParameter; }\n        }\n\n        IGenericParameterProvider IGenericContext.Type\n        {\n            get { return ElementType; }\n        }\n\n        public GenericInstanceType(TypeReference type)\n            : base(type)\n        {\n            base.IsValueType = type.IsValueType;\n            this.etype = MD.ElementType.GenericInst;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/GenericParameter.cs",
    "content": "//\n// GenericParameter.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class GenericParameter : TypeReference, ICustomAttributeProvider {\n\n\t\tinternal int position;\n\t\tinternal GenericParameterType type;\n\t\tinternal IGenericParameterProvider owner;\n\n\t\tushort attributes;\n\t\tCollection<TypeReference> constraints;\n\t\tCollection<CustomAttribute> custom_attributes;\n\n\t\tpublic GenericParameterAttributes Attributes {\n\t\t\tget { return (GenericParameterAttributes) attributes; }\n\t\t\tset { attributes = (ushort) value; }\n\t\t}\n\n\t\tpublic int Position {\n\t\t\tget { return position; }\n\t\t}\n\n\t\tpublic GenericParameterType Type {\n\t\t\tget { return type; }\n\t\t}\n\n\t\tpublic IGenericParameterProvider Owner {\n\t\t\tget { return owner; }\n\t\t}\n\n\t\tpublic bool HasConstraints {\n\t\t\tget {\n\t\t\t\tif (constraints != null)\n\t\t\t\t\treturn constraints.Count > 0;\n\n\t\t\t\tif (HasImage)\n\t\t\t\t\treturn Module.Read (this, (generic_parameter, reader) => reader.HasGenericConstraints (generic_parameter));\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<TypeReference> Constraints {\n\t\t\tget {\n\t\t\t\tif (constraints != null)\n\t\t\t\t\treturn constraints;\n\n\t\t\t\tif (HasImage)\n\t\t\t\t\treturn Module.Read (ref constraints, this, (generic_parameter, reader) => reader.ReadGenericConstraints (generic_parameter));\n\n\t\t\t\treturn constraints = new Collection<TypeReference> ();\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasCustomAttributes {\n\t\t\tget {\n\t\t\t\tif (custom_attributes != null)\n\t\t\t\t\treturn custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttribute> CustomAttributes {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n\t\t}\n\n\t\tpublic override IMetadataScope Scope {\n\t\t\tget {\n\t\t\t\tif (owner == null)\n\t\t\t\t\treturn null;\n\n\t\t\t\treturn owner.GenericParameterType == GenericParameterType.Method\n\t\t\t\t\t? ((MethodReference) owner).DeclaringType.Scope\n\t\t\t\t\t: ((TypeReference) owner).Scope;\n\t\t\t}\n\t\t}\n\n\t\tpublic override ModuleDefinition Module {\n\t\t\tget { return module ?? owner.Module; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget {\n\t\t\t\tif (!string.IsNullOrEmpty (base.Name))\n\t\t\t\t\treturn base.Name;\n\n\t\t\t\treturn base.Name = (type == GenericParameterType.Method ? \"!!\" : \"!\") + position;\n\t\t\t}\n\t\t}\n\n\t\tpublic override string Namespace {\n\t\t\tget { return string.Empty; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return Name; }\n\t\t}\n\n\t\tpublic override bool IsGenericParameter {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic override MetadataType MetadataType {\n\t\t\tget { return (MetadataType) etype; }\n\t\t}\n\n\t\t#region GenericParameterAttributes\n\n\t\tpublic bool IsNonVariant {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.NonVariant); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.NonVariant, value); }\n\t\t}\n\n\t\tpublic bool IsCovariant {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Covariant); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Covariant, value); }\n\t\t}\n\n\t\tpublic bool IsContravariant {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Contravariant); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Contravariant, value); }\n\t\t}\n\n\t\tpublic bool HasReferenceTypeConstraint {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) GenericParameterAttributes.ReferenceTypeConstraint); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) GenericParameterAttributes.ReferenceTypeConstraint, value); }\n\t\t}\n\n\t\tpublic bool HasNotNullableValueTypeConstraint {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) GenericParameterAttributes.NotNullableValueTypeConstraint); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) GenericParameterAttributes.NotNullableValueTypeConstraint, value); }\n\t\t}\n\n\t\tpublic bool HasDefaultConstructorConstraint {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) GenericParameterAttributes.DefaultConstructorConstraint); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) GenericParameterAttributes.DefaultConstructorConstraint, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic GenericParameter (IGenericParameterProvider owner)\n\t\t\t: this (string.Empty, owner)\n\t\t{\n\t\t}\n\n\t\tpublic GenericParameter (string name, IGenericParameterProvider owner)\n\t\t\t: base (string.Empty, name)\n\t\t{\n\t\t\tif (owner == null)\n\t\t\t\tthrow new ArgumentNullException ();\n\n\t\t\tthis.position = -1;\n\t\t\tthis.owner = owner;\n\t\t\tthis.type = owner.GenericParameterType;\n\t\t\tthis.etype = ConvertGenericParameterType (this.type);\n\t\t}\n\n\t\tpublic GenericParameter (int position, GenericParameterType type, ModuleDefinition module)\n\t\t\t: base (string.Empty, string.Empty)\n\t\t{\n\t\t\tif (module == null)\n\t\t\t\tthrow new ArgumentNullException ();\n\n\t\t\tthis.position = position;\n\t\t\tthis.type = type;\n\t\t\tthis.etype = ConvertGenericParameterType (type);\n\t\t\tthis.module = module;\n\t\t}\n\n\t\tstatic ElementType ConvertGenericParameterType (GenericParameterType type)\n\t\t{\n\t\t\tswitch (type) {\n\t\t\tcase GenericParameterType.Type:\n\t\t\t\treturn ElementType.Var;\n\t\t\tcase GenericParameterType.Method:\n\t\t\t\treturn ElementType.MVar;\n\t\t\t}\n\n\t\t\tthrow new ArgumentOutOfRangeException ();\n\t\t}\n\n\t\tpublic override TypeDefinition Resolve ()\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tsealed class GenericParameterCollection : Collection<GenericParameter> {\n\n\t\treadonly IGenericParameterProvider owner;\n\n\t\tinternal GenericParameterCollection (IGenericParameterProvider owner)\n\t\t{\n\t\t\tthis.owner = owner;\n\t\t}\n\n\t\tinternal GenericParameterCollection (IGenericParameterProvider owner, int capacity)\n\t\t\t: base (capacity)\n\t\t{\n\t\t\tthis.owner = owner;\n\t\t}\n\n\t\tprotected override void OnAdd (GenericParameter item, int index)\n\t\t{\n\t\t\tUpdateGenericParameter (item, index);\n\t\t}\n\n\t\tprotected override void OnInsert (GenericParameter item, int index)\n\t\t{\n\t\t\tUpdateGenericParameter (item, index);\n\n\t\t\tfor (int i = index; i < size; i++)\n\t\t\t\titems[i].position = i + 1;\n\t\t}\n\n\t\tprotected override void OnSet (GenericParameter item, int index)\n\t\t{\n\t\t\tUpdateGenericParameter (item, index);\n\t\t}\n\n\t\tvoid UpdateGenericParameter (GenericParameter item, int index)\n\t\t{\n\t\t\titem.owner = owner;\n\t\t\titem.position = index;\n\t\t\titem.type = owner.GenericParameterType;\n\t\t}\n\n\t\tprotected override void OnRemove (GenericParameter item, int index)\n\t\t{\n\t\t\titem.owner = null;\n\t\t\titem.position = -1;\n\t\t\titem.type = GenericParameterType.Type;\n\n\t\t\tfor (int i = index + 1; i < size; i++)\n\t\t\t\titems[i].position = i - 1;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/GenericParameterAttributes.cs",
    "content": "//\n// GenericParameterAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum GenericParameterAttributes : ushort {\n\t\tVarianceMask\t= 0x0003,\n\t\tNonVariant\t\t= 0x0000,\n\t\tCovariant\t\t= 0x0001,\n\t\tContravariant\t= 0x0002,\n\n\t\tSpecialConstraintMask\t\t\t= 0x001c,\n\t\tReferenceTypeConstraint\t\t\t= 0x0004,\n\t\tNotNullableValueTypeConstraint\t= 0x0008,\n\t\tDefaultConstructorConstraint\t= 0x0010\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/IConstantProvider.cs",
    "content": "//\n// IConstantProvider.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic interface IConstantProvider : IMetadataTokenProvider {\n\n\t\tbool HasConstant { get; set; }\n\t\tobject Constant { get; set; }\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tinternal static object NoValue = new object ();\n\t\tinternal static object NotResolved = new object ();\n\n\t\tpublic static void ResolveConstant (\n\t\t\tIConstantProvider self,\n\t\t\tref object constant,\n\t\t\tModuleDefinition module)\n\t\t{\n\t\t\tlock (module.SyncRoot) {\n\t\t\t\tif (constant != Mixin.NotResolved)\n\t\t\t\t\treturn;\n\t\t\t\tif (Mixin.HasImage (module))\n\t\t\t\t\tconstant = module.Read (self, (provider, reader) => reader.ReadConstant (provider));\n\t\t\t\telse\n\t\t\t\t\tconstant = Mixin.NoValue;\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ICustomAttributeProvider.cs",
    "content": "//\n// ICustomAttributeProvider.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public interface ICustomAttributeProvider : IMetadataTokenProvider\n    {\n\n        Collection<CustomAttribute> CustomAttributes { get; }\n\n        bool HasCustomAttributes { get; }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool GetHasCustomAttributes(\n            ICustomAttributeProvider self,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module) && module.Read(self, (provider, reader) => reader.HasCustomAttributes(provider));\n        }\n\n        public static Collection<CustomAttribute> GetCustomAttributes(\n            ICustomAttributeProvider self,\n            ref Collection<CustomAttribute> variable,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module)\n                ? module.Read(ref variable, self, (provider, reader) => reader.ReadCustomAttributes(provider))\n                : variable = new Collection<CustomAttribute>();\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/IGenericInstance.cs",
    "content": "//\n// IGenericInstance.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic interface IGenericInstance : IMetadataTokenProvider {\n\n\t\tbool HasGenericArguments { get; }\n\t\tCollection<TypeReference> GenericArguments { get; }\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic static bool ContainsGenericParameter (IGenericInstance self)\n\t\t{\n\t\t\tvar arguments = self.GenericArguments;\n\n\t\t\tfor (int i = 0; i < arguments.Count; i++)\n\t\t\t\tif (arguments [i].ContainsGenericParameter)\n\t\t\t\t\treturn true;\n\n\t\t\treturn false;\n\t\t}\n\n\t\tpublic static void GenericInstanceFullName (IGenericInstance self, StringBuilder builder)\n\t\t{\n\t\t\tbuilder.Append (\"<\");\n\t\t\tvar arguments = self.GenericArguments;\n\t\t\tfor (int i = 0; i < arguments.Count; i++) {\n\t\t\t\tif (i > 0)\n\t\t\t\t\tbuilder.Append (\",\");\n\t\t\t\tbuilder.Append (arguments [i].FullName);\n\t\t\t}\n\t\t\tbuilder.Append (\">\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/IGenericParameterProvider.cs",
    "content": "//\n// IGenericParameterProvider.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public interface IGenericParameterProvider : IMetadataTokenProvider\n    {\n\n        bool HasGenericParameters { get; }\n        bool IsDefinition { get; }\n        ModuleDefinition Module { get; }\n        Collection<GenericParameter> GenericParameters { get; }\n        GenericParameterType GenericParameterType { get; }\n    }\n\n    public enum GenericParameterType\n    {\n        Type,\n        Method\n    }\n\n    interface IGenericContext\n    {\n\n        bool IsDefinition { get; }\n        IGenericParameterProvider Type { get; }\n        IGenericParameterProvider Method { get; }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool GetHasGenericParameters(\n            IGenericParameterProvider self,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module) && module.Read(self, (provider, reader) => reader.HasGenericParameters(provider));\n        }\n\n        public static Collection<GenericParameter> GetGenericParameters(\n            IGenericParameterProvider self,\n            ref Collection<GenericParameter> collection,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module)\n                ? module.Read(ref collection, self, (provider, reader) => reader.ReadGenericParameters(provider))\n                : collection = new GenericParameterCollection(self);\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/IMarshalInfoProvider.cs",
    "content": "//\n// IMarshalInfoProvider.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil\n{\n\n    public interface IMarshalInfoProvider : IMetadataTokenProvider\n    {\n\n        bool HasMarshalInfo { get; }\n        MarshalInfo MarshalInfo { get; set; }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool GetHasMarshalInfo(\n            IMarshalInfoProvider self,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module) && module.Read(self, (provider, reader) => reader.HasMarshalInfo(provider));\n        }\n\n        public static MarshalInfo GetMarshalInfo(\n            IMarshalInfoProvider self,\n            ref MarshalInfo variable,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module)\n                ? module.Read(ref variable, self, (provider, reader) => reader.ReadMarshalInfo(provider))\n                : null;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/IMemberDefinition.cs",
    "content": "//\n// IMemberDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil\n{\n\n    public interface IMemberDefinition : ICustomAttributeProvider\n    {\n\n        string Name { get; set; }\n        string FullName { get; }\n\n        bool IsSpecialName { get; set; }\n        bool IsRuntimeSpecialName { get; set; }\n\n        TypeDefinition DeclaringType { get; set; }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool GetAttributes(uint self, uint attributes)\n        {\n            return (self & attributes) != 0;\n        }\n\n        public static uint SetAttributes(uint self, uint attributes, bool value)\n        {\n            if (value)\n                return self | attributes;\n\n            return self & ~attributes;\n        }\n\n        public static bool GetMaskedAttributes(uint self, uint mask, uint attributes)\n        {\n            return (self & mask) == attributes;\n        }\n\n        public static uint SetMaskedAttributes(uint self, uint mask, uint attributes, bool value)\n        {\n            if (value)\n            {\n                self &= ~mask;\n                return self | attributes;\n            }\n\n            return self & ~(mask & attributes);\n        }\n\n        public static bool GetAttributes(ushort self, ushort attributes)\n        {\n            return (self & attributes) != 0;\n        }\n\n        public static ushort SetAttributes(ushort self, ushort attributes, bool value)\n        {\n            if (value)\n                return (ushort)(self | attributes);\n\n            return (ushort)(self & ~attributes);\n        }\n\n        public static bool GetMaskedAttributes(ushort self, ushort mask, uint attributes)\n        {\n            return (self & mask) == attributes;\n        }\n\n        public static ushort SetMaskedAttributes(ushort self, ushort mask, uint attributes, bool value)\n        {\n            if (value)\n            {\n                self = (ushort)(self & ~mask);\n                return (ushort)(self | attributes);\n            }\n\n            return (ushort)(self & ~(mask & attributes));\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/IMetadataScope.cs",
    "content": "//\n// IMetadataScope.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum MetadataScopeType {\n\t\tAssemblyNameReference,\n\t\tModuleReference,\n\t\tModuleDefinition,\n\t}\n\n\tpublic interface IMetadataScope : IMetadataTokenProvider {\n\t\tMetadataScopeType MetadataScopeType { get; }\n\t\tstring Name { get; set; }\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/IMetadataTokenProvider.cs",
    "content": "//\n// IMetadataTokenProvider.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic interface IMetadataTokenProvider {\n\n\t\tMetadataToken MetadataToken { get; set; }\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/IMethodSignature.cs",
    "content": "//\n// IMethodSignature.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic interface IMethodSignature : IMetadataTokenProvider {\n\n\t\tbool HasThis { get; set; }\n\t\tbool ExplicitThis { get; set; }\n\t\tMethodCallingConvention CallingConvention { get; set; }\n\n\t\tbool HasParameters { get; }\n\t\tCollection<ParameterDefinition> Parameters { get; }\n\t\tTypeReference ReturnType { get; set; }\n\t\tMethodReturnType MethodReturnType { get; }\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic static bool HasImplicitThis (IMethodSignature self)\n\t\t{\n\t\t\treturn self.HasThis && !self.ExplicitThis;\n\t\t}\n\n\t\tpublic static void MethodSignatureFullName (IMethodSignature self, StringBuilder builder)\n\t\t{\n\t\t\tbuilder.Append (\"(\");\n\n\t\t\tif (self.HasParameters) {\n\t\t\t\tvar parameters = self.Parameters;\n\t\t\t\tfor (int i = 0; i < parameters.Count; i++) {\n\t\t\t\t\tvar parameter = parameters [i];\n\t\t\t\t\tif (i > 0)\n\t\t\t\t\t\tbuilder.Append (\",\");\n\n\t\t\t\t\tif (parameter.ParameterType.IsSentinel)\n\t\t\t\t\t\tbuilder.Append (\"...,\");\n\n\t\t\t\t\tbuilder.Append (parameter.ParameterType.FullName);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbuilder.Append (\")\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/Import.cs",
    "content": "//\n// Import.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing SR = System.Reflection;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil\n{\n\n    enum ImportGenericKind\n    {\n        Definition,\n        Open,\n    }\n\n    class MetadataImporter\n    {\n\n        readonly ModuleDefinition module;\n\n        public MetadataImporter(ModuleDefinition module)\n        {\n            this.module = module;\n        }\n\n\n        public TypeReference ImportType(TypeReference type, IGenericContext context)\n        {\n            if (Mixin.IsTypeSpecification(type))\n                return ImportTypeSpecification(type, context);\n\n            var reference = new TypeReference(\n                type.Namespace,\n                type.Name,\n                module,\n                ImportScope(type.Scope),\n                type.IsValueType);\n\n            MetadataSystem.TryProcessPrimitiveTypeReference(reference);\n\n            if (type.IsNested)\n                reference.DeclaringType = ImportType(type.DeclaringType, context);\n\n            if (type.HasGenericParameters)\n                ImportGenericParameters(reference, type);\n\n            return reference;\n        }\n\n        IMetadataScope ImportScope(IMetadataScope scope)\n        {\n            switch (scope.MetadataScopeType)\n            {\n                case MetadataScopeType.AssemblyNameReference:\n                    return ImportAssemblyName((AssemblyNameReference)scope);\n                case MetadataScopeType.ModuleDefinition:\n                    return ImportAssemblyName(((ModuleDefinition)scope).Assembly.Name);\n                case MetadataScopeType.ModuleReference:\n                    throw new NotImplementedException();\n            }\n\n            throw new NotSupportedException();\n        }\n\n        AssemblyNameReference ImportAssemblyName(AssemblyNameReference name)\n        {\n            AssemblyNameReference reference;\n            if (TryGetAssemblyNameReference(name, out reference))\n                return reference;\n\n            reference = new AssemblyNameReference(name.Name, name.Version)\n            {\n                Culture = name.Culture,\n                HashAlgorithm = name.HashAlgorithm,\n            };\n\n            var pk_token = !Mixin.IsNullOrEmpty(name.PublicKeyToken)\n                ? new byte[name.PublicKeyToken.Length]\n                : Empty<byte>.Array;\n\n            if (pk_token.Length > 0)\n                Buffer.BlockCopy(name.PublicKeyToken, 0, pk_token, 0, pk_token.Length);\n\n            reference.PublicKeyToken = pk_token;\n\n            module.AssemblyReferences.Add(reference);\n\n            return reference;\n        }\n\n        bool TryGetAssemblyNameReference(AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)\n        {\n            var references = module.AssemblyReferences;\n\n            for (int i = 0; i < references.Count; i++)\n            {\n                var reference = references[i];\n                if (name_reference.FullName != reference.FullName) // TODO compare field by field\n                    continue;\n\n                assembly_reference = reference;\n                return true;\n            }\n\n            assembly_reference = null;\n            return false;\n        }\n\n        static void ImportGenericParameters(IGenericParameterProvider imported, IGenericParameterProvider original)\n        {\n            var parameters = original.GenericParameters;\n            var imported_parameters = imported.GenericParameters;\n\n            for (int i = 0; i < parameters.Count; i++)\n                imported_parameters.Add(new GenericParameter(parameters[i].Name, imported));\n        }\n\n        TypeReference ImportTypeSpecification(TypeReference type, IGenericContext context)\n        {\n            switch (type.etype)\n            {\n                case ElementType.SzArray:\n                    var vector = (ArrayType)type;\n                    return new ArrayType(ImportType(vector.ElementType, context));\n                case ElementType.Ptr:\n                    var pointer = (PointerType)type;\n                    return new PointerType(ImportType(pointer.ElementType, context));\n                case ElementType.ByRef:\n                    var byref = (ByReferenceType)type;\n                    return new ByReferenceType(ImportType(byref.ElementType, context));\n                case ElementType.Pinned:\n                    var pinned = (PinnedType)type;\n                    return new PinnedType(ImportType(pinned.ElementType, context));\n                case ElementType.Sentinel:\n                    var sentinel = (SentinelType)type;\n                    return new SentinelType(ImportType(sentinel.ElementType, context));\n                case ElementType.CModOpt:\n                    var modopt = (OptionalModifierType)type;\n                    return new OptionalModifierType(\n                        ImportType(modopt.ModifierType, context),\n                        ImportType(modopt.ElementType, context));\n                case ElementType.CModReqD:\n                    var modreq = (RequiredModifierType)type;\n                    return new RequiredModifierType(\n                        ImportType(modreq.ModifierType, context),\n                        ImportType(modreq.ElementType, context));\n                case ElementType.Array:\n                    var array = (ArrayType)type;\n                    var imported_array = new ArrayType(ImportType(array.ElementType, context));\n                    if (array.IsVector)\n                        return imported_array;\n\n                    var dimensions = array.Dimensions;\n                    var imported_dimensions = imported_array.Dimensions;\n\n                    imported_dimensions.Clear();\n\n                    for (int i = 0; i < dimensions.Count; i++)\n                    {\n                        var dimension = dimensions[i];\n\n                        imported_dimensions.Add(new ArrayDimension(dimension.LowerBound, dimension.UpperBound));\n                    }\n\n                    return imported_array;\n                case ElementType.GenericInst:\n                    var instance = (GenericInstanceType)type;\n                    var element_type = ImportType(instance.ElementType, context);\n                    var imported_instance = new GenericInstanceType(element_type);\n\n                    var arguments = instance.GenericArguments;\n                    var imported_arguments = imported_instance.GenericArguments;\n\n                    for (int i = 0; i < arguments.Count; i++)\n                        imported_arguments.Add(ImportType(arguments[i], context));\n\n                    return imported_instance;\n                case ElementType.Var:\n                    if (context == null || context.Type == null)\n                        throw new InvalidOperationException();\n\n                    return ((TypeReference)context.Type).GetElementType().GenericParameters[((GenericParameter)type).Position];\n                case ElementType.MVar:\n                    if (context == null || context.Method == null)\n                        throw new InvalidOperationException();\n\n                    return context.Method.GenericParameters[((GenericParameter)type).Position];\n            }\n\n            throw new NotSupportedException(type.etype.ToString());\n        }\n\n        public FieldReference ImportField(FieldReference field, IGenericContext context)\n        {\n            var declaring_type = ImportType(field.DeclaringType, context);\n\n            return new FieldReference\n            {\n                Name = field.Name,\n                DeclaringType = declaring_type,\n                FieldType = ImportType(field.FieldType, context ?? declaring_type),\n            };\n        }\n\n        public MethodReference ImportMethod(MethodReference method, IGenericContext context)\n        {\n            if (method.IsGenericInstance)\n                return ImportMethodSpecification(method, context);\n\n            var declaring_type = ImportType(method.DeclaringType, context);\n\n            var reference = new MethodReference\n            {\n                Name = method.Name,\n                HasThis = method.HasThis,\n                ExplicitThis = method.ExplicitThis,\n                DeclaringType = declaring_type,\n            };\n\n            reference.CallingConvention = method.CallingConvention;\n\n            if (method.HasGenericParameters)\n                ImportGenericParameters(reference, method);\n\n            reference.ReturnType = ImportType(method.ReturnType, context ?? reference);\n\n            if (!method.HasParameters)\n                return reference;\n\n            var reference_parameters = reference.Parameters;\n\n            var parameters = method.Parameters;\n            for (int i = 0; i < parameters.Count; i++)\n                reference_parameters.Add(\n                    new ParameterDefinition(ImportType(parameters[i].ParameterType, context ?? reference)));\n\n            return reference;\n        }\n\n        MethodSpecification ImportMethodSpecification(MethodReference method, IGenericContext context)\n        {\n            if (!method.IsGenericInstance)\n                throw new NotSupportedException();\n\n            var instance = (GenericInstanceMethod)method;\n            var element_method = ImportMethod(instance.ElementMethod, context);\n            var imported_instance = new GenericInstanceMethod(element_method);\n\n            var arguments = instance.GenericArguments;\n            var imported_arguments = imported_instance.GenericArguments;\n\n            for (int i = 0; i < arguments.Count; i++)\n                imported_arguments.Add(ImportType(arguments[i], context));\n\n            return imported_instance;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/LinkedResource.cs",
    "content": "//\n// LinkedResource.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class LinkedResource : Resource {\n\n\t\tinternal byte [] hash;\n\t\tstring file;\n\n\t\tpublic byte [] Hash {\n\t\t\tget { return hash; }\n\t\t}\n\n\t\tpublic string File {\n\t\t\tget { return file; }\n\t\t\tset { file = value; }\n\t\t}\n\n\t\tpublic override ResourceType ResourceType {\n\t\t\tget { return ResourceType.Linked; }\n\t\t}\n\n\t\tpublic LinkedResource (string name, ManifestResourceAttributes flags)\n\t\t\t: base (name, flags)\n\t\t{\n\t\t}\n\n\t\tpublic LinkedResource (string name, ManifestResourceAttributes flags, string file)\n\t\t\t: base (name, flags)\n\t\t{\n\t\t\tthis.file = file;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ManifestResourceAttributes.cs",
    "content": "//\n// ManifestResourceAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum ManifestResourceAttributes : uint {\n\t\tVisibilityMask\t= 0x0007,\n\t\tPublic\t\t\t= 0x0001,\t// The resource is exported from the Assembly\n\t\tPrivate\t\t\t= 0x0002\t // The resource is private to the Assembly\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MarshalInfo.cs",
    "content": "//\n// MarshalInfo.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic class MarshalInfo {\n\n\t\tinternal NativeType native;\n\n\t\tpublic NativeType NativeType {\n\t\t\tget { return native; }\n\t\t\tset { native = value; }\n\t\t}\n\n\t\tpublic MarshalInfo (NativeType native)\n\t\t{\n\t\t\tthis.native = native;\n\t\t}\n\t}\n\n\tpublic sealed class ArrayMarshalInfo : MarshalInfo {\n\n\t\tinternal NativeType element_type;\n\t\tinternal int size_parameter_index;\n\t\tinternal int size;\n\t\tinternal int size_parameter_multiplier;\n\n\t\tpublic NativeType ElementType {\n\t\t\tget { return element_type; }\n\t\t\tset { element_type = value; }\n\t\t}\n\n\t\tpublic int SizeParameterIndex {\n\t\t\tget { return size_parameter_index; }\n\t\t\tset { size_parameter_index = value; }\n\t\t}\n\n\t\tpublic int Size {\n\t\t\tget { return size; }\n\t\t\tset { size = value; }\n\t\t}\n\n\t\tpublic int SizeParameterMultiplier {\n\t\t\tget { return size_parameter_multiplier; }\n\t\t\tset { size_parameter_multiplier = value; }\n\t\t}\n\n\t\tpublic ArrayMarshalInfo ()\n\t\t\t: base (NativeType.Array)\n\t\t{\n\t\t\telement_type = NativeType.None;\n\t\t\tsize_parameter_index = -1;\n\t\t\tsize = -1;\n\t\t\tsize_parameter_multiplier = -1;\n\t\t}\n\t}\n\n\tpublic sealed class CustomMarshalInfo : MarshalInfo {\n\n\t\tinternal Guid guid;\n\t\tinternal string unmanaged_type;\n\t\tinternal TypeReference managed_type;\n\t\tinternal string cookie;\n\n\t\tpublic Guid Guid {\n\t\t\tget { return guid; }\n\t\t\tset { guid = value; }\n\t\t}\n\n\t\tpublic string UnmanagedType {\n\t\t\tget { return unmanaged_type; }\n\t\t\tset { unmanaged_type = value; }\n\t\t}\n\n\t\tpublic TypeReference ManagedType {\n\t\t\tget { return managed_type; }\n\t\t\tset { managed_type = value; }\n\t\t}\n\n\t\tpublic string Cookie {\n\t\t\tget { return cookie; }\n\t\t\tset { cookie = value; }\n\t\t}\n\n\t\tpublic CustomMarshalInfo ()\n\t\t\t: base (NativeType.CustomMarshaler)\n\t\t{\n\t\t}\n\t}\n\n\tpublic sealed class SafeArrayMarshalInfo : MarshalInfo {\n\n\t\tinternal VariantType element_type;\n\n\t\tpublic VariantType ElementType {\n\t\t\tget { return element_type; }\n\t\t\tset { element_type = value; }\n\t\t}\n\n\t\tpublic SafeArrayMarshalInfo ()\n\t\t\t: base (NativeType.SafeArray)\n\t\t{\n\t\t\telement_type = VariantType.None;\n\t\t}\n\t}\n\n\tpublic sealed class FixedArrayMarshalInfo : MarshalInfo {\n\n\t\tinternal NativeType element_type;\n\t\tinternal int size;\n\n\t\tpublic NativeType ElementType {\n\t\t\tget { return element_type; }\n\t\t\tset { element_type = value; }\n\t\t}\n\n\t\tpublic int Size {\n\t\t\tget { return size; }\n\t\t\tset { size = value; }\n\t\t}\n\n\t\tpublic FixedArrayMarshalInfo ()\n\t\t\t: base (NativeType.FixedArray)\n\t\t{\n\t\t\telement_type = NativeType.None;\n\t\t}\n\t}\n\n\tpublic sealed class FixedSysStringMarshalInfo : MarshalInfo {\n\n\t\tinternal int size;\n\n\t\tpublic int Size {\n\t\t\tget { return size; }\n\t\t\tset { size = value; }\n\t\t}\n\n\t\tpublic FixedSysStringMarshalInfo ()\n\t\t\t: base (NativeType.FixedSysString)\n\t\t{\n\t\t\tsize = -1;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MemberDefinitionCollection.cs",
    "content": "//\n// MemberDefinitionCollection.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tclass MemberDefinitionCollection<T> : Collection<T> where T : IMemberDefinition {\n\n\t\tTypeDefinition container;\n\n\t\tinternal MemberDefinitionCollection (TypeDefinition container)\n\t\t{\n\t\t\tthis.container = container;\n\t\t}\n\n\t\tinternal MemberDefinitionCollection (TypeDefinition container, int capacity)\n\t\t\t: base (capacity)\n\t\t{\n\t\t\tthis.container = container;\n\t\t}\n\n\t\tprotected override void OnAdd (T item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected sealed override void OnSet (T item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected sealed override void OnInsert (T item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected sealed override void OnRemove (T item, int index)\n\t\t{\n\t\t\tDetach (item);\n\t\t}\n\n\t\tprotected sealed override void OnClear ()\n\t\t{\n\t\t\tforeach (var definition in this)\n\t\t\t\tDetach (definition);\n\t\t}\n\n\t\tvoid Attach (T element)\n\t\t{\n\t\t\tif (element.DeclaringType == container)\n\t\t\t\treturn;\n\n\t\t\tif (element.DeclaringType != null)\n\t\t\t\tthrow new ArgumentException (\"Member already attached\");\n\n\t\t\telement.DeclaringType = this.container;\n\t\t}\n\n\t\tstatic void Detach (T element)\n\t\t{\n\t\t\telement.DeclaringType = null;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MemberReference.cs",
    "content": "//\n// MemberReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class MemberReference : IMetadataTokenProvider {\n\n\t\tstring name;\n\t\tTypeReference declaring_type;\n\n\t\tinternal MetadataToken token;\n\n\t\tpublic virtual string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic abstract string FullName {\n\t\t\tget;\n\t\t}\n\n\t\tpublic virtual TypeReference DeclaringType {\n\t\t\tget { return declaring_type; }\n\t\t\tset { declaring_type = value; }\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return token; }\n\t\t\tset { token = value; }\n\t\t}\n\n\t\tinternal bool HasImage {\n\t\t\tget {\n\t\t\t\tvar module = Module;\n\t\t\t\tif (module == null)\n\t\t\t\t\treturn false;\n\n\t\t\t\treturn module.HasImage;\n\t\t\t}\n\t\t}\n\n\t\tpublic virtual ModuleDefinition Module {\n\t\t\tget { return declaring_type != null ? declaring_type.Module : null; }\n\t\t}\n\n\t\tpublic virtual bool IsDefinition {\n\t\t\tget { return false; }\n\t\t}\n\n\t\tinternal virtual bool ContainsGenericParameter {\n\t\t\tget { return declaring_type != null && declaring_type.ContainsGenericParameter; }\n\t\t}\n\n\t\tinternal MemberReference ()\n\t\t{\n\t\t}\n\n\t\tinternal MemberReference (string name)\n\t\t{\n\t\t\tthis.name = name ?? string.Empty;\n\t\t}\n\n\t\tinternal string MemberFullName ()\n\t\t{\n\t\t\tif (declaring_type == null)\n\t\t\t\treturn name;\n\n\t\t\treturn declaring_type.FullName + \"::\" + name;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn FullName;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MetadataResolver.cs",
    "content": "//\n// MetadataResolver.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public interface IAssemblyResolver\n    {\n        AssemblyDefinition Resolve(AssemblyNameReference name);\n        AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters);\n\n        AssemblyDefinition Resolve(string fullName);\n        AssemblyDefinition Resolve(string fullName, ReaderParameters parameters);\n        event AssemblyResolveEventHandler ResolveFailure;\n    }\n\n    public interface IMetadataResolver\n    {\n        TypeDefinition Resolve(TypeReference type);\n        FieldDefinition Resolve(FieldReference field);\n        MethodDefinition Resolve(MethodReference method);\n    }\n\n\n    public class ResolutionException : Exception\n    {\n\n        readonly MemberReference member;\n\n        public MemberReference Member\n        {\n            get { return member; }\n        }\n\n        public ResolutionException(MemberReference member)\n            : base(\"Failed to resolve \" + member.FullName)\n        {\n            this.member = member;\n        }\n\n\n    }\n\n    public class MetadataResolver : IMetadataResolver\n    {\n\n        readonly IAssemblyResolver assembly_resolver;\n\n        public IAssemblyResolver AssemblyResolver\n        {\n            get { return assembly_resolver; }\n        }\n\n        public MetadataResolver(IAssemblyResolver assemblyResolver)\n        {\n            if (assemblyResolver == null)\n                throw new ArgumentNullException(\"assemblyResolver\");\n\n            assembly_resolver = assemblyResolver;\n        }\n\n        public virtual TypeDefinition Resolve(TypeReference type)\n        {\n            if (type == null)\n                throw new ArgumentNullException(\"type\");\n\n            type = type.GetElementType();\n\n            var scope = type.Scope;\n            switch (scope.MetadataScopeType)\n            {\n                case MetadataScopeType.AssemblyNameReference:\n                    var assembly = assembly_resolver.Resolve((AssemblyNameReference)scope);\n                    if (assembly == null)\n                        return null;\n\n                    return GetType(assembly.MainModule, type);\n                case MetadataScopeType.ModuleDefinition:\n                    return GetType((ModuleDefinition)scope, type);\n                case MetadataScopeType.ModuleReference:\n                    var modules = type.Module.Assembly.Modules;\n                    var module_ref = (ModuleReference)scope;\n                    for (int i = 0; i < modules.Count; i++)\n                    {\n                        var netmodule = modules[i];\n                        if (netmodule.Name == module_ref.Name)\n                            return GetType(netmodule, type);\n                    }\n                    break;\n            }\n\n            throw new NotSupportedException();\n        }\n\n        static TypeDefinition GetType(ModuleDefinition module, TypeReference reference)\n        {\n            var type = GetTypeDefinition(module, reference);\n            if (type != null)\n                return type;\n\n            if (!module.HasExportedTypes)\n                return null;\n\n            var exported_types = module.ExportedTypes;\n\n            for (int i = 0; i < exported_types.Count; i++)\n            {\n                var exported_type = exported_types[i];\n                if (exported_type.Name != reference.Name)\n                    continue;\n\n                if (exported_type.Namespace != reference.Namespace)\n                    continue;\n\n                return exported_type.Resolve();\n            }\n\n            return null;\n        }\n\n        static TypeDefinition GetTypeDefinition(ModuleDefinition module, TypeReference type)\n        {\n            if (!type.IsNested)\n                return module.GetType(type.Namespace, type.Name);\n\n            var declaring_type = type.DeclaringType.Resolve();\n            if (declaring_type == null)\n                return null;\n\n            return Mixin.GetNestedType(declaring_type, type.Name);\n        }\n\n        public virtual FieldDefinition Resolve(FieldReference field)\n        {\n            if (field == null)\n                throw new ArgumentNullException(\"field\");\n\n            var type = Resolve(field.DeclaringType);\n            if (type == null)\n                return null;\n\n            if (!type.HasFields)\n                return null;\n\n            return GetField(type, field);\n        }\n\n        FieldDefinition GetField(TypeDefinition type, FieldReference reference)\n        {\n            while (type != null)\n            {\n                var field = GetField(type.Fields, reference);\n                if (field != null)\n                    return field;\n\n                if (type.BaseType == null)\n                    return null;\n\n                type = Resolve(type.BaseType);\n            }\n\n            return null;\n        }\n\n        static FieldDefinition GetField(Collection<FieldDefinition> fields, FieldReference reference)\n        {\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var field = fields[i];\n\n                if (field.Name != reference.Name)\n                    continue;\n\n                if (!AreSame(field.FieldType, reference.FieldType))\n                    continue;\n\n                return field;\n            }\n\n            return null;\n        }\n\n        public virtual MethodDefinition Resolve(MethodReference method)\n        {\n            if (method == null)\n                throw new ArgumentNullException(\"method\");\n\n            var type = Resolve(method.DeclaringType);\n            if (type == null)\n                return null;\n\n            method = method.GetElementMethod();\n\n            if (!type.HasMethods)\n                return null;\n\n            return GetMethod(type, method);\n        }\n\n        MethodDefinition GetMethod(TypeDefinition type, MethodReference reference)\n        {\n            while (type != null)\n            {\n                var method = GetMethod(type.Methods, reference);\n                if (method != null)\n                    return method;\n\n                if (type.BaseType == null)\n                    return null;\n\n                type = Resolve(type.BaseType);\n            }\n\n            return null;\n        }\n\n        public static MethodDefinition GetMethod(Collection<MethodDefinition> methods, MethodReference reference)\n        {\n            for (int i = 0; i < methods.Count; i++)\n            {\n                var method = methods[i];\n\n                if (method.Name != reference.Name)\n                    continue;\n\n                if (method.HasGenericParameters != reference.HasGenericParameters)\n                    continue;\n\n                if (method.HasGenericParameters && method.GenericParameters.Count != reference.GenericParameters.Count)\n                    continue;\n\n                if (!AreSame(method.ReturnType, reference.ReturnType))\n                    continue;\n\n                if (method.HasParameters != reference.HasParameters)\n                    continue;\n\n                if (!method.HasParameters && !reference.HasParameters)\n                    return method;\n\n                if (!AreSame(method.Parameters, reference.Parameters))\n                    continue;\n\n                return method;\n            }\n\n            return null;\n        }\n\n        static bool AreSame(Collection<ParameterDefinition> a, Collection<ParameterDefinition> b)\n        {\n            var count = a.Count;\n\n            if (count != b.Count)\n                return false;\n\n            if (count == 0)\n                return true;\n\n            for (int i = 0; i < count; i++)\n                if (!AreSame(a[i].ParameterType, b[i].ParameterType))\n                    return false;\n\n            return true;\n        }\n\n        static bool AreSame(TypeSpecification a, TypeSpecification b)\n        {\n            if (!AreSame(a.ElementType, b.ElementType))\n                return false;\n\n            if (a.IsGenericInstance)\n                return AreSame((GenericInstanceType)a, (GenericInstanceType)b);\n\n            if (a.IsRequiredModifier || a.IsOptionalModifier)\n                return AreSame((IModifierType)a, (IModifierType)b);\n\n            if (a.IsArray)\n                return AreSame((ArrayType)a, (ArrayType)b);\n\n            return true;\n        }\n\n        static bool AreSame(ArrayType a, ArrayType b)\n        {\n            if (a.Rank != b.Rank)\n                return false;\n\n            // TODO: dimensions\n\n            return true;\n        }\n\n        static bool AreSame(IModifierType a, IModifierType b)\n        {\n            return AreSame(a.ModifierType, b.ModifierType);\n        }\n\n        static bool AreSame(GenericInstanceType a, GenericInstanceType b)\n        {\n            if (a.GenericArguments.Count != b.GenericArguments.Count)\n                return false;\n\n            for (int i = 0; i < a.GenericArguments.Count; i++)\n                if (!AreSame(a.GenericArguments[i], b.GenericArguments[i]))\n                    return false;\n\n            return true;\n        }\n\n        static bool AreSame(GenericParameter a, GenericParameter b)\n        {\n            return a.Position == b.Position;\n        }\n\n        static bool AreSame(TypeReference a, TypeReference b)\n        {\n            if (ReferenceEquals(a, b))\n                return true;\n\n            if (a == null || b == null)\n                return false;\n\n            if (a.etype != b.etype)\n                return false;\n\n            if (a.IsGenericParameter)\n                return AreSame((GenericParameter)a, (GenericParameter)b);\n\n            if (Mixin.IsTypeSpecification(a))\n                return AreSame((TypeSpecification)a, (TypeSpecification)b);\n\n            if (a.Name != b.Name || a.Namespace != b.Namespace)\n                return false;\n\n            //TODO: check scope\n\n            return AreSame(a.DeclaringType, b.DeclaringType);\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MetadataSystem.cs",
    "content": "//\n// MetadataSystem.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tstruct Range {\n\t\tpublic uint Start;\n\t\tpublic uint Length;\n\n\t\tpublic Range (uint index, uint length)\n\t\t{\n\t\t\tthis.Start = index;\n\t\t\tthis.Length = length;\n\t\t}\n\t}\n\n\tsealed class MetadataSystem {\n\n\t\tinternal AssemblyNameReference [] AssemblyReferences;\n\t\tinternal ModuleReference [] ModuleReferences;\n\n\t\tinternal TypeDefinition [] Types;\n\t\tinternal TypeReference [] TypeReferences;\n\n\t\tinternal FieldDefinition [] Fields;\n\t\tinternal MethodDefinition [] Methods;\n\t\tinternal MemberReference [] MemberReferences;\n\n\t\tinternal Dictionary<uint, uint []> NestedTypes;\n\t\tinternal Dictionary<uint, uint> ReverseNestedTypes;\n\t\tinternal Dictionary<uint, MetadataToken []> Interfaces;\n\t\tinternal Dictionary<uint, Row<ushort, uint>> ClassLayouts;\n\t\tinternal Dictionary<uint, uint> FieldLayouts;\n\t\tinternal Dictionary<uint, uint> FieldRVAs;\n\t\tinternal Dictionary<MetadataToken, uint> FieldMarshals;\n\t\tinternal Dictionary<MetadataToken, Row<ElementType, uint>> Constants;\n\t\tinternal Dictionary<uint, MetadataToken []> Overrides;\n\t\tinternal Dictionary<MetadataToken, Range> CustomAttributes;\n\t\tinternal Dictionary<MetadataToken, Range> SecurityDeclarations;\n\t\tinternal Dictionary<uint, Range> Events;\n\t\tinternal Dictionary<uint, Range> Properties;\n\t\tinternal Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>> Semantics;\n\t\tinternal Dictionary<uint, Row<PInvokeAttributes, uint, uint>> PInvokes;\n\t\tinternal Dictionary<MetadataToken, Range> GenericParameters;\n\t\tinternal Dictionary<uint, MetadataToken []> GenericConstraints;\n\n\t\tstatic Dictionary<string, Row<ElementType, bool>> primitive_value_types;\n\n\t\tstatic void InitializePrimitives ()\n\t\t{\n\t\t\tprimitive_value_types = new Dictionary<string, Row<ElementType, bool>> (18, StringComparer.Ordinal) {\n\t\t\t\t{ \"Void\", new Row<ElementType, bool> (ElementType.Void, false) },\n\t\t\t\t{ \"Boolean\", new Row<ElementType, bool> (ElementType.Boolean, true) },\n\t\t\t\t{ \"Char\", new Row<ElementType, bool> (ElementType.Char, true) },\n\t\t\t\t{ \"SByte\", new Row<ElementType, bool> (ElementType.I1, true) },\n\t\t\t\t{ \"Byte\", new Row<ElementType, bool> (ElementType.U1, true) },\n\t\t\t\t{ \"Int16\", new Row<ElementType, bool> (ElementType.I2, true) },\n\t\t\t\t{ \"UInt16\", new Row<ElementType, bool> (ElementType.U2, true) },\n\t\t\t\t{ \"Int32\", new Row<ElementType, bool> (ElementType.I4, true) },\n\t\t\t\t{ \"UInt32\", new Row<ElementType, bool> (ElementType.U4, true) },\n\t\t\t\t{ \"Int64\", new Row<ElementType, bool> (ElementType.I8, true) },\n\t\t\t\t{ \"UInt64\", new Row<ElementType, bool> (ElementType.U8, true) },\n\t\t\t\t{ \"Single\", new Row<ElementType, bool> (ElementType.R4, true) },\n\t\t\t\t{ \"Double\", new Row<ElementType, bool> (ElementType.R8, true) },\n\t\t\t\t{ \"String\", new Row<ElementType, bool> (ElementType.String, false) },\n\t\t\t\t{ \"TypedReference\", new Row<ElementType, bool> (ElementType.TypedByRef, false) },\n\t\t\t\t{ \"IntPtr\", new Row<ElementType, bool> (ElementType.I, true) },\n\t\t\t\t{ \"UIntPtr\", new Row<ElementType, bool> (ElementType.U, true) },\n\t\t\t\t{ \"Object\", new Row<ElementType, bool> (ElementType.Object, false) },\n\t\t\t};\n\t\t}\n\n\t\tpublic static void TryProcessPrimitiveTypeReference (TypeReference type)\n\t\t{\n\t\t\tif (type.Namespace != \"System\")\n\t\t\t\treturn;\n\n\t\t\tvar scope = type.scope;\n\t\t\tif (scope == null || scope.MetadataScopeType != MetadataScopeType.AssemblyNameReference)\n\t\t\t\treturn;\n\n\t\t\tRow<ElementType, bool> primitive_data;\n\t\t\tif (!TryGetPrimitiveData (type, out primitive_data))\n\t\t\t\treturn;\n\n\t\t\ttype.etype = primitive_data.Col1;\n\t\t\ttype.IsValueType = primitive_data.Col2;\n\t\t}\n\n\t\tpublic static bool TryGetPrimitiveElementType (TypeDefinition type, out ElementType etype)\n\t\t{\n\t\t\tetype = ElementType.None;\n\n\t\t\tif (type.Namespace != \"System\")\n\t\t\t\treturn false;\n\n\t\t\tRow<ElementType, bool> primitive_data;\n\t\t\tif (TryGetPrimitiveData (type, out primitive_data) &&Mixin .IsPrimitive (primitive_data.Col1)) {\n\t\t\t\tetype = primitive_data.Col1;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tstatic bool TryGetPrimitiveData (TypeReference type, out Row<ElementType, bool> primitive_data)\n\t\t{\n\t\t\tif (primitive_value_types == null)\n\t\t\t\tInitializePrimitives ();\n\n\t\t\treturn primitive_value_types.TryGetValue (type.Name, out primitive_data);\n\t\t}\n\n\t\tpublic void Clear ()\n\t\t{\n\t\t\tif (NestedTypes != null) NestedTypes.Clear ();\n\t\t\tif (ReverseNestedTypes != null) ReverseNestedTypes.Clear ();\n\t\t\tif (Interfaces != null) Interfaces.Clear ();\n\t\t\tif (ClassLayouts != null) ClassLayouts.Clear ();\n\t\t\tif (FieldLayouts != null) FieldLayouts.Clear ();\n\t\t\tif (FieldRVAs != null) FieldRVAs.Clear ();\n\t\t\tif (FieldMarshals != null) FieldMarshals.Clear ();\n\t\t\tif (Constants != null) Constants.Clear ();\n\t\t\tif (Overrides != null) Overrides.Clear ();\n\t\t\tif (CustomAttributes != null) CustomAttributes.Clear ();\n\t\t\tif (SecurityDeclarations != null) SecurityDeclarations.Clear ();\n\t\t\tif (Events != null) Events.Clear ();\n\t\t\tif (Properties != null) Properties.Clear ();\n\t\t\tif (Semantics != null) Semantics.Clear ();\n\t\t\tif (PInvokes != null) PInvokes.Clear ();\n\t\t\tif (GenericParameters != null) GenericParameters.Clear ();\n\t\t\tif (GenericConstraints != null) GenericConstraints.Clear ();\n\t\t}\n\n\t\tpublic TypeDefinition GetTypeDefinition (uint rid)\n\t\t{\n\t\t\tif (rid < 1 || rid > Types.Length)\n\t\t\t\treturn null;\n\n\t\t\treturn Types [rid - 1];\n\t\t}\n\n\t\tpublic void AddTypeDefinition (TypeDefinition type)\n\t\t{\n\t\t\tTypes [type.token.RID - 1] = type;\n\t\t}\n\n\t\tpublic TypeReference GetTypeReference (uint rid)\n\t\t{\n\t\t\tif (rid < 1 || rid > TypeReferences.Length)\n\t\t\t\treturn null;\n\n\t\t\treturn TypeReferences [rid - 1];\n\t\t}\n\n\t\tpublic void AddTypeReference (TypeReference type)\n\t\t{\n\t\t\tTypeReferences [type.token.RID - 1] = type;\n\t\t}\n\n\t\tpublic FieldDefinition GetFieldDefinition (uint rid)\n\t\t{\n\t\t\tif (rid < 1 || rid > Fields.Length)\n\t\t\t\treturn null;\n\n\t\t\treturn Fields [rid - 1];\n\t\t}\n\n\t\tpublic void AddFieldDefinition (FieldDefinition field)\n\t\t{\n\t\t\tFields [field.token.RID - 1] = field;\n\t\t}\n\n\t\tpublic MethodDefinition GetMethodDefinition (uint rid)\n\t\t{\n\t\t\tif (rid < 1 || rid > Methods.Length)\n\t\t\t\treturn null;\n\n\t\t\treturn Methods [rid - 1];\n\t\t}\n\n\t\tpublic void AddMethodDefinition (MethodDefinition method)\n\t\t{\n\t\t\tMethods [method.token.RID - 1] = method;\n\t\t}\n\n\t\tpublic MemberReference GetMemberReference (uint rid)\n\t\t{\n\t\t\tif (rid < 1 || rid > MemberReferences.Length)\n\t\t\t\treturn null;\n\n\t\t\treturn MemberReferences [rid - 1];\n\t\t}\n\n\t\tpublic void AddMemberReference (MemberReference member)\n\t\t{\n\t\t\tMemberReferences [member.token.RID - 1] = member;\n\t\t}\n\n\t\tpublic bool TryGetNestedTypeMapping (TypeDefinition type, out uint [] mapping)\n\t\t{\n\t\t\treturn NestedTypes.TryGetValue (type.token.RID, out mapping);\n\t\t}\n\n\t\tpublic void SetNestedTypeMapping (uint type_rid, uint [] mapping)\n\t\t{\n\t\t\tNestedTypes [type_rid] = mapping;\n\t\t}\n\n\t\tpublic void RemoveNestedTypeMapping (TypeDefinition type)\n\t\t{\n\t\t\tNestedTypes.Remove (type.token.RID);\n\t\t}\n\n\t\tpublic bool TryGetReverseNestedTypeMapping (TypeDefinition type, out uint declaring)\n\t\t{\n\t\t\treturn ReverseNestedTypes.TryGetValue (type.token.RID, out declaring);\n\t\t}\n\n\t\tpublic void SetReverseNestedTypeMapping (uint nested, uint declaring)\n\t\t{\n\t\t\tReverseNestedTypes.Add (nested, declaring);\n\t\t}\n\n\t\tpublic void RemoveReverseNestedTypeMapping (TypeDefinition type)\n\t\t{\n\t\t\tReverseNestedTypes.Remove (type.token.RID);\n\t\t}\n\n\t\tpublic bool TryGetInterfaceMapping (TypeDefinition type, out MetadataToken [] mapping)\n\t\t{\n\t\t\treturn Interfaces.TryGetValue (type.token.RID, out mapping);\n\t\t}\n\n\t\tpublic void SetInterfaceMapping (uint type_rid, MetadataToken [] mapping)\n\t\t{\n\t\t\tInterfaces [type_rid] = mapping;\n\t\t}\n\n\t\tpublic void RemoveInterfaceMapping (TypeDefinition type)\n\t\t{\n\t\t\tInterfaces.Remove (type.token.RID);\n\t\t}\n\n\t\tpublic void AddPropertiesRange (uint type_rid, Range range)\n\t\t{\n\t\t\tProperties.Add (type_rid, range);\n\t\t}\n\n\t\tpublic bool TryGetPropertiesRange (TypeDefinition type, out Range range)\n\t\t{\n\t\t\treturn Properties.TryGetValue (type.token.RID, out range);\n\t\t}\n\n\t\tpublic void RemovePropertiesRange (TypeDefinition type)\n\t\t{\n\t\t\tProperties.Remove (type.token.RID);\n\t\t}\n\n\t\tpublic void AddEventsRange (uint type_rid, Range range)\n\t\t{\n\t\t\tEvents.Add (type_rid, range);\n\t\t}\n\n\t\tpublic bool TryGetEventsRange (TypeDefinition type, out Range range)\n\t\t{\n\t\t\treturn Events.TryGetValue (type.token.RID, out range);\n\t\t}\n\n\t\tpublic void RemoveEventsRange (TypeDefinition type)\n\t\t{\n\t\t\tEvents.Remove (type.token.RID);\n\t\t}\n\n\t\tpublic bool TryGetGenericParameterRange (IGenericParameterProvider owner, out Range range)\n\t\t{\n\t\t\treturn GenericParameters.TryGetValue (owner.MetadataToken, out range);\n\t\t}\n\n\t\tpublic void RemoveGenericParameterRange (IGenericParameterProvider owner)\n\t\t{\n\t\t\tGenericParameters.Remove (owner.MetadataToken);\n\t\t}\n\n\t\tpublic bool TryGetCustomAttributeRange (ICustomAttributeProvider owner, out Range range)\n\t\t{\n\t\t\treturn CustomAttributes.TryGetValue (owner.MetadataToken, out range);\n\t\t}\n\n\t\tpublic void RemoveCustomAttributeRange (ICustomAttributeProvider owner)\n\t\t{\n\t\t\tCustomAttributes.Remove (owner.MetadataToken);\n\t\t}\n\n\t\tpublic bool TryGetSecurityDeclarationRange (ISecurityDeclarationProvider owner, out Range range)\n\t\t{\n\t\t\treturn SecurityDeclarations.TryGetValue (owner.MetadataToken, out range);\n\t\t}\n\n\t\tpublic void RemoveSecurityDeclarationRange (ISecurityDeclarationProvider owner)\n\t\t{\n\t\t\tSecurityDeclarations.Remove (owner.MetadataToken);\n\t\t}\n\n\t\tpublic bool TryGetGenericConstraintMapping (GenericParameter generic_parameter, out MetadataToken [] mapping)\n\t\t{\n\t\t\treturn GenericConstraints.TryGetValue (generic_parameter.token.RID, out mapping);\n\t\t}\n\n\t\tpublic void SetGenericConstraintMapping (uint gp_rid, MetadataToken [] mapping)\n\t\t{\n\t\t\tGenericConstraints [gp_rid] = mapping;\n\t\t}\n\n\t\tpublic void RemoveGenericConstraintMapping (GenericParameter generic_parameter)\n\t\t{\n\t\t\tGenericConstraints.Remove (generic_parameter.token.RID);\n\t\t}\n\n\t\tpublic bool TryGetOverrideMapping (MethodDefinition method, out MetadataToken [] mapping)\n\t\t{\n\t\t\treturn Overrides.TryGetValue (method.token.RID, out mapping);\n\t\t}\n\n\t\tpublic void SetOverrideMapping (uint rid, MetadataToken [] mapping)\n\t\t{\n\t\t\tOverrides [rid] = mapping;\n\t\t}\n\n\t\tpublic void RemoveOverrideMapping (MethodDefinition method)\n\t\t{\n\t\t\tOverrides.Remove (method.token.RID);\n\t\t}\n\n\t\tpublic TypeDefinition GetFieldDeclaringType (uint field_rid)\n\t\t{\n\t\t\treturn BinaryRangeSearch (Types, field_rid, true);\n\t\t}\n\n\t\tpublic TypeDefinition GetMethodDeclaringType (uint method_rid)\n\t\t{\n\t\t\treturn BinaryRangeSearch (Types, method_rid, false);\n\t\t}\n\n\t\tstatic TypeDefinition BinaryRangeSearch (TypeDefinition [] types, uint rid, bool field)\n\t\t{\n\t\t\tint min = 0;\n\t\t\tint max = types.Length - 1;\n\t\t\twhile (min <= max) {\n\t\t\t\tint mid = min + ((max - min) / 2);\n\t\t\t\tvar type = types [mid];\n\t\t\t\tvar range = field ? type.fields_range : type.methods_range;\n\n\t\t\t\tif (rid < range.Start)\n\t\t\t\t\tmax = mid - 1;\n\t\t\t\telse if (rid >= range.Start + range.Length)\n\t\t\t\t\tmin = mid + 1;\n\t\t\t\telse\n\t\t\t\t\treturn type;\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodAttributes.cs",
    "content": "//\n// MethodAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum MethodAttributes : ushort {\n\t\tMemberAccessMask\t= 0x0007,\n\t\tCompilerControlled\t= 0x0000,\t// Member not referenceable\n\t\tPrivate\t\t\t\t= 0x0001,\t// Accessible only by the parent type\n\t\tFamANDAssem\t\t\t= 0x0002,\t// Accessible by sub-types only in this Assembly\n\t\tAssembly\t\t\t= 0x0003,\t// Accessibly by anyone in the Assembly\n\t\tFamily\t\t\t\t= 0x0004,\t// Accessible only by type and sub-types\n\t\tFamORAssem\t\t\t= 0x0005,\t// Accessibly by sub-types anywhere, plus anyone in assembly\n\t\tPublic\t\t\t\t= 0x0006,\t// Accessibly by anyone who has visibility to this scope\n\n\t\tStatic\t\t\t\t= 0x0010,\t// Defined on type, else per instance\n\t\tFinal\t\t\t\t= 0x0020,\t// Method may not be overridden\n\t\tVirtual\t\t\t\t= 0x0040,\t// Method is virtual\n\t\tHideBySig\t\t\t= 0x0080,\t// Method hides by name+sig, else just by name\n\n\t\tVtableLayoutMask\t= 0x0100,\t// Use this mask to retrieve vtable attributes\n\t\tReuseSlot\t\t\t= 0x0000,\t// Method reuses existing slot in vtable\n\t\tNewSlot\t\t\t\t= 0x0100,\t// Method always gets a new slot in the vtable\n\n\t\tCheckAccessOnOverride = 0x0200,   // Method can only be overriden if also accessible\n\t\tAbstract\t\t\t= 0x0400,\t// Method does not provide an implementation\n\t\tSpecialName\t\t\t= 0x0800,\t// Method is special\n\n\t\t// Interop Attributes\n\t\tPInvokeImpl\t\t\t= 0x2000,\t// Implementation is forwarded through PInvoke\n\t\tUnmanagedExport\t\t= 0x0008,\t// Reserved: shall be zero for conforming implementations\n\n\t\t// Additional flags\n\t\tRTSpecialName\t\t= 0x1000,\t// CLI provides 'special' behavior, depending upon the name of the method\n\t\tHasSecurity\t\t\t= 0x4000,\t// Method has security associate with it\n\t\tRequireSecObject\t= 0x8000\t // Method calls another method containing security code\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodCallingConvention.cs",
    "content": "//\n// MethodCallingConvention.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum MethodCallingConvention : byte {\n\t\tDefault\t\t= 0x0,\n\t\tC\t\t\t= 0x1,\n\t\tStdCall\t\t= 0x2,\n\t\tThisCall\t= 0x3,\n\t\tFastCall\t= 0x4,\n\t\tVarArg\t\t= 0x5,\n\t\tGeneric\t\t= 0x10,\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodDefinition.cs",
    "content": "//\n// MethodDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Cecil.Cil;\nusing Mono.Collections.Generic;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class MethodDefinition : MethodReference, IMemberDefinition, ISecurityDeclarationProvider\n    {\n\n        ushort attributes;\n        ushort impl_attributes;\n        internal volatile bool sem_attrs_ready;\n        internal MethodSemanticsAttributes sem_attrs;\n        Collection<CustomAttribute> custom_attributes;\n        Collection<SecurityDeclaration> security_declarations;\n\n        internal RVA rva;\n        internal PInvokeInfo pinvoke;\n        Collection<MethodReference> overrides;\n\n        internal MethodBody body;\n\n        public MethodAttributes Attributes\n        {\n            get { return (MethodAttributes)attributes; }\n            set { attributes = (ushort)value; }\n        }\n\n        public MethodImplAttributes ImplAttributes\n        {\n            get { return (MethodImplAttributes)impl_attributes; }\n            set { impl_attributes = (ushort)value; }\n        }\n\n        public MethodSemanticsAttributes SemanticsAttributes\n        {\n            get\n            {\n                if (sem_attrs_ready)\n                    return sem_attrs;\n\n                if (HasImage)\n                {\n                    ReadSemantics();\n                    return sem_attrs;\n                }\n\n                sem_attrs = MethodSemanticsAttributes.None;\n                sem_attrs_ready = true;\n                return sem_attrs;\n            }\n            set { sem_attrs = value; }\n        }\n\n        internal void ReadSemantics()\n        {\n            if (sem_attrs_ready)\n                return;\n\n            var module = this.Module;\n            if (module == null)\n                return;\n\n            if (!module.HasImage)\n                return;\n\n            module.Read(this, (method, reader) => reader.ReadAllSemantics(method));\n        }\n\n        public bool HasSecurityDeclarations\n        {\n            get\n            {\n                if (security_declarations != null)\n                    return security_declarations.Count > 0;\n\n                return Mixin.GetHasSecurityDeclarations(this, Module);\n            }\n        }\n\n        public Collection<SecurityDeclaration> SecurityDeclarations\n        {\n            get { return security_declarations ?? (Mixin.GetSecurityDeclarations(this, ref security_declarations, Module)); }\n        }\n\n        public bool HasCustomAttributes\n        {\n            get\n            {\n                if (custom_attributes != null)\n                    return custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n            }\n        }\n\n        public Collection<CustomAttribute> CustomAttributes\n        {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n        }\n\n        public int RVA\n        {\n            get { return (int)rva; }\n        }\n\n        public bool HasBody\n        {\n            get\n            {\n                return (attributes & (ushort)MethodAttributes.Abstract) == 0 &&\n                    (attributes & (ushort)MethodAttributes.PInvokeImpl) == 0 &&\n                    (impl_attributes & (ushort)MethodImplAttributes.InternalCall) == 0 &&\n                    (impl_attributes & (ushort)MethodImplAttributes.Native) == 0 &&\n                    (impl_attributes & (ushort)MethodImplAttributes.Unmanaged) == 0 &&\n                    (impl_attributes & (ushort)MethodImplAttributes.Runtime) == 0;\n            }\n        }\n\n        public MethodBody Body\n        {\n            get\n            {\n                MethodBody localBody = this.body;\n                if (localBody != null)\n                    return localBody;\n\n                if (!HasBody)\n                    return null;\n\n                if (HasImage && rva != 0)\n                    return Module.Read(ref body, this, (method, reader) => reader.ReadMethodBody(method));\n\n                return body = new MethodBody(this);\n            }\n            set\n            {\n                // we reset Body to null in ILSpy to save memory; so we need that operation to be thread-safe\n                lock (Module.SyncRoot)\n                {\n                    body = value;\n                }\n            }\n        }\n\n        public bool HasPInvokeInfo\n        {\n            get\n            {\n                if (pinvoke != null)\n                    return true;\n\n                return IsPInvokeImpl;\n            }\n        }\n\n        public PInvokeInfo PInvokeInfo\n        {\n            get\n            {\n                if (pinvoke != null)\n                    return pinvoke;\n\n                if (HasImage && IsPInvokeImpl)\n                    return Module.Read(ref pinvoke, this, (method, reader) => reader.ReadPInvokeInfo(method));\n\n                return null;\n            }\n            set\n            {\n                IsPInvokeImpl = true;\n                pinvoke = value;\n            }\n        }\n\n        public bool HasOverrides\n        {\n            get\n            {\n                if (overrides != null)\n                    return overrides.Count > 0;\n\n                if (HasImage)\n                    return Module.Read(this, (method, reader) => reader.HasOverrides(method));\n\n                return false;\n            }\n        }\n\n        public Collection<MethodReference> Overrides\n        {\n            get\n            {\n                if (overrides != null)\n                    return overrides;\n\n                if (HasImage)\n                    return Module.Read(ref overrides, this, (method, reader) => reader.ReadOverrides(method));\n\n                return overrides = new Collection<MethodReference>();\n            }\n        }\n\n        public override bool HasGenericParameters\n        {\n            get\n            {\n                if (generic_parameters != null)\n                    return generic_parameters.Count > 0;\n\n                return Mixin.GetHasGenericParameters(this, Module);\n            }\n        }\n\n        public override Collection<GenericParameter> GenericParameters\n        {\n            get { return generic_parameters ?? (Mixin.GetGenericParameters(this, ref generic_parameters, Module)); }\n        }\n\n        #region MethodAttributes\n\n        public bool IsCompilerControlled\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.CompilerControlled); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.CompilerControlled, value); }\n        }\n\n        public bool IsPrivate\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Private); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Private, value); }\n        }\n\n        public bool IsFamilyAndAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamANDAssem); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamANDAssem, value); }\n        }\n\n        public bool IsAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Assembly); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Assembly, value); }\n        }\n\n        public bool IsFamily\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Family); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Family, value); }\n        }\n\n        public bool IsFamilyOrAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamORAssem); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamORAssem, value); }\n        }\n\n        public bool IsPublic\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Public); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Public, value); }\n        }\n\n        public bool IsStatic\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Static); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Static, value); }\n        }\n\n        public bool IsFinal\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Final); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Final, value); }\n        }\n\n        public bool IsVirtual\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Virtual); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Virtual, value); }\n        }\n\n        public bool IsHideBySig\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.HideBySig); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.HideBySig, value); }\n        }\n\n        public bool IsReuseSlot\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.ReuseSlot); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.ReuseSlot, value); }\n        }\n\n        public bool IsNewSlot\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.NewSlot); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.NewSlot, value); }\n        }\n\n        public bool IsCheckAccessOnOverride\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.CheckAccessOnOverride); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.CheckAccessOnOverride, value); }\n        }\n\n        public bool IsAbstract\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Abstract); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Abstract, value); }\n        }\n\n        public bool IsSpecialName\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.SpecialName); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.SpecialName, value); }\n        }\n\n        public bool IsPInvokeImpl\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.PInvokeImpl); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.PInvokeImpl, value); }\n        }\n\n        public bool IsUnmanagedExport\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.UnmanagedExport); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.UnmanagedExport, value); }\n        }\n\n        public bool IsRuntimeSpecialName\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.RTSpecialName); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.RTSpecialName, value); }\n        }\n\n        public bool HasSecurity\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.HasSecurity); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.HasSecurity, value); }\n        }\n\n        #endregion\n\n        #region MethodImplAttributes\n\n        public bool IsIL\n        {\n            get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.IL); }\n            set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.IL, value); }\n        }\n\n        public bool IsNative\n        {\n            get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Native); }\n            set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Native, value); }\n        }\n\n        public bool IsRuntime\n        {\n            get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Runtime); }\n            set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Runtime, value); }\n        }\n\n        public bool IsUnmanaged\n        {\n            get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Unmanaged); }\n            set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Unmanaged, value); }\n        }\n\n        public bool IsManaged\n        {\n            get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Managed); }\n            set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Managed, value); }\n        }\n\n        public bool IsForwardRef\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.ForwardRef); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.ForwardRef, value); }\n        }\n\n        public bool IsPreserveSig\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.PreserveSig); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.PreserveSig, value); }\n        }\n\n        public bool IsInternalCall\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.InternalCall); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.InternalCall, value); }\n        }\n\n        public bool IsSynchronized\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.Synchronized); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.Synchronized, value); }\n        }\n\n        public bool NoInlining\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.NoInlining); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.NoInlining, value); }\n        }\n\n        public bool NoOptimization\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.NoOptimization); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.NoOptimization, value); }\n        }\n\n        #endregion\n\n        #region MethodSemanticsAttributes\n\n        public bool IsSetter\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Setter); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Setter, value); }\n        }\n\n        public bool IsGetter\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Getter); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Getter, value); }\n        }\n\n        public bool IsOther\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Other); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Other, value); }\n        }\n\n        public bool IsAddOn\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.AddOn); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.AddOn, value); }\n        }\n\n        public bool IsRemoveOn\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.RemoveOn); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.RemoveOn, value); }\n        }\n\n        public bool IsFire\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Fire); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Fire, value); }\n        }\n\n        #endregion\n\n        public new TypeDefinition DeclaringType\n        {\n            get { return (TypeDefinition)base.DeclaringType; }\n            set { base.DeclaringType = value; }\n        }\n\n        public bool IsConstructor\n        {\n            get\n            {\n                return this.IsRuntimeSpecialName\n                    && this.IsSpecialName\n                    && (this.Name == \".cctor\" || this.Name == \".ctor\");\n            }\n        }\n\n        public override bool IsDefinition\n        {\n            get { return true; }\n        }\n\n        internal MethodDefinition()\n        {\n            this.token = new MetadataToken(TokenType.Method);\n        }\n\n        public MethodDefinition(string name, MethodAttributes attributes, TypeReference returnType)\n            : base(name, returnType)\n        {\n            this.attributes = (ushort)attributes;\n            this.HasThis = !this.IsStatic;\n            this.token = new MetadataToken(TokenType.Method);\n        }\n\n        public override MethodDefinition Resolve()\n        {\n            return this;\n        }\n    }\n\n    static partial class Mixin\n    {\n\n        public static ParameterDefinition GetParameter(MethodBody self, int index)\n        {\n            var method = self.method;\n\n            if (method.HasThis)\n            {\n                if (index == 0)\n                    return self.ThisParameter;\n\n                index--;\n            }\n\n            var parameters = method.Parameters;\n\n            if (index < 0 || index >= parameters.size)\n                return null;\n\n            return parameters[index];\n        }\n\n        public static VariableDefinition GetVariable(MethodBody self, int index)\n        {\n            var variables = self.Variables;\n\n            if (index < 0 || index >= variables.size)\n                return null;\n\n            return variables[index];\n        }\n\n        public static bool GetSemantics(MethodDefinition self, MethodSemanticsAttributes semantics)\n        {\n            return (self.SemanticsAttributes & semantics) != 0;\n        }\n\n        public static void SetSemantics(MethodDefinition self, MethodSemanticsAttributes semantics, bool value)\n        {\n            if (value)\n                self.SemanticsAttributes |= semantics;\n            else\n                self.SemanticsAttributes &= ~semantics;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodImplAttributes.cs",
    "content": "//\n// MethodImplAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum MethodImplAttributes : ushort {\n\t\tCodeTypeMask\t\t= 0x0003,\n\t\tIL\t\t\t\t\t= 0x0000,\t// Method impl is CIL\n\t\tNative\t\t\t\t= 0x0001,\t// Method impl is native\n\t\tOPTIL\t\t\t\t= 0x0002,\t// Reserved: shall be zero in conforming implementations\n\t\tRuntime\t\t\t\t= 0x0003,\t// Method impl is provided by the runtime\n\n\t\tManagedMask\t\t\t= 0x0004,\t// Flags specifying whether the code is managed or unmanaged\n\t\tUnmanaged\t\t\t= 0x0004,\t// Method impl is unmanaged, otherwise managed\n\t\tManaged\t\t\t\t= 0x0000,\t// Method impl is managed\n\n\t\t// Implementation info and interop\n\t\tForwardRef\t\t\t= 0x0010,\t// Indicates method is defined; used primarily in merge scenarios\n\t\tPreserveSig\t\t\t= 0x0080,\t// Reserved: conforming implementations may ignore\n\t\tInternalCall\t\t= 0x1000,\t// Reserved: shall be zero in conforming implementations\n\t\tSynchronized\t\t= 0x0020,\t// Method is single threaded through the body\n\t\tNoOptimization\t\t= 0x0040,\t// Method is not optimized by the JIT.\n\t\tNoInlining\t\t\t= 0x0008,\t// Method may not be inlined\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodReference.cs",
    "content": "//\n// MethodReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public class MethodReference : MemberReference, IMethodSignature, IGenericParameterProvider, IGenericContext\n    {\n        int hashCode = -1;\n        static int instance_id;\n        internal ParameterDefinitionCollection parameters;\n        MethodReturnType return_type;\n\n        bool has_this;\n        bool explicit_this;\n        MethodCallingConvention calling_convention;\n        internal Collection<GenericParameter> generic_parameters;\n\n        public virtual bool HasThis\n        {\n            get { return has_this; }\n            set { has_this = value; }\n        }\n\n        public virtual bool ExplicitThis\n        {\n            get { return explicit_this; }\n            set { explicit_this = value; }\n        }\n\n        public virtual MethodCallingConvention CallingConvention\n        {\n            get { return calling_convention; }\n            set { calling_convention = value; }\n        }\n\n        public virtual bool HasParameters\n        {\n            get { return !Mixin.IsNullOrEmpty(parameters); }\n        }\n\n        public virtual Collection<ParameterDefinition> Parameters\n        {\n            get\n            {\n                if (parameters == null)\n                    parameters = new ParameterDefinitionCollection(this);\n\n                return parameters;\n            }\n        }\n\n        IGenericParameterProvider IGenericContext.Type\n        {\n            get\n            {\n                var declaring_type = this.DeclaringType;\n                var instance = declaring_type as GenericInstanceType;\n                if (instance != null)\n                    return instance.ElementType;\n\n                return declaring_type;\n            }\n        }\n\n        IGenericParameterProvider IGenericContext.Method\n        {\n            get { return this; }\n        }\n\n        GenericParameterType IGenericParameterProvider.GenericParameterType\n        {\n            get { return GenericParameterType.Method; }\n        }\n\n        public virtual bool HasGenericParameters\n        {\n            get { return !Mixin.IsNullOrEmpty(generic_parameters); }\n        }\n\n        public virtual Collection<GenericParameter> GenericParameters\n        {\n            get\n            {\n                if (generic_parameters != null)\n                    return generic_parameters;\n\n                return generic_parameters = new GenericParameterCollection(this);\n            }\n        }\n\n        public TypeReference ReturnType\n        {\n            get\n            {\n                var return_type = MethodReturnType;\n                return return_type != null ? return_type.ReturnType : null;\n            }\n            set\n            {\n                var return_type = MethodReturnType;\n                if (return_type != null)\n                    return_type.ReturnType = value;\n            }\n        }\n\n        public virtual MethodReturnType MethodReturnType\n        {\n            get { return return_type; }\n            set { return_type = value; }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                var builder = new StringBuilder();\n                builder.Append(ReturnType.FullName)\n                    .Append(\" \")\n                    .Append(MemberFullName());\n                Mixin.MethodSignatureFullName(this, builder);\n                return builder.ToString();\n            }\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n\n        public virtual bool IsGenericInstance\n        {\n            get { return false; }\n        }\n\n        internal override bool ContainsGenericParameter\n        {\n            get\n            {\n                if (this.ReturnType.ContainsGenericParameter || base.ContainsGenericParameter)\n                    return true;\n\n                var parameters = this.Parameters;\n\n                for (int i = 0; i < parameters.Count; i++)\n                    if (parameters[i].ParameterType.ContainsGenericParameter)\n                        return true;\n\n                return false;\n            }\n        }\n\n        internal MethodReference()\n        {\n            this.return_type = new MethodReturnType(this);\n            this.token = new MetadataToken(TokenType.MemberRef);\n        }\n\n        public MethodReference(string name, TypeReference returnType)\n            : base(name)\n        {\n            if (returnType == null)\n                throw new ArgumentNullException(\"returnType\");\n\n            this.return_type = new MethodReturnType(this);\n            this.return_type.ReturnType = returnType;\n            this.token = new MetadataToken(TokenType.MemberRef);\n        }\n\n        public MethodReference(string name, TypeReference returnType, TypeReference declaringType)\n            : this(name, returnType)\n        {\n            if (declaringType == null)\n                throw new ArgumentNullException(\"declaringType\");\n\n            this.DeclaringType = declaringType;\n        }\n\n        public virtual MethodReference GetElementMethod()\n        {\n            return this;\n        }\n\n        public virtual MethodDefinition Resolve()\n        {\n            var module = this.Module;\n            if (module == null)\n                throw new NotSupportedException();\n\n            return module.Resolve(this);\n        }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool IsVarArg(IMethodSignature self)\n        {\n            return (self.CallingConvention & MethodCallingConvention.VarArg) != 0;\n        }\n\n        public static int GetSentinelPosition(IMethodSignature self)\n        {\n            if (!self.HasParameters)\n                return -1;\n\n            var parameters = self.Parameters;\n            for (int i = 0; i < parameters.Count; i++)\n                if (parameters[i].ParameterType.IsSentinel)\n                    return i;\n\n            return -1;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodReturnType.cs",
    "content": "//\n// MethodReturnType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.Threading;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class MethodReturnType : IConstantProvider, ICustomAttributeProvider, IMarshalInfoProvider {\n\n\t\tinternal IMethodSignature method;\n\t\tinternal ParameterDefinition parameter;\n\t\tTypeReference return_type;\n\n\t\tpublic IMethodSignature Method {\n\t\t\tget { return method; }\n\t\t}\n\n\t\tpublic TypeReference ReturnType {\n\t\t\tget { return return_type; }\n\t\t\tset { return_type = value; }\n\t\t}\n\n\t\tinternal ParameterDefinition Parameter {\n\t\t\tget {\n\t\t\t\tif (parameter == null)\n                    parameter=new ParameterDefinition (return_type, method);\n\n\t\t\t\treturn parameter;\n\t\t\t}\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return Parameter.MetadataToken; }\n\t\t\tset { Parameter.MetadataToken = value; }\n\t\t}\n\n\t\tpublic ParameterAttributes Attributes {\n\t\t\tget { return Parameter.Attributes; }\n\t\t\tset { Parameter.Attributes = value; }\n\t\t}\n\n\t\tpublic bool HasCustomAttributes {\n\t\t\tget { return parameter != null && parameter.HasCustomAttributes; }\n\t\t}\n\n\t\tpublic Collection<CustomAttribute> CustomAttributes {\n\t\t\tget { return Parameter.CustomAttributes; }\n\t\t}\n\n\t\tpublic bool HasDefault {\n\t\t\tget { return parameter != null && parameter.HasDefault; }\n\t\t\tset { Parameter.HasDefault = value; }\n\t\t}\n\n\t\tpublic bool HasConstant {\n\t\t\tget { return parameter != null && parameter.HasConstant; }\n\t\t\tset { Parameter.HasConstant = value; }\n\t\t}\n\n\t\tpublic object Constant {\n\t\t\tget { return Parameter.Constant; }\n\t\t\tset { Parameter.Constant = value; }\n\t\t}\n\n\t\tpublic bool HasFieldMarshal {\n\t\t\tget { return parameter != null && parameter.HasFieldMarshal; }\n\t\t\tset { Parameter.HasFieldMarshal = value; }\n\t\t}\n\n\t\tpublic bool HasMarshalInfo {\n\t\t\tget { return parameter != null && parameter.HasMarshalInfo; }\n\t\t}\n\n\t\tpublic MarshalInfo MarshalInfo {\n\t\t\tget { return Parameter.MarshalInfo; }\n\t\t\tset { Parameter.MarshalInfo = value; }\n\t\t}\n\n\t\tpublic MethodReturnType (IMethodSignature method)\n\t\t{\n\t\t\tthis.method = method;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodSemanticsAttributes.cs",
    "content": "//\n// MethodSemanticsattributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum MethodSemanticsAttributes : ushort {\n\t\tNone\t\t= 0x0000,\n\t\tSetter\t\t= 0x0001,\t// Setter for property\n\t\tGetter\t\t= 0x0002,\t// Getter for property\n\t\tOther\t\t= 0x0004,\t// Other method for property or event\n\t\tAddOn\t\t= 0x0008,\t// AddOn method for event\n\t\tRemoveOn\t= 0x0010,\t// RemoveOn method for event\n\t\tFire\t\t= 0x0020\t // Fire method for event\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodSpecification.cs",
    "content": "//\n// MethodSpecification.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class MethodSpecification : MethodReference {\n\n\t\treadonly MethodReference method;\n\n\t\tpublic MethodReference ElementMethod {\n\t\t\tget { return method; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return method.Name; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override MethodCallingConvention CallingConvention {\n\t\t\tget { return method.CallingConvention; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool HasThis {\n\t\t\tget { return method.HasThis; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool ExplicitThis {\n\t\t\tget { return method.ExplicitThis; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override MethodReturnType MethodReturnType {\n\t\t\tget { return method.MethodReturnType; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override TypeReference DeclaringType {\n\t\t\tget { return method.DeclaringType; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override ModuleDefinition Module {\n\t\t\tget { return method.Module; }\n\t\t}\n\n\t\tpublic override bool HasParameters {\n\t\t\tget { return method.HasParameters; }\n\t\t}\n\n\t\tpublic override Collection<ParameterDefinition> Parameters {\n\t\t\tget { return method.Parameters; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return method.ContainsGenericParameter; }\n\t\t}\n\n\t\tinternal MethodSpecification (MethodReference method)\n\t\t{\n\t\t\tif (method == null)\n\t\t\t\tthrow new ArgumentNullException (\"method\");\n\n\t\t\tthis.method = method;\n\t\t\tthis.token = new MetadataToken (TokenType.MethodSpec);\n\t\t}\n\n\t\tpublic sealed override MethodReference GetElementMethod ()\n\t\t{\n\t\t\treturn method.GetElementMethod ();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/Modifiers.cs",
    "content": "//\n// Modifiers.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic interface IModifierType {\n\t\tTypeReference ModifierType { get; }\n\t\tTypeReference ElementType { get; }\n\t}\n\n\tpublic sealed class OptionalModifierType : TypeSpecification, IModifierType {\n\n\t\tTypeReference modifier_type;\n\n\t\tpublic TypeReference ModifierType {\n\t\t\tget { return modifier_type; }\n\t\t\tset { modifier_type = value; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return base.Name + Suffix; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return base.FullName + Suffix; }\n\t\t}\n\n\t\tstring Suffix {\n\t\t\tget { return \" modopt(\" + modifier_type + \")\"; }\n\t\t}\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsOptionalModifier {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return modifier_type.ContainsGenericParameter || base.ContainsGenericParameter; }\n\t\t}\n\n\t\tpublic OptionalModifierType (TypeReference modifierType, TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckModifier (modifierType, type);\n\t\t\tthis.modifier_type = modifierType;\n\t\t\tthis.etype = MD.ElementType.CModOpt;\n\t\t}\n\t}\n\n\tpublic sealed class RequiredModifierType : TypeSpecification, IModifierType {\n\n\t\tTypeReference modifier_type;\n\n\t\tpublic TypeReference ModifierType {\n\t\t\tget { return modifier_type; }\n\t\t\tset { modifier_type = value; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return base.Name + Suffix; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return base.FullName + Suffix; }\n\t\t}\n\n\t\tstring Suffix {\n\t\t\tget { return \" modreq(\" + modifier_type + \")\"; }\n\t\t}\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsRequiredModifier {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return modifier_type.ContainsGenericParameter || base.ContainsGenericParameter; }\n\t\t}\n\n\t\tpublic RequiredModifierType (TypeReference modifierType, TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckModifier (modifierType, type);\n\t\t\tthis.modifier_type = modifierType;\n\t\t\tthis.etype = MD.ElementType.CModReqD;\n\t\t}\n\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic static void CheckModifier (TypeReference modifierType, TypeReference type)\n\t\t{\n\t\t\tif (modifierType == null)\n\t\t\t\tthrow new ArgumentNullException (\"modifierType\");\n\t\t\tif (type == null)\n\t\t\t\tthrow new ArgumentNullException (\"type\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ModuleDefinition.cs",
    "content": "//\n// ModuleDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading;\nusing SR = System.Reflection;\nusing Mono.Cecil.Cil;\nusing Mono.Cecil.Metadata;\nusing Mono.Cecil.PE;\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public enum ReadingMode\n    {\n        Immediate = 1,\n        Deferred = 2,\n    }\n\n    public sealed class ReaderParameters\n    {\n\n        ReadingMode reading_mode;\n        IAssemblyResolver assembly_resolver;\n        IMetadataResolver metadata_resolver;\n        Stream symbol_stream;\n        ISymbolReaderProvider symbol_reader_provider;\n        bool read_symbols;\n\n        public ReadingMode ReadingMode\n        {\n            get { return reading_mode; }\n            set { reading_mode = value; }\n        }\n\n        public IAssemblyResolver AssemblyResolver\n        {\n            get { return assembly_resolver; }\n            set { assembly_resolver = value; }\n        }\n\n        public IMetadataResolver MetadataResolver\n        {\n            get { return metadata_resolver; }\n            set { metadata_resolver = value; }\n        }\n\n        public Stream SymbolStream\n        {\n            get { return symbol_stream; }\n            set { symbol_stream = value; }\n        }\n\n        public ISymbolReaderProvider SymbolReaderProvider\n        {\n            get { return symbol_reader_provider; }\n            set { symbol_reader_provider = value; }\n        }\n\n        public bool ReadSymbols\n        {\n            get { return read_symbols; }\n            set { read_symbols = value; }\n        }\n\n        public ReaderParameters()\n            : this(ReadingMode.Deferred)\n        {\n        }\n\n        public ReaderParameters(ReadingMode readingMode)\n        {\n            this.reading_mode = readingMode;\n        }\n    }\n\n\n    public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider\n    {\n\n        internal Image Image;\n        internal MetadataSystem MetadataSystem;\n        internal ReadingMode ReadingMode;\n        internal ISymbolReaderProvider SymbolReaderProvider;\n\n        internal ISymbolReader symbol_reader;\n        internal IAssemblyResolver assembly_resolver;\n        internal IMetadataResolver metadata_resolver;\n        internal TypeSystem type_system;\n\n        readonly MetadataReader reader;\n        readonly string fq_name;\n\n        internal ModuleKind kind;\n        TargetRuntime runtime;\n        TargetArchitecture architecture;\n        ModuleAttributes attributes;\n        ModuleCharacteristics characteristics;\n        Guid mvid;\n\n        internal AssemblyDefinition assembly;\n        MethodDefinition entry_point;\n\n        Collection<CustomAttribute> custom_attributes;\n        Collection<AssemblyNameReference> references;\n        Collection<ModuleReference> modules;\n        Collection<Resource> resources;\n        Collection<ExportedType> exported_types;\n        TypeDefinitionCollection types;\n\n        public bool IsMain\n        {\n            get { return kind != ModuleKind.NetModule; }\n        }\n\n        public ModuleKind Kind\n        {\n            get { return kind; }\n            set { kind = value; }\n        }\n\n        public TargetRuntime Runtime\n        {\n            get { return runtime; }\n            set { runtime = value; }\n        }\n\n        public TargetArchitecture Architecture\n        {\n            get { return architecture; }\n            set { architecture = value; }\n        }\n\n        public ModuleAttributes Attributes\n        {\n            get { return attributes; }\n            set { attributes = value; }\n        }\n\n        public ModuleCharacteristics Characteristics\n        {\n            get { return characteristics; }\n            set { characteristics = value; }\n        }\n\n        public string FullyQualifiedName\n        {\n            get { return fq_name; }\n        }\n\n        public Guid Mvid\n        {\n            get { return mvid; }\n            set { mvid = value; }\n        }\n\n        internal bool HasImage\n        {\n            get { return Image != null; }\n        }\n\n        public bool HasSymbols\n        {\n            get { return symbol_reader != null; }\n        }\n\n        public ISymbolReader SymbolReader\n        {\n            get { return symbol_reader; }\n        }\n\n        public override MetadataScopeType MetadataScopeType\n        {\n            get { return MetadataScopeType.ModuleDefinition; }\n        }\n\n        public AssemblyDefinition Assembly\n        {\n            get { return assembly; }\n        }\n\n\n        public IAssemblyResolver AssemblyResolver\n        {\n            get { return assembly_resolver ?? (assembly_resolver = new DefaultAssemblyResolver()); }\n        }\n\n        public IMetadataResolver MetadataResolver\n        {\n            get\n            {\n                if (metadata_resolver == null)\n                    metadata_resolver=new MetadataResolver(this.AssemblyResolver);\n\n                return metadata_resolver;\n            }\n        }\n\n        public TypeSystem TypeSystem\n        {\n            get\n            {\n                if (type_system == null)\n                    type_system = TypeSystem.CreateTypeSystem(this);\n                return type_system;\n            }\n        }\n\n        public bool HasAssemblyReferences\n        {\n            get\n            {\n                if (references != null)\n                    return references.Count > 0;\n\n                return HasImage && Image.HasTable(Table.AssemblyRef);\n            }\n        }\n\n        public Collection<AssemblyNameReference> AssemblyReferences\n        {\n            get\n            {\n                if (references != null)\n                    return references;\n\n                if (HasImage)\n                    return Read(ref references, this, (_, reader) => reader.ReadAssemblyReferences());\n\n                return references = new Collection<AssemblyNameReference>();\n            }\n        }\n\n        public bool HasModuleReferences\n        {\n            get\n            {\n                if (modules != null)\n                    return modules.Count > 0;\n\n                return HasImage && Image.HasTable(Table.ModuleRef);\n            }\n        }\n\n        public Collection<ModuleReference> ModuleReferences\n        {\n            get\n            {\n                if (modules != null)\n                    return modules;\n\n                if (HasImage)\n                    return Read(ref modules, this, (_, reader) => reader.ReadModuleReferences());\n\n                return modules = new Collection<ModuleReference>();\n            }\n        }\n\n        public bool HasResources\n        {\n            get\n            {\n                if (resources != null)\n                    return resources.Count > 0;\n\n                if (HasImage)\n                    return Image.HasTable(Table.ManifestResource) || Read(this, (_, reader) => reader.HasFileResource());\n\n                return false;\n            }\n        }\n\n        public Collection<Resource> Resources\n        {\n            get\n            {\n                if (resources != null)\n                    return resources;\n\n                if (HasImage)\n                    return Read(ref resources, this, (_, reader) => reader.ReadResources());\n\n                return resources = new Collection<Resource>();\n            }\n        }\n\n        public bool HasCustomAttributes\n        {\n            get\n            {\n                if (custom_attributes != null)\n                    return custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, this);\n            }\n        }\n\n        public Collection<CustomAttribute> CustomAttributes\n        {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, this)); }\n        }\n\n        public bool HasTypes\n        {\n            get\n            {\n                if (types != null)\n                    return types.Count > 0;\n\n                return HasImage && Image.HasTable(Table.TypeDef);\n            }\n        }\n\n        public Collection<TypeDefinition> Types\n        {\n            get\n            {\n                if (types != null)\n                    return types;\n\n                if (HasImage)\n                    return Read(ref types, this, (_, reader) => reader.ReadTypes());\n\n                return types = new TypeDefinitionCollection(this);\n            }\n        }\n\n        public bool HasExportedTypes\n        {\n            get\n            {\n                if (exported_types != null)\n                    return exported_types.Count > 0;\n\n                return HasImage && Image.HasTable(Table.ExportedType);\n            }\n        }\n\n        public Collection<ExportedType> ExportedTypes\n        {\n            get\n            {\n                if (exported_types != null)\n                    return exported_types;\n\n                if (HasImage)\n                    return Read(ref exported_types, this, (_, reader) => reader.ReadExportedTypes());\n\n                return exported_types = new Collection<ExportedType>();\n            }\n        }\n\n        public MethodDefinition EntryPoint\n        {\n            get\n            {\n                if (entry_point != null)\n                    return entry_point;\n\n                if (HasImage)\n                    return Read(ref entry_point, this, (_, reader) => reader.ReadEntryPoint());\n\n                return entry_point = null;\n            }\n            set { entry_point = value; }\n        }\n\n        internal ModuleDefinition()\n        {\n            this.MetadataSystem = new MetadataSystem();\n            this.token = new MetadataToken(TokenType.Module, 1);\n        }\n\n        internal ModuleDefinition(Image image)\n            : this()\n        {\n            this.Image = image;\n            this.kind = image.Kind;\n            this.runtime = image.Runtime;\n            this.architecture = image.Architecture;\n            this.attributes = image.Attributes;\n            this.characteristics = image.Characteristics;\n            this.fq_name = image.FileName;\n\n            this.reader = new MetadataReader(this);\n        }\n\n        public bool HasTypeReference(string fullName)\n        {\n            return HasTypeReference(string.Empty, fullName);\n        }\n\n        public bool HasTypeReference(string scope, string fullName)\n        {\n            CheckFullName(fullName);\n\n            if (!HasImage)\n                return false;\n\n            return GetTypeReference(scope, fullName) != null;\n        }\n\n        public bool TryGetTypeReference(string fullName, out TypeReference type)\n        {\n            return TryGetTypeReference(string.Empty, fullName, out type);\n        }\n\n        public bool TryGetTypeReference(string scope, string fullName, out TypeReference type)\n        {\n            CheckFullName(fullName);\n\n            if (!HasImage)\n            {\n                type = null;\n                return false;\n            }\n\n            return (type = GetTypeReference(scope, fullName)) != null;\n        }\n\n        TypeReference GetTypeReference(string scope, string fullname)\n        {\n            return Read(new Row<string, string>(scope, fullname), (row, reader) => reader.GetTypeReference(row.Col1, row.Col2));\n        }\n\n        public IEnumerable<TypeReference> GetTypeReferences()\n        {\n            if (!HasImage)\n                return Empty<TypeReference>.Array;\n\n            return Read(this, (_, reader) => reader.GetTypeReferences());\n        }\n\n        public IEnumerable<MemberReference> GetMemberReferences()\n        {\n            if (!HasImage)\n                return Empty<MemberReference>.Array;\n\n            return Read(this, (_, reader) => reader.GetMemberReferences());\n        }\n\n        public TypeReference GetType(string fullName, bool runtimeName)\n        {\n            return runtimeName\n                ? TypeParser.ParseType(this, fullName)\n                : GetType(fullName);\n        }\n\n        public TypeDefinition GetType(string fullName)\n        {\n            CheckFullName(fullName);\n\n            var position = fullName.IndexOf('/');\n            if (position > 0)\n                return GetNestedType(fullName);\n\n            return ((TypeDefinitionCollection)this.Types).GetType(fullName);\n        }\n\n        public TypeDefinition GetType(string @namespace, string name)\n        {\n            Mixin.CheckName(name);\n\n            return ((TypeDefinitionCollection)this.Types).GetType(@namespace ?? string.Empty, name);\n        }\n\n        public IEnumerable<TypeDefinition> GetTypes()\n        {\n            return GetTypes(Types);\n        }\n\n        static IEnumerable<TypeDefinition> GetTypes(Collection<TypeDefinition> types)\n        {\n            for (int i = 0; i < types.Count; i++)\n            {\n                var type = types[i];\n\n                yield return type;\n\n                if (!type.HasNestedTypes)\n                    continue;\n\n                foreach (var nested in GetTypes(type.NestedTypes))\n                    yield return nested;\n            }\n        }\n\n        static void CheckFullName(string fullName)\n        {\n            if (fullName == null)\n                throw new ArgumentNullException(\"fullName\");\n            if (fullName.Length == 0)\n                throw new ArgumentException();\n        }\n\n        TypeDefinition GetNestedType(string fullname)\n        {\n            var names = fullname.Split('/');\n            var type = GetType(names[0]);\n\n            if (type == null)\n                return null;\n\n            for (int i = 1; i < names.Length; i++)\n            {\n                var nested_type = Mixin.GetNestedType(type, names[i]);\n                if (nested_type == null)\n                    return null;\n\n                type = nested_type;\n            }\n\n            return type;\n        }\n\n        internal FieldDefinition Resolve(FieldReference field)\n        {\n            return MetadataResolver.Resolve(field);\n        }\n\n        internal MethodDefinition Resolve(MethodReference method)\n        {\n            return MetadataResolver.Resolve(method);\n        }\n\n        internal TypeDefinition Resolve(TypeReference type)\n        {\n            return MetadataResolver.Resolve(type);\n        }\n\n\n        public IMetadataTokenProvider LookupToken(int token)\n        {\n            return LookupToken(new MetadataToken((uint)token));\n        }\n\n        public IMetadataTokenProvider LookupToken(MetadataToken token)\n        {\n            return Read(token, (t, reader) => reader.LookupToken(t));\n        }\n\n        readonly object module_lock = new object();\n\n        internal object SyncRoot\n        {\n            get { return module_lock; }\n        }\n\n        internal TRet Read<TItem, TRet>(TItem item, Func<TItem, MetadataReader, TRet> read)\n        {\n            lock (module_lock)\n            {\n                var position = reader.position;\n                var context = reader.context;\n\n                var ret = read(item, reader);\n\n                reader.position = position;\n                reader.context = context;\n\n                return ret;\n            }\n        }\n\n        internal TRet Read<TItem, TRet>(ref TRet variable, TItem item, Func<TItem, MetadataReader, TRet> read) where TRet : class\n        {\n            lock (module_lock)\n            {\n                if (variable != null)\n                    return variable;\n\n                var position = reader.position;\n                var context = reader.context;\n\n                var ret = read(item, reader);\n\n                reader.position = position;\n                reader.context = context;\n\n                return variable = ret;\n            }\n        }\n\n        public bool HasDebugHeader\n        {\n            get { return Image != null && !Image.Debug.IsZero; }\n        }\n\n        public ImageDebugDirectory GetDebugHeader(out byte[] header)\n        {\n            if (!HasDebugHeader)\n                throw new InvalidOperationException();\n\n            return Image.GetDebugHeader(out header);\n        }\n\n        void ProcessDebugHeader()\n        {\n            if (!HasDebugHeader)\n                return;\n\n            byte[] header;\n            var directory = GetDebugHeader(out header);\n\n            if (!symbol_reader.ProcessDebugHeader(directory, header))\n                throw new InvalidOperationException();\n        }\n\n\n\n        public void ReadSymbols()\n        {\n            if (string.IsNullOrEmpty(fq_name))\n                throw new InvalidOperationException();\n\n            var provider = SymbolProvider.GetPlatformReaderProvider();\n            if (provider == null)\n                throw new InvalidOperationException();\n\n            ReadSymbols(provider.GetSymbolReader(this, fq_name));\n        }\n\n        public void ReadSymbols(ISymbolReader reader)\n        {\n            if (reader == null)\n                throw new ArgumentNullException(\"reader\");\n\n            symbol_reader = reader;\n\n            ProcessDebugHeader();\n        }\n\n        public static ModuleDefinition ReadModule(string fileName)\n        {\n            return ReadModule(fileName, new ReaderParameters(ReadingMode.Deferred));\n        }\n\n        public static ModuleDefinition ReadModule(Stream stream)\n        {\n            return ReadModule(stream, new ReaderParameters(ReadingMode.Deferred));\n        }\n\n        public static ModuleDefinition ReadModule(string fileName, ReaderParameters parameters)\n        {\n            using (var stream = GetFileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))\n            {\n                return ReadModule(stream, parameters);\n            }\n        }\n\n        static void CheckStream(object stream)\n        {\n            if (stream == null)\n                throw new ArgumentNullException(\"stream\");\n        }\n\n        public static ModuleDefinition ReadModule(Stream stream, ReaderParameters parameters)\n        {\n            CheckStream(stream);\n            if (!stream.CanRead || !stream.CanSeek)\n                throw new ArgumentException();\n            Mixin.CheckParameters(parameters);\n\n            return ModuleReader.CreateModuleFrom(\n                ImageReader.ReadImageFrom(stream),\n                parameters);\n        }\n\n        static Stream GetFileStream(string fileName, FileMode mode, FileAccess access, FileShare share)\n        {\n            if (fileName == null)\n                throw new ArgumentNullException(\"fileName\");\n            if (fileName.Length == 0)\n                throw new ArgumentException();\n\n            return new FileStream(fileName, mode, access, share);\n        }\n\n\n\n    }\n\n    static partial class Mixin\n    {\n\n        public static void CheckParameters(object parameters)\n        {\n            if (parameters == null)\n                throw new ArgumentNullException(\"parameters\");\n        }\n\n        public static bool HasImage(ModuleDefinition self)\n        {\n            return self != null && self.HasImage;\n        }\n\n        public static bool IsCorlib(ModuleDefinition module)\n        {\n            if (module.Assembly == null)\n                return false;\n\n            return module.Assembly.Name.Name == \"mscorlib\";\n        }\n\n        public static string GetFullyQualifiedName(Stream self)\n        {\n\n            return string.Empty;\n        }\n\n        public static TargetRuntime ParseRuntime(string self)\n        {\n            switch (self[1])\n            {\n                case '1':\n                    return self[3] == '0'\n                        ? TargetRuntime.Net_1_0\n                        : TargetRuntime.Net_1_1;\n                case '2':\n                    return TargetRuntime.Net_2_0;\n                case '4':\n                default:\n                    return TargetRuntime.Net_4_0;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ModuleKind.cs",
    "content": "//\n// ModuleKind.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic enum ModuleKind {\n\t\tDll,\n\t\tConsole,\n\t\tWindows,\n\t\tNetModule,\n\t}\n\n\tpublic enum TargetArchitecture {\n\t\tI386,\n\t\tAMD64,\n\t\tIA64,\n\t\tARMv7,\n\t}\n\n\t[Flags]\n\tpublic enum ModuleAttributes {\n\t\tILOnly = 1,\n\t\tRequired32Bit = 2,\n\t\tStrongNameSigned = 8,\n\t\tPreferred32Bit = 0x00020000,\n\t}\n\n\t[Flags]\n\tpublic enum ModuleCharacteristics {\n\t\tHighEntropyVA = 0x0020,\n\t\tDynamicBase = 0x0040,\n\t\tNoSEH = 0x0400,\n\t\tNXCompat = 0x0100,\n\t\tAppContainer = 0x1000,\n\t\tTerminalServerAware = 0x8000,\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ModuleReference.cs",
    "content": "//\n// ModuleReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic class ModuleReference : IMetadataScope {\n\n\t\tstring name;\n\n\t\tinternal MetadataToken token;\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic virtual MetadataScopeType MetadataScopeType {\n\t\t\tget { return MetadataScopeType.ModuleReference; }\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return token; }\n\t\t\tset { token = value; }\n\t\t}\n\n\t\tinternal ModuleReference ()\n\t\t{\n\t\t\tthis.token = new MetadataToken (TokenType.ModuleRef);\n\t\t}\n\n\t\tpublic ModuleReference (string name)\n\t\t\t: this ()\n\t\t{\n\t\t\tthis.name = name;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn name;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/NativeType.cs",
    "content": "//\n// NativeType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum NativeType {\n\t\tNone = 0x66,\n\n\t\tBoolean = 0x02,\n\t\tI1 = 0x03,\n\t\tU1 = 0x04,\n\t\tI2 = 0x05,\n\t\tU2 = 0x06,\n\t\tI4 = 0x07,\n\t\tU4 = 0x08,\n\t\tI8 = 0x09,\n\t\tU8 = 0x0a,\n\t\tR4 = 0x0b,\n\t\tR8 = 0x0c,\n\t\tLPStr = 0x14,\n\t\tInt = 0x1f,\n\t\tUInt = 0x20,\n\t\tFunc = 0x26,\n\t\tArray = 0x2a,\n\n\t\t// Msft specific\n\t\tCurrency = 0x0f,\n\t\tBStr = 0x13,\n\t\tLPWStr = 0x15,\n\t\tLPTStr = 0x16,\n\t\tFixedSysString = 0x17,\n\t\tIUnknown = 0x19,\n\t\tIDispatch = 0x1a,\n\t\tStruct = 0x1b,\n\t\tIntF = 0x1c,\n\t\tSafeArray = 0x1d,\n\t\tFixedArray = 0x1e,\n\t\tByValStr = 0x22,\n\t\tANSIBStr = 0x23,\n\t\tTBStr = 0x24,\n\t\tVariantBool = 0x25,\n\t\tASAny = 0x28,\n\t\tLPStruct = 0x2b,\n\t\tCustomMarshaler = 0x2c,\n\t\tError = 0x2d,\n\t\tMax = 0x50\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/PInvokeAttributes.cs",
    "content": "//\n// PInvokeAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum PInvokeAttributes : ushort {\n\t\tNoMangle\t\t\t= 0x0001,\t// PInvoke is to use the member name as specified\n\n\t\t// Character set\n\t\tCharSetMask\t\t\t= 0x0006,\n\t\tCharSetNotSpec\t\t= 0x0000,\n\t\tCharSetAnsi\t\t\t= 0x0002,\n\t\tCharSetUnicode\t\t= 0x0004,\n\t\tCharSetAuto\t\t\t= 0x0006,\n\n\t\tSupportsLastError\t= 0x0040,\t// Information about target function. Not relevant for fields\n\n\t\t// Calling convetion\n\t\tCallConvMask\t\t= 0x0700,\n\t\tCallConvWinapi\t\t= 0x0100,\n\t\tCallConvCdecl\t\t= 0x0200,\n\t\tCallConvStdCall\t\t= 0x0300,\n\t\tCallConvThiscall\t= 0x0400,\n\t\tCallConvFastcall\t= 0x0500,\n\n\t\tBestFitMask\t\t\t= 0x0030,\n\t\tBestFitEnabled\t\t= 0x0010,\n\t\tBestFitDisabled\t\t= 0x0020,\n\n\t\tThrowOnUnmappableCharMask = 0x3000,\n\t\tThrowOnUnmappableCharEnabled = 0x1000,\n\t\tThrowOnUnmappableCharDisabled = 0x2000,\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/PInvokeInfo.cs",
    "content": "//\n// PInvokeInfo.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class PInvokeInfo {\n\n\t\tushort attributes;\n\t\tstring entry_point;\n\t\tModuleReference module;\n\n\t\tpublic PInvokeAttributes Attributes {\n\t\t\tget { return (PInvokeAttributes) attributes; }\n\t\t\tset { attributes = (ushort) value; }\n\t\t}\n\n\t\tpublic string EntryPoint {\n\t\t\tget { return entry_point; }\n\t\t\tset { entry_point = value; }\n\t\t}\n\n\t\tpublic ModuleReference Module {\n\t\t\tget { return module; }\n\t\t\tset { module = value; }\n\t\t}\n\n\t\t#region PInvokeAttributes\n\n\t\tpublic bool IsNoMangle {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) PInvokeAttributes.NoMangle); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) PInvokeAttributes.NoMangle, value); }\n\t\t}\n\n\t\tpublic bool IsCharSetNotSpec {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetNotSpec); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetNotSpec, value); }\n\t\t}\n\n\t\tpublic bool IsCharSetAnsi {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAnsi); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAnsi, value); }\n\t\t}\n\n\t\tpublic bool IsCharSetUnicode {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetUnicode); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetUnicode, value); }\n\t\t}\n\n\t\tpublic bool IsCharSetAuto {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAuto); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAuto, value); }\n\t\t}\n\n\t\tpublic bool SupportsLastError {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) PInvokeAttributes.SupportsLastError); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) PInvokeAttributes.SupportsLastError, value); }\n\t\t}\n\n\t\tpublic bool IsCallConvWinapi {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvWinapi); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvWinapi, value); }\n\t\t}\n\n\t\tpublic bool IsCallConvCdecl {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvCdecl); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvCdecl, value); }\n\t\t}\n\n\t\tpublic bool IsCallConvStdCall {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvStdCall); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvStdCall, value); }\n\t\t}\n\n\t\tpublic bool IsCallConvThiscall {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvThiscall); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvThiscall, value); }\n\t\t}\n\n\t\tpublic bool IsCallConvFastcall {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvFastcall); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvFastcall, value); }\n\t\t}\n\n\t\tpublic bool IsBestFitEnabled {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitEnabled); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitEnabled, value); }\n\t\t}\n\n\t\tpublic bool IsBestFitDisabled {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitDisabled); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitDisabled, value); }\n\t\t}\n\n\t\tpublic bool IsThrowOnUnmappableCharEnabled {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharEnabled); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharEnabled, value); }\n\t\t}\n\n\t\tpublic bool IsThrowOnUnmappableCharDisabled {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharDisabled); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharDisabled, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic PInvokeInfo (PInvokeAttributes attributes, string entryPoint, ModuleReference module)\n\t\t{\n\t\t\tthis.attributes = (ushort) attributes;\n\t\t\tthis.entry_point = entryPoint;\n\t\t\tthis.module = module;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ParameterAttributes.cs",
    "content": "//\n// ParameterAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum ParameterAttributes : ushort {\n\t\tNone\t\t\t\t= 0x0000,\n\t\tIn\t\t\t\t\t= 0x0001,\t// Param is [In]\n\t\tOut\t\t\t\t\t= 0x0002,\t// Param is [Out]\n\t\tLcid\t\t\t\t= 0x0004,\n\t\tRetval\t\t\t\t= 0x0008,\n\t\tOptional\t\t\t= 0x0010,\t// Param is optional\n\t\tHasDefault\t\t\t= 0x1000,\t// Param has default value\n\t\tHasFieldMarshal\t\t= 0x2000,\t// Param has field marshal\n\t\tUnused\t\t\t\t= 0xcfe0\t // Reserved: shall be zero in a conforming implementation\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ParameterDefinition.cs",
    "content": "//\n// ParameterDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class ParameterDefinition : ParameterReference, ICustomAttributeProvider, IConstantProvider, IMarshalInfoProvider\n    {\n\n        ushort attributes;\n\n        internal IMethodSignature method;\n\n        object constant = Mixin.NotResolved;\n        Collection<CustomAttribute> custom_attributes;\n        MarshalInfo marshal_info;\n\n        public ParameterAttributes Attributes\n        {\n            get { return (ParameterAttributes)attributes; }\n            set { attributes = (ushort)value; }\n        }\n\n        public IMethodSignature Method\n        {\n            get { return method; }\n        }\n\n        public int Sequence\n        {\n            get\n            {\n                if (method == null)\n                    return -1;\n\n                return Mixin.HasImplicitThis(method) ? index + 1 : index;\n            }\n        }\n\n        public bool HasConstant\n        {\n            get\n            {\n                Mixin.ResolveConstant(this, ref constant, parameter_type.Module);\n\n                return constant != Mixin.NoValue;\n            }\n            set { if (!value) constant = Mixin.NoValue; }\n        }\n\n        public object Constant\n        {\n            get { return HasConstant ? constant : null; }\n            set { constant = value; }\n        }\n\n        public bool HasCustomAttributes\n        {\n            get\n            {\n                if (custom_attributes != null)\n                    return custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, parameter_type.Module);\n            }\n        }\n\n        public Collection<CustomAttribute> CustomAttributes\n        {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, parameter_type.Module)); }\n        }\n\n        public bool HasMarshalInfo\n        {\n            get\n            {\n                if (marshal_info != null)\n                    return true;\n\n                return Mixin.GetHasMarshalInfo(this, parameter_type.Module);\n            }\n        }\n\n        public MarshalInfo MarshalInfo\n        {\n            get { return marshal_info ?? (Mixin.GetMarshalInfo(this, ref marshal_info, parameter_type.Module)); }\n            set { marshal_info = value; }\n        }\n\n        #region ParameterAttributes\n\n        public bool IsIn\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.In); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.In, value); }\n        }\n\n        public bool IsOut\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.Out); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.Out, value); }\n        }\n\n        public bool IsLcid\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.Lcid); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.Lcid, value); }\n        }\n\n        public bool IsReturnValue\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.Retval); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.Retval, value); }\n        }\n\n        public bool IsOptional\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.Optional); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.Optional, value); }\n        }\n\n        public bool HasDefault\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.HasDefault); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.HasDefault, value); }\n        }\n\n        public bool HasFieldMarshal\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.HasFieldMarshal); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.HasFieldMarshal, value); }\n        }\n\n        #endregion\n\n        internal ParameterDefinition(TypeReference parameterType, IMethodSignature method)\n            : this(string.Empty, ParameterAttributes.None, parameterType)\n        {\n            this.method = method;\n        }\n\n        public ParameterDefinition(TypeReference parameterType)\n            : this(string.Empty, ParameterAttributes.None, parameterType)\n        {\n        }\n\n        public ParameterDefinition(string name, ParameterAttributes attributes, TypeReference parameterType)\n            : base(name, parameterType)\n        {\n            this.attributes = (ushort)attributes;\n            this.token = new MetadataToken(TokenType.Param);\n        }\n\n        public override ParameterDefinition Resolve()\n        {\n            return this;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ParameterDefinitionCollection.cs",
    "content": "//\n// ParameterDefinitionCollection.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tsealed class ParameterDefinitionCollection : Collection<ParameterDefinition> {\n\n\t\treadonly IMethodSignature method;\n\n\t\tinternal ParameterDefinitionCollection (IMethodSignature method)\n\t\t{\n\t\t\tthis.method = method;\n\t\t}\n\n\t\tinternal ParameterDefinitionCollection (IMethodSignature method, int capacity)\n\t\t\t: base (capacity)\n\t\t{\n\t\t\tthis.method = method;\n\t\t}\n\n\t\tprotected override void OnAdd (ParameterDefinition item, int index)\n\t\t{\n\t\t\titem.method = method;\n\t\t\titem.index = index;\n\t\t}\n\n\t\tprotected override void OnInsert (ParameterDefinition item, int index)\n\t\t{\n\t\t\titem.method = method;\n\t\t\titem.index = index;\n\n\t\t\tfor (int i = index; i < size; i++)\n\t\t\t\titems [i].index = i + 1;\n\t\t}\n\n\t\tprotected override void OnSet (ParameterDefinition item, int index)\n\t\t{\n\t\t\titem.method = method;\n\t\t\titem.index = index;\n\t\t}\n\n\t\tprotected override void OnRemove (ParameterDefinition item, int index)\n\t\t{\n\t\t\titem.method = null;\n\t\t\titem.index = -1;\n\n\t\t\tfor (int i = index + 1; i < size; i++)\n\t\t\t\titems [i].index = i - 1;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ParameterReference.cs",
    "content": "//\n// ParameterReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class ParameterReference : IMetadataTokenProvider {\n\n\t\tstring name;\n\t\tinternal int index = -1;\n\t\tprotected TypeReference parameter_type;\n\t\tinternal MetadataToken token;\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic int Index {\n\t\t\tget { return index; }\n\t\t}\n\n\t\tpublic TypeReference ParameterType {\n\t\t\tget { return parameter_type; }\n\t\t\tset { parameter_type = value; }\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return token; }\n\t\t\tset { token = value; }\n\t\t}\n\n\t\tinternal ParameterReference (string name, TypeReference parameterType)\n\t\t{\n\t\t\tif (parameterType == null)\n\t\t\t\tthrow new ArgumentNullException (\"parameterType\");\n\n\t\t\tthis.name = name ?? string.Empty;\n\t\t\tthis.parameter_type = parameterType;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn name;\n\t\t}\n\n\t\tpublic abstract ParameterDefinition Resolve ();\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/PinnedType.cs",
    "content": "//\n// PinnedType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class PinnedType : TypeSpecification {\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsPinned {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic PinnedType (TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.etype = MD.ElementType.Pinned;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/PointerType.cs",
    "content": "//\n// PointerType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class PointerType : TypeSpecification {\n\n\t\tpublic override string Name {\n\t\t\tget { return base.Name + \"*\"; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return base.FullName + \"*\"; }\n\t\t}\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsPointer {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic PointerType (TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.etype = MD.ElementType.Ptr;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/PropertyAttributes.cs",
    "content": "//\n// PropertyAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum PropertyAttributes : ushort {\n\t\tNone\t\t\t= 0x0000,\n\t\tSpecialName\t\t= 0x0200,\t// Property is special\n\t\tRTSpecialName\t= 0x0400,\t// Runtime(metadata internal APIs) should check name encoding\n\t\tHasDefault\t\t= 0x1000,\t// Property has default\n\t\tUnused\t\t\t= 0xe9ff\t // Reserved: shall be zero in a conforming implementation\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/PropertyDefinition.cs",
    "content": "//\n// PropertyDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class PropertyDefinition : PropertyReference, IMemberDefinition, IConstantProvider {\n\n\t\tbool? has_this;\n\t\tushort attributes;\n\n\t\tCollection<CustomAttribute> custom_attributes;\n\n\t\tinternal MethodDefinition get_method;\n\t\tinternal MethodDefinition set_method;\n\t\tinternal Collection<MethodDefinition> other_methods;\n\n\t\tobject constant = Mixin.NotResolved;\n\n\t\tpublic PropertyAttributes Attributes {\n\t\t\tget { return (PropertyAttributes) attributes; }\n\t\t\tset { attributes = (ushort) value; }\n\t\t}\n\n\t\tpublic bool HasThis {\n\t\t\tget {\n\t\t\t\tif (has_this.HasValue)\n\t\t\t\t\treturn has_this.Value;\n\n\t\t\t\tif (GetMethod != null)\n\t\t\t\t\treturn get_method.HasThis;\n\n\t\t\t\tif (SetMethod != null)\n\t\t\t\t\treturn set_method.HasThis;\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tset { has_this = value; }\n\t\t}\n\n\t\tpublic bool HasCustomAttributes {\n\t\t\tget {\n\t\t\t\tif (custom_attributes != null)\n\t\t\t\t\treturn custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttribute> CustomAttributes {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n\t\t}\n\n\t\tpublic MethodDefinition GetMethod {\n\t\t\tget {\n\t\t\t\tif (get_method != null)\n\t\t\t\t\treturn get_method;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn get_method;\n\t\t\t}\n\t\t\tset { get_method = value; }\n\t\t}\n\n\t\tpublic MethodDefinition SetMethod {\n\t\t\tget {\n\t\t\t\tif (set_method != null)\n\t\t\t\t\treturn set_method;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn set_method;\n\t\t\t}\n\t\t\tset { set_method = value; }\n\t\t}\n\n\t\tpublic bool HasOtherMethods {\n\t\t\tget {\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods.Count > 0;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn !Mixin.IsNullOrEmpty (other_methods);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<MethodDefinition> OtherMethods {\n\t\t\tget {\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods;\n\n\t\t\t\tInitializeMethods ();\n\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods;\n\n\t\t\t\treturn other_methods = new Collection<MethodDefinition> ();\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasParameters {\n\t\t\tget {\n\t\t\t\tInitializeMethods ();\n\n\t\t\t\tif (get_method != null)\n\t\t\t\t\treturn get_method.HasParameters;\n\n\t\t\t\tif (set_method != null)\n\t\t\t\t\treturn set_method.HasParameters && set_method.Parameters.Count > 1;\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tpublic override Collection<ParameterDefinition> Parameters {\n\t\t\tget {\n\t\t\t\tInitializeMethods ();\n\n\t\t\t\tif (get_method != null)\n\t\t\t\t\treturn MirrorParameters (get_method, 0);\n\n\t\t\t\tif (set_method != null)\n\t\t\t\t\treturn MirrorParameters (set_method, 1);\n\n\t\t\t\treturn new Collection<ParameterDefinition> ();\n\t\t\t}\n\t\t}\n\n\t\tstatic Collection<ParameterDefinition> MirrorParameters (MethodDefinition method, int bound)\n\t\t{\n\t\t\tvar parameters = new Collection<ParameterDefinition> ();\n\t\t\tif (!method.HasParameters)\n\t\t\t\treturn parameters;\n\n\t\t\tvar original_parameters = method.Parameters;\n\t\t\tvar end = original_parameters.Count - bound;\n\n\t\t\tfor (int i = 0; i < end; i++)\n\t\t\t\tparameters.Add (original_parameters [i]);\n\n\t\t\treturn parameters;\n\t\t}\n\n\t\tpublic bool HasConstant {\n\t\t\tget {\n                Mixin.ResolveConstant(this, ref constant, Module);\n\n\t\t\t\treturn constant != Mixin.NoValue;\n\t\t\t}\n\t\t\tset { if (!value) constant = Mixin.NoValue; }\n\t\t}\n\n\t\tpublic object Constant {\n\t\t\tget { return HasConstant ? constant : null;\t}\n\t\t\tset { constant = value; }\n\t\t}\n\n\t\t#region PropertyAttributes\n\n\t\tpublic bool IsSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) PropertyAttributes.SpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) PropertyAttributes.SpecialName, value); }\n\t\t}\n\n\t\tpublic bool IsRuntimeSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) PropertyAttributes.RTSpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) PropertyAttributes.RTSpecialName, value); }\n\t\t}\n\n\t\tpublic bool HasDefault {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) PropertyAttributes.HasDefault); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) PropertyAttributes.HasDefault, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic new TypeDefinition DeclaringType {\n\t\t\tget { return (TypeDefinition) base.DeclaringType; }\n\t\t\tset { base.DeclaringType = value; }\n\t\t}\n\n\t\tpublic override bool IsDefinition {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget {\n\t\t\t\tvar builder = new StringBuilder ();\n\t\t\t\tbuilder.Append (PropertyType.ToString ());\n\t\t\t\tbuilder.Append (' ');\n\t\t\t\tbuilder.Append (MemberFullName ());\n\t\t\t\tbuilder.Append ('(');\n\t\t\t\tif (HasParameters) {\n\t\t\t\t\tvar parameters = Parameters;\n\t\t\t\t\tfor (int i = 0; i < parameters.Count; i++) {\n\t\t\t\t\t\tif (i > 0)\n\t\t\t\t\t\t\tbuilder.Append (',');\n\t\t\t\t\t\tbuilder.Append (parameters [i].ParameterType.FullName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbuilder.Append (')');\n\t\t\t\treturn builder.ToString ();\n\t\t\t}\n\t\t}\n\n\t\tpublic PropertyDefinition (string name, PropertyAttributes attributes, TypeReference propertyType)\n\t\t\t: base (name, propertyType)\n\t\t{\n\t\t\tthis.attributes = (ushort) attributes;\n\t\t\tthis.token = new MetadataToken (TokenType.Property);\n\t\t}\n\n\t\tvoid InitializeMethods ()\n\t\t{\n\t\t\tvar module = this.Module;\n\t\t\tlock (module.SyncRoot) {\n\t\t\t\tif (get_method != null || set_method != null)\n\t\t\t\t\treturn;\n\n                if (!Mixin.HasImage(module))\n\t\t\t\t\treturn;\n\n\t\t\t\tmodule.Read (this, (property, reader) => reader.ReadMethods (property));\n\t\t\t}\n\t\t}\n\n\t\tpublic override PropertyDefinition Resolve ()\n\t\t{\n\t\t\treturn this;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/PropertyReference.cs",
    "content": "//\n// PropertyReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class PropertyReference : MemberReference {\n\n\t\tTypeReference property_type;\n\n\t\tpublic TypeReference PropertyType {\n\t\t\tget { return property_type; }\n\t\t\tset { property_type = value; }\n\t\t}\n\n\t\tpublic abstract Collection<ParameterDefinition> Parameters {\n\t\t\tget;\n\t\t}\n\n\t\tinternal PropertyReference (string name, TypeReference propertyType)\n\t\t\t: base (name)\n\t\t{\n\t\t\tif (propertyType == null)\n\t\t\t\tthrow new ArgumentNullException (\"propertyType\");\n\n\t\t\tproperty_type = propertyType;\n\t\t}\n\n\t\tpublic abstract PropertyDefinition Resolve ();\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/ReferenceType.cs",
    "content": "//\n// ByReferenceType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class ByReferenceType : TypeSpecification {\n\n\t\tpublic override string Name {\n\t\t\tget { return base.Name + \"&\"; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return base.FullName + \"&\"; }\n\t\t}\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsByReference {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic ByReferenceType (TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.etype = MD.ElementType.ByRef;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/Resource.cs",
    "content": "//\n// ResourceType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum ResourceType {\n\t\tLinked,\n\t\tEmbedded,\n\t\tAssemblyLinked,\n\t}\n\n\tpublic abstract class Resource {\n\n\t\tstring name;\n\t\tuint attributes;\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic ManifestResourceAttributes Attributes {\n\t\t\tget { return (ManifestResourceAttributes) attributes; }\n\t\t\tset { attributes = (uint) value; }\n\t\t}\n\n\t\tpublic abstract ResourceType ResourceType {\n\t\t\tget;\n\t\t}\n\n\t\t#region ManifestResourceAttributes\n\n\t\tpublic bool IsPublic {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Public); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Public, value); }\n\t\t}\n\n\t\tpublic bool IsPrivate {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Private); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Private, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tinternal Resource (string name, ManifestResourceAttributes attributes)\n\t\t{\n\t\t\tthis.name = name;\n\t\t\tthis.attributes = (uint) attributes;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/SecurityDeclaration.cs",
    "content": "//\n// SecurityDeclaration.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Threading;\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public enum SecurityAction : ushort\n    {\n        Request = 1,\n        Demand = 2,\n        Assert = 3,\n        Deny = 4,\n        PermitOnly = 5,\n        LinkDemand = 6,\n        InheritDemand = 7,\n        RequestMinimum = 8,\n        RequestOptional = 9,\n        RequestRefuse = 10,\n        PreJitGrant = 11,\n        PreJitDeny = 12,\n        NonCasDemand = 13,\n        NonCasLinkDemand = 14,\n        NonCasInheritance = 15\n    }\n\n    public interface ISecurityDeclarationProvider : IMetadataTokenProvider\n    {\n\n        bool HasSecurityDeclarations { get; }\n        Collection<SecurityDeclaration> SecurityDeclarations { get; }\n    }\n\n    public sealed class SecurityAttribute : ICustomAttribute\n    {\n\n        TypeReference attribute_type;\n\n        internal Collection<CustomAttributeNamedArgument> fields;\n        internal Collection<CustomAttributeNamedArgument> properties;\n\n        public TypeReference AttributeType\n        {\n            get { return attribute_type; }\n            set { attribute_type = value; }\n        }\n\n        public bool HasFields\n        {\n            get { return !Mixin.IsNullOrEmpty(fields); }\n        }\n\n        public Collection<CustomAttributeNamedArgument> Fields\n        {\n            get { return fields ?? (fields = new Collection<CustomAttributeNamedArgument>()); }\n        }\n\n        public bool HasProperties\n        {\n            get { return !Mixin.IsNullOrEmpty(properties); }\n        }\n\n        public Collection<CustomAttributeNamedArgument> Properties\n        {\n            get { return properties ?? (properties = new Collection<CustomAttributeNamedArgument>()); }\n        }\n\n        public SecurityAttribute(TypeReference attributeType)\n        {\n            this.attribute_type = attributeType;\n        }\n    }\n\n    public sealed class SecurityDeclaration\n    {\n\n        readonly internal uint signature;\n        byte[] blob;\n        readonly ModuleDefinition module;\n\n        internal bool resolved;\n        SecurityAction action;\n        internal Collection<SecurityAttribute> security_attributes;\n\n        public SecurityAction Action\n        {\n            get { return action; }\n            set { action = value; }\n        }\n\n        public bool HasSecurityAttributes\n        {\n            get\n            {\n                Resolve();\n\n                return !Mixin.IsNullOrEmpty(security_attributes);\n            }\n        }\n\n        public Collection<SecurityAttribute> SecurityAttributes\n        {\n            get\n            {\n                Resolve();\n\n                return security_attributes ?? (security_attributes = new Collection<SecurityAttribute>());\n            }\n        }\n\n        internal bool HasImage\n        {\n            get { return module != null && module.HasImage; }\n        }\n\n        internal SecurityDeclaration(SecurityAction action, uint signature, ModuleDefinition module)\n        {\n            this.action = action;\n            this.signature = signature;\n            this.module = module;\n        }\n\n        public SecurityDeclaration(SecurityAction action)\n        {\n            this.action = action;\n            this.resolved = true;\n        }\n\n        public SecurityDeclaration(SecurityAction action, byte[] blob)\n        {\n            this.action = action;\n            this.resolved = false;\n            this.blob = blob;\n        }\n\n        public byte[] GetBlob()\n        {\n            if (blob != null)\n                return blob;\n\n            if (!HasImage || signature == 0)\n                throw new NotSupportedException();\n\n            return blob = module.Read(this, (declaration, reader) => reader.ReadSecurityDeclarationBlob(declaration.signature));\n        }\n\n        void Resolve()\n        {\n            if (resolved || !HasImage)\n                return;\n\n            module.Read(this, (declaration, reader) =>\n            {\n                reader.ReadSecurityDeclarationSignature(declaration);\n                return this;\n            });\n\n            resolved = true;\n        }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool GetHasSecurityDeclarations(\n            ISecurityDeclarationProvider self,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module) && module.Read(self, (provider, reader) => reader.HasSecurityDeclarations(provider));\n        }\n\n        public static Collection<SecurityDeclaration> GetSecurityDeclarations(\n            ISecurityDeclarationProvider self,\n            ref Collection<SecurityDeclaration> variable,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module)\n                ? module.Read(ref variable, self, (provider, reader) => reader.ReadSecurityDeclarations(provider))\n                : variable = new Collection<SecurityDeclaration>();\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/SentinelType.cs",
    "content": "//\n// SentinelType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class SentinelType : TypeSpecification {\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsSentinel {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic SentinelType (TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.etype = MD.ElementType.Sentinel;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/TargetRuntime.cs",
    "content": "//\n// TargetRuntime.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum TargetRuntime {\n\t\tNet_1_0,\n\t\tNet_1_1,\n\t\tNet_2_0,\n\t\tNet_4_0,\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeAttributes.cs",
    "content": "//\n// TypeAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum TypeAttributes : uint {\n\t\t// Visibility attributes\n\t\tVisibilityMask\t\t= 0x00000007,\t// Use this mask to retrieve visibility information\n\t\tNotPublic\t\t\t= 0x00000000,\t// Class has no public scope\n\t\tPublic\t\t\t\t= 0x00000001,\t// Class has public scope\n\t\tNestedPublic\t\t= 0x00000002,\t// Class is nested with public visibility\n\t\tNestedPrivate\t\t= 0x00000003,\t// Class is nested with private visibility\n\t\tNestedFamily\t\t= 0x00000004,\t// Class is nested with family visibility\n\t\tNestedAssembly\t\t= 0x00000005,\t// Class is nested with assembly visibility\n\t\tNestedFamANDAssem\t= 0x00000006,\t// Class is nested with family and assembly visibility\n\t\tNestedFamORAssem\t= 0x00000007,\t// Class is nested with family or assembly visibility\n\n\t\t// Class layout attributes\n\t\tLayoutMask\t\t\t= 0x00000018,\t// Use this mask to retrieve class layout information\n\t\tAutoLayout\t\t\t= 0x00000000,\t// Class fields are auto-laid out\n\t\tSequentialLayout\t= 0x00000008,\t// Class fields are laid out sequentially\n\t\tExplicitLayout\t\t= 0x00000010,\t// Layout is supplied explicitly\n\n\t\t// Class semantics attributes\n\t\tClassSemanticMask\t= 0x00000020,\t// Use this mask to retrieve class semantics information\n\t\tClass\t\t\t\t= 0x00000000,\t// Type is a class\n\t\tInterface\t\t\t= 0x00000020,\t// Type is an interface\n\n\t\t// Special semantics in addition to class semantics\n\t\tAbstract\t\t\t= 0x00000080,\t// Class is abstract\n\t\tSealed\t\t\t\t= 0x00000100,\t// Class cannot be extended\n\t\tSpecialName\t\t\t= 0x00000400,\t// Class name is special\n\n\t\t// Implementation attributes\n\t\tImport\t\t\t\t= 0x00001000,\t// Class/Interface is imported\n\t\tSerializable\t\t= 0x00002000,\t// Class is serializable\n\t\tWindowsRuntime\t\t= 0x00004000,\t// Windows Runtime type\n\n\t\t// String formatting attributes\n\t\tStringFormatMask\t= 0x00030000,\t// Use this mask to retrieve string information for native interop\n\t\tAnsiClass\t\t\t= 0x00000000,\t// LPSTR is interpreted as ANSI\n\t\tUnicodeClass\t\t= 0x00010000,\t// LPSTR is interpreted as Unicode\n\t\tAutoClass\t\t\t= 0x00020000,\t// LPSTR is interpreted automatically\n\n\t\t// Class initialization attributes\n\t\tBeforeFieldInit\t\t= 0x00100000,\t// Initialize the class before first static field access\n\n\t\t// Additional flags\n\t\tRTSpecialName\t\t= 0x00000800,\t// CLI provides 'special' behavior, depending upon the name of the Type\n\t\tHasSecurity\t\t\t= 0x00040000,\t// Type has security associate with it\n\t\tForwarder\t\t\t= 0x00200000,   // Exported type is a type forwarder\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeDefinition.cs",
    "content": "//\n// TypeDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.Metadata;\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class TypeDefinition : TypeReference, IMemberDefinition, ISecurityDeclarationProvider\n    {\n\n        uint attributes;\n        TypeReference base_type;\n        internal Range fields_range;\n        internal Range methods_range;\n\n        short packing_size = Mixin.NotResolvedMarker;\n        int class_size = Mixin.NotResolvedMarker;\n\n        Collection<TypeReference> interfaces;\n        Collection<TypeDefinition> nested_types;\n        Collection<MethodDefinition> methods;\n        Collection<FieldDefinition> fields;\n        Collection<EventDefinition> events;\n        Collection<PropertyDefinition> properties;\n        Collection<CustomAttribute> custom_attributes;\n        Collection<SecurityDeclaration> security_declarations;\n\n        public TypeAttributes Attributes\n        {\n            get { return (TypeAttributes)attributes; }\n            set { attributes = (uint)value; }\n        }\n\n        public TypeReference BaseType\n        {\n            get { return base_type; }\n            set { base_type = value; }\n        }\n\n        void ResolveLayout()\n        {\n            if (packing_size != Mixin.NotResolvedMarker || class_size != Mixin.NotResolvedMarker)\n                return;\n\n            if (!HasImage)\n            {\n                packing_size = Mixin.NoDataMarker;\n                class_size = Mixin.NoDataMarker;\n                return;\n            }\n\n            var row = Module.Read(this, (type, reader) => reader.ReadTypeLayout(type));\n\n            packing_size = row.Col1;\n            class_size = row.Col2;\n        }\n\n        public bool HasLayoutInfo\n        {\n            get\n            {\n                if (packing_size >= 0 || class_size >= 0)\n                    return true;\n\n                ResolveLayout();\n\n                return packing_size >= 0 || class_size >= 0;\n            }\n        }\n\n        public short PackingSize\n        {\n            get\n            {\n                if (packing_size >= 0)\n                    return packing_size;\n\n                ResolveLayout();\n\n                return packing_size >= 0 ? packing_size : (short)-1;\n            }\n            set { packing_size = value; }\n        }\n\n        public int ClassSize\n        {\n            get\n            {\n                if (class_size >= 0)\n                    return class_size;\n\n                ResolveLayout();\n\n                return class_size >= 0 ? class_size : -1;\n            }\n            set { class_size = value; }\n        }\n\n        public bool HasInterfaces\n        {\n            get\n            {\n                if (interfaces != null)\n                    return interfaces.Count > 0;\n\n                if (HasImage)\n                    return Module.Read(this, (type, reader) => reader.HasInterfaces(type));\n\n                return false;\n            }\n        }\n\n        public Collection<TypeReference> Interfaces\n        {\n            get\n            {\n                if (interfaces != null)\n                    return interfaces;\n\n                if (HasImage)\n                    return Module.Read(ref interfaces, this, (type, reader) => reader.ReadInterfaces(type));\n\n                return interfaces = new Collection<TypeReference>();\n            }\n        }\n\n        public bool HasNestedTypes\n        {\n            get\n            {\n                if (nested_types != null)\n                    return nested_types.Count > 0;\n\n                if (HasImage)\n                    return Module.Read(this, (type, reader) => reader.HasNestedTypes(type));\n\n                return false;\n            }\n        }\n\n        public Collection<TypeDefinition> NestedTypes\n        {\n            get\n            {\n                if (nested_types != null)\n                    return nested_types;\n\n                if (HasImage)\n                    return Module.Read(ref nested_types, this, (type, reader) => reader.ReadNestedTypes(type));\n\n                return nested_types = new MemberDefinitionCollection<TypeDefinition>(this);\n            }\n        }\n\n        public bool HasMethods\n        {\n            get\n            {\n                if (methods != null)\n                    return methods.Count > 0;\n\n                if (HasImage)\n                    return methods_range.Length > 0;\n\n                return false;\n            }\n        }\n\n        public Collection<MethodDefinition> Methods\n        {\n            get\n            {\n                if (methods != null)\n                    return methods;\n\n                if (HasImage)\n                    return Module.Read(ref methods, this, (type, reader) => reader.ReadMethods(type));\n\n                return methods = new MemberDefinitionCollection<MethodDefinition>(this);\n            }\n        }\n\n        public bool HasFields\n        {\n            get\n            {\n                if (fields != null)\n                    return fields.Count > 0;\n\n                if (HasImage)\n                    return fields_range.Length > 0;\n\n                return false;\n            }\n        }\n\n        public Collection<FieldDefinition> Fields\n        {\n            get\n            {\n                if (fields != null)\n                    return fields;\n\n                if (HasImage)\n                    return Module.Read(ref fields, this, (type, reader) => reader.ReadFields(type));\n\n                return fields = new MemberDefinitionCollection<FieldDefinition>(this);\n            }\n        }\n\n        public bool HasEvents\n        {\n            get\n            {\n                if (events != null)\n                    return events.Count > 0;\n\n                if (HasImage)\n                    return Module.Read(this, (type, reader) => reader.HasEvents(type));\n\n                return false;\n            }\n        }\n\n        public Collection<EventDefinition> Events\n        {\n            get\n            {\n                if (events != null)\n                    return events;\n\n                if (HasImage)\n                    return Module.Read(ref events, this, (type, reader) => reader.ReadEvents(type));\n\n                return events = new MemberDefinitionCollection<EventDefinition>(this);\n            }\n        }\n\n        public bool HasProperties\n        {\n            get\n            {\n                if (properties != null)\n                    return properties.Count > 0;\n\n                if (HasImage)\n                    return Module.Read(this, (type, reader) => reader.HasProperties(type));\n\n                return false;\n            }\n        }\n\n        public Collection<PropertyDefinition> Properties\n        {\n            get\n            {\n                if (properties != null)\n                    return properties;\n\n                if (HasImage)\n                    return Module.Read(ref properties, this, (type, reader) => reader.ReadProperties(type));\n\n                return properties = new MemberDefinitionCollection<PropertyDefinition>(this);\n            }\n        }\n\n        public bool HasSecurityDeclarations\n        {\n            get\n            {\n                if (security_declarations != null)\n                    return security_declarations.Count > 0;\n\n                return Mixin.GetHasSecurityDeclarations(this, Module);\n            }\n        }\n\n        public Collection<SecurityDeclaration> SecurityDeclarations\n        {\n            get { return security_declarations ?? (Mixin.GetSecurityDeclarations(this, ref security_declarations, Module)); }\n        }\n\n        public bool HasCustomAttributes\n        {\n            get\n            {\n                if (custom_attributes != null)\n                    return custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n            }\n        }\n\n        public Collection<CustomAttribute> CustomAttributes\n        {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n        }\n\n        public override bool HasGenericParameters\n        {\n            get\n            {\n                if (generic_parameters != null)\n                    return generic_parameters.Count > 0;\n\n                return Mixin.GetHasGenericParameters(this, Module);\n            }\n        }\n\n        public override Collection<GenericParameter> GenericParameters\n        {\n            get { return generic_parameters ?? (Mixin.GetGenericParameters(this,ref generic_parameters, Module)); }\n        }\n\n        #region TypeAttributes\n\n        public bool IsNotPublic\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NotPublic); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NotPublic, value); }\n        }\n\n        public bool IsPublic\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.Public); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.Public, value); }\n        }\n\n        public bool IsNestedPublic\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedPublic); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedPublic, value); }\n        }\n\n        public bool IsNestedPrivate\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedPrivate); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedPrivate, value); }\n        }\n\n        public bool IsNestedFamily\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamily); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamily, value); }\n        }\n\n        public bool IsNestedAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedAssembly); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedAssembly, value); }\n        }\n\n        public bool IsNestedFamilyAndAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamANDAssem); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamANDAssem, value); }\n        }\n\n        public bool IsNestedFamilyOrAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamORAssem); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamORAssem, value); }\n        }\n\n        public bool IsAutoLayout\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.AutoLayout); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.AutoLayout, value); }\n        }\n\n        public bool IsSequentialLayout\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.SequentialLayout); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.SequentialLayout, value); }\n        }\n\n        public bool IsExplicitLayout\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.ExplicitLayout); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.ExplicitLayout, value); }\n        }\n\n        public bool IsClass\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.ClassSemanticMask, (uint)TypeAttributes.Class); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.ClassSemanticMask, (uint)TypeAttributes.Class, value); }\n        }\n\n        public bool IsInterface\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.ClassSemanticMask, (uint)TypeAttributes.Interface); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.ClassSemanticMask, (uint)TypeAttributes.Interface, value); }\n        }\n\n        public bool IsAbstract\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.Abstract); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.Abstract, value); }\n        }\n\n        public bool IsSealed\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.Sealed); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.Sealed, value); }\n        }\n\n        public bool IsSpecialName\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.SpecialName); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.SpecialName, value); }\n        }\n\n        public bool IsImport\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.Import); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.Import, value); }\n        }\n\n        public bool IsSerializable\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.Serializable); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.Serializable, value); }\n        }\n\n        public bool IsWindowsRuntime\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.WindowsRuntime); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.WindowsRuntime, value); }\n        }\n\n        public bool IsAnsiClass\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.AnsiClass); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.AnsiClass, value); }\n        }\n\n        public bool IsUnicodeClass\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.UnicodeClass); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.UnicodeClass, value); }\n        }\n\n        public bool IsAutoClass\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.AutoClass); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.AutoClass, value); }\n        }\n\n        public bool IsBeforeFieldInit\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.BeforeFieldInit); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.BeforeFieldInit, value); }\n        }\n\n        public bool IsRuntimeSpecialName\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.RTSpecialName); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.RTSpecialName, value); }\n        }\n\n        public bool HasSecurity\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.HasSecurity); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.HasSecurity, value); }\n        }\n\n        #endregion\n\n        public bool IsEnum\n        {\n            get { return base_type != null && Mixin.IsTypeOf(base_type, \"System\", \"Enum\"); }\n        }\n\n        public override bool IsValueType\n        {\n            get\n            {\n                if (base_type == null)\n                    return false;\n\n                return Mixin.IsTypeOf(base_type, \"System\", \"Enum\") || (Mixin.IsTypeOf(base_type, \"System\", \"ValueType\") && !Mixin.IsTypeOf(this, \"System\", \"Enum\"));\n            }\n        }\n\n        public override bool IsPrimitive\n        {\n            get\n            {\n                ElementType primitive_etype;\n                return MetadataSystem.TryGetPrimitiveElementType(this, out primitive_etype);\n            }\n        }\n\n        public override MetadataType MetadataType\n        {\n            get\n            {\n                ElementType primitive_etype;\n                if (MetadataSystem.TryGetPrimitiveElementType(this, out primitive_etype))\n                    return (MetadataType)primitive_etype;\n\n                return base.MetadataType;\n            }\n        }\n\n        public override bool IsDefinition\n        {\n            get { return true; }\n        }\n\n        public new TypeDefinition DeclaringType\n        {\n            get { return (TypeDefinition)base.DeclaringType; }\n            set { base.DeclaringType = value; }\n        }\n\n        public TypeDefinition(string @namespace, string name, TypeAttributes attributes)\n            : base(@namespace, name)\n        {\n            this.attributes = (uint)attributes;\n            this.token = new MetadataToken(TokenType.TypeDef);\n        }\n\n        public TypeDefinition(string @namespace, string name, TypeAttributes attributes, TypeReference baseType) :\n            this(@namespace, name, attributes)\n        {\n            this.BaseType = baseType;\n        }\n\n        public override TypeDefinition Resolve()\n        {\n            return this;\n        }\n    }\n\n    static partial class Mixin\n    {\n\n        public static TypeReference GetEnumUnderlyingType(TypeDefinition self)\n        {\n            var fields = self.Fields;\n\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var field = fields[i];\n                if (!field.IsStatic)\n                    return field.FieldType;\n            }\n\n            throw new ArgumentException();\n        }\n\n        public static TypeDefinition GetNestedType(TypeDefinition self, string name)\n        {\n            if (!self.HasNestedTypes)\n                return null;\n\n            var nested_types = self.NestedTypes;\n\n            for (int i = 0; i < nested_types.Count; i++)\n            {\n                var nested_type = nested_types[i];\n                if (nested_type.Name == name)\n                    return nested_type;\n            }\n\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeDefinitionCollection.cs",
    "content": "//\n// TypeDefinitionCollection.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\n\nusing Mono.Cecil.Metadata;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tusing Slot = Row<string, string>;\n\n\tsealed class TypeDefinitionCollection : Collection<TypeDefinition> {\n\n\t\treadonly ModuleDefinition container;\n\t\treadonly Dictionary<Slot, TypeDefinition> name_cache;\n\n\t\tinternal TypeDefinitionCollection (ModuleDefinition container)\n\t\t{\n\t\t\tthis.container = container;\n\t\t\tthis.name_cache = new Dictionary<Slot, TypeDefinition> (new RowEqualityComparer ());\n\t\t}\n\n\t\tinternal TypeDefinitionCollection (ModuleDefinition container, int capacity)\n\t\t\t: base (capacity)\n\t\t{\n\t\t\tthis.container = container;\n\t\t\tthis.name_cache = new Dictionary<Slot, TypeDefinition> (capacity, new RowEqualityComparer ());\n\t\t}\n\n\t\tprotected override void OnAdd (TypeDefinition item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected override void OnSet (TypeDefinition item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected override void OnInsert (TypeDefinition item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected override void OnRemove (TypeDefinition item, int index)\n\t\t{\n\t\t\tDetach (item);\n\t\t}\n\n\t\tprotected override void OnClear ()\n\t\t{\n\t\t\tforeach (var type in this)\n\t\t\t\tDetach (type);\n\t\t}\n\n\t\tvoid Attach (TypeDefinition type)\n\t\t{\n\t\t\tif (type.Module != null && type.Module != container)\n\t\t\t\tthrow new ArgumentException (\"Type already attached\");\n\n\t\t\ttype.module = container;\n\t\t\ttype.scope = container;\n\t\t\tname_cache [new Slot (type.Namespace, type.Name)] = type;\n\t\t}\n\n\t\tvoid Detach (TypeDefinition type)\n\t\t{\n\t\t\ttype.module = null;\n\t\t\ttype.scope = null;\n\t\t\tname_cache.Remove (new Slot (type.Namespace, type.Name));\n\t\t}\n\n\t\tpublic TypeDefinition GetType (string fullname)\n\t\t{\n\t\t\tstring @namespace, name;\n\t\t\tTypeParser.SplitFullName (fullname, out @namespace, out name);\n\n\t\t\treturn GetType (@namespace, name);\n\t\t}\n\n\t\tpublic TypeDefinition GetType (string @namespace, string name)\n\t\t{\n\t\t\tTypeDefinition type;\n\t\t\tif (name_cache.TryGetValue (new Slot (@namespace, name), out type))\n\t\t\t\treturn type;\n\n\t\t\treturn null;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeParser.cs",
    "content": "//\n// TypeParser.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil\n{\n\n    class TypeParser\n    {\n\n        class Type\n        {\n            public const int Ptr = -1;\n            public const int ByRef = -2;\n            public const int SzArray = -3;\n\n            public string type_fullname;\n            public string[] nested_names;\n            public int arity;\n            public int[] specs;\n            public Type[] generic_arguments;\n            public string assembly;\n        }\n\n        readonly string fullname;\n        readonly int length;\n\n        int position;\n\n        TypeParser(string fullname)\n        {\n            this.fullname = fullname;\n            this.length = fullname.Length;\n        }\n\n        Type ParseType(bool fq_name)\n        {\n            var type = new Type();\n            type.type_fullname = ParsePart();\n\n            type.nested_names = ParseNestedNames();\n\n            if (TryGetArity(type))\n                type.generic_arguments = ParseGenericArguments(type.arity);\n\n            type.specs = ParseSpecs();\n\n            if (fq_name)\n                type.assembly = ParseAssemblyName();\n\n            return type;\n        }\n\n        static bool TryGetArity(Type type)\n        {\n            int arity = 0;\n\n            TryAddArity(type.type_fullname, ref arity);\n\n            var nested_names = type.nested_names;\n            if (!Mixin.IsNullOrEmpty(nested_names))\n            {\n                for (int i = 0; i < nested_names.Length; i++)\n                    TryAddArity(nested_names[i], ref arity);\n            }\n\n            type.arity = arity;\n            return arity > 0;\n        }\n\n        static bool TryGetArity(string name, out int arity)\n        {\n            arity = 0;\n            var index = name.LastIndexOf('`');\n            if (index == -1)\n                return false;\n\n            return ParseInt32(name.Substring(index + 1), out arity);\n        }\n\n        static bool ParseInt32(string value, out int result)\n        {\n#if CF\n\t\t\ttry {\n\t\t\t\tresult = int.Parse (value);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\tresult = 0;\n\t\t\t\treturn false;\n\t\t\t}\n#else\n            return int.TryParse(value, out result);\n#endif\n        }\n\n        static void TryAddArity(string name, ref int arity)\n        {\n            int type_arity;\n            if (!TryGetArity(name, out type_arity))\n                return;\n\n            arity += type_arity;\n        }\n\n        string ParsePart()\n        {\n            int start = position;\n            while (position < length && !IsDelimiter(fullname[position]))\n                position++;\n\n            return fullname.Substring(start, position - start);\n        }\n\n        static bool IsDelimiter(char chr)\n        {\n            return \"+,[]*&\".IndexOf(chr) != -1;\n        }\n\n        void TryParseWhiteSpace()\n        {\n            while (position < length && Char.IsWhiteSpace(fullname[position]))\n                position++;\n        }\n\n        string[] ParseNestedNames()\n        {\n            string[] nested_names = null;\n            while (TryParse('+'))\n                Add(ref nested_names, ParsePart());\n\n            return nested_names;\n        }\n\n        bool TryParse(char chr)\n        {\n            if (position < length && fullname[position] == chr)\n            {\n                position++;\n                return true;\n            }\n\n            return false;\n        }\n\n        static void Add<T>(ref T[] array, T item)\n        {\n            if (array == null)\n            {\n                array = new[] { item };\n                return;\n            }\n\n#if !CF\n            Array.Resize(ref array, array.Length + 1);\n#else\n\t\t\tvar copy = new T [array.Length + 1];\n\t\t\tArray.Copy (array, copy, array.Length);\n\t\t\tarray = copy;\n#endif\n            array[array.Length - 1] = item;\n        }\n\n        int[] ParseSpecs()\n        {\n            int[] specs = null;\n\n            while (position < length)\n            {\n                switch (fullname[position])\n                {\n                    case '*':\n                        position++;\n                        Add(ref specs, Type.Ptr);\n                        break;\n                    case '&':\n                        position++;\n                        Add(ref specs, Type.ByRef);\n                        break;\n                    case '[':\n                        position++;\n                        switch (fullname[position])\n                        {\n                            case ']':\n                                position++;\n                                Add(ref specs, Type.SzArray);\n                                break;\n                            case '*':\n                                position++;\n                                Add(ref specs, 1);\n                                break;\n                            default:\n                                var rank = 1;\n                                while (TryParse(','))\n                                    rank++;\n\n                                Add(ref specs, rank);\n\n                                TryParse(']');\n                                break;\n                        }\n                        break;\n                    default:\n                        return specs;\n                }\n            }\n\n            return specs;\n        }\n\n        Type[] ParseGenericArguments(int arity)\n        {\n            Type[] generic_arguments = null;\n\n            if (position == length || fullname[position] != '[')\n                return generic_arguments;\n\n            TryParse('[');\n\n            for (int i = 0; i < arity; i++)\n            {\n                var fq_argument = TryParse('[');\n                Add(ref generic_arguments, ParseType(fq_argument));\n                if (fq_argument)\n                    TryParse(']');\n\n                TryParse(',');\n                TryParseWhiteSpace();\n            }\n\n            TryParse(']');\n\n            return generic_arguments;\n        }\n\n        string ParseAssemblyName()\n        {\n            if (!TryParse(','))\n                return string.Empty;\n\n            TryParseWhiteSpace();\n\n            var start = position;\n            while (position < length)\n            {\n                var chr = fullname[position];\n                if (chr == '[' || chr == ']')\n                    break;\n\n                position++;\n            }\n\n            return fullname.Substring(start, position - start);\n        }\n\n        public static TypeReference ParseType(ModuleDefinition module, string fullname)\n        {\n            if (string.IsNullOrEmpty(fullname))\n                return null;\n\n            var parser = new TypeParser(fullname);\n            return GetTypeReference(module, parser.ParseType(true));\n        }\n\n        static TypeReference GetTypeReference(ModuleDefinition module, Type type_info)\n        {\n            TypeReference type;\n            if (!TryGetDefinition(module, type_info, out type))\n                type = CreateReference(type_info, module, GetMetadataScope(module, type_info));\n\n            return CreateSpecs(type, type_info);\n        }\n\n        static TypeReference CreateSpecs(TypeReference type, Type type_info)\n        {\n            type = TryCreateGenericInstanceType(type, type_info);\n\n            var specs = type_info.specs;\n            if (Mixin.IsNullOrEmpty(specs))\n                return type;\n\n            for (int i = 0; i < specs.Length; i++)\n            {\n                switch (specs[i])\n                {\n                    case Type.Ptr:\n                        type = new PointerType(type);\n                        break;\n                    case Type.ByRef:\n                        type = new ByReferenceType(type);\n                        break;\n                    case Type.SzArray:\n                        type = new ArrayType(type);\n                        break;\n                    default:\n                        var array = new ArrayType(type);\n                        array.Dimensions.Clear();\n\n                        for (int j = 0; j < specs[i]; j++)\n                            array.Dimensions.Add(new ArrayDimension());\n\n                        type = array;\n                        break;\n                }\n            }\n\n            return type;\n        }\n\n        static TypeReference TryCreateGenericInstanceType(TypeReference type, Type type_info)\n        {\n            var generic_arguments = type_info.generic_arguments;\n            if (Mixin.IsNullOrEmpty(generic_arguments))\n                return type;\n\n            var instance = new GenericInstanceType(type);\n            var instance_arguments = instance.GenericArguments;\n\n            for (int i = 0; i < generic_arguments.Length; i++)\n                instance_arguments.Add(GetTypeReference(type.Module, generic_arguments[i]));\n\n            return instance;\n        }\n\n        public static void SplitFullName(string fullname, out string @namespace, out string name)\n        {\n            var last_dot = fullname.LastIndexOf('.');\n\n            if (last_dot == -1)\n            {\n                @namespace = string.Empty;\n                name = fullname;\n            }\n            else\n            {\n                @namespace = fullname.Substring(0, last_dot);\n                name = fullname.Substring(last_dot + 1);\n            }\n        }\n\n        static TypeReference CreateReference(Type type_info, ModuleDefinition module, IMetadataScope scope)\n        {\n            string @namespace, name;\n            SplitFullName(type_info.type_fullname, out @namespace, out name);\n\n            var type = new TypeReference(@namespace, name, module, scope);\n            MetadataSystem.TryProcessPrimitiveTypeReference(type);\n\n            AdjustGenericParameters(type);\n\n            var nested_names = type_info.nested_names;\n            if (Mixin.IsNullOrEmpty(nested_names))\n                return type;\n\n            for (int i = 0; i < nested_names.Length; i++)\n            {\n                type = new TypeReference(string.Empty, nested_names[i], module, null)\n                {\n                    DeclaringType = type,\n                };\n\n                AdjustGenericParameters(type);\n            }\n\n            return type;\n        }\n\n        static void AdjustGenericParameters(TypeReference type)\n        {\n            int arity;\n            if (!TryGetArity(type.Name, out arity))\n                return;\n\n            for (int i = 0; i < arity; i++)\n                type.GenericParameters.Add(new GenericParameter(type));\n        }\n\n        static IMetadataScope GetMetadataScope(ModuleDefinition module, Type type_info)\n        {\n            if (string.IsNullOrEmpty(type_info.assembly))\n                return module.TypeSystem.Corlib;\n\n            return MatchReference(module, AssemblyNameReference.Parse(type_info.assembly));\n        }\n\n        static AssemblyNameReference MatchReference(ModuleDefinition module, AssemblyNameReference pattern)\n        {\n            var references = module.AssemblyReferences;\n\n            for (int i = 0; i < references.Count; i++)\n            {\n                var reference = references[i];\n                if (reference.FullName == pattern.FullName)\n                    return reference;\n            }\n\n            return pattern;\n        }\n\n        static bool TryGetDefinition(ModuleDefinition module, Type type_info, out TypeReference type)\n        {\n            type = null;\n            if (!TryCurrentModule(module, type_info))\n                return false;\n\n            var typedef = module.GetType(type_info.type_fullname);\n            if (typedef == null)\n                return false;\n\n            var nested_names = type_info.nested_names;\n            if (!Mixin.IsNullOrEmpty(nested_names))\n            {\n                for (int i = 0; i < nested_names.Length; i++)\n                    typedef = Mixin.GetNestedType(typedef, nested_names[i]);\n            }\n\n            type = typedef;\n            return true;\n        }\n\n        static bool TryCurrentModule(ModuleDefinition module, Type type_info)\n        {\n            if (string.IsNullOrEmpty(type_info.assembly))\n                return true;\n\n            if (module.assembly != null && module.assembly.Name.FullName == type_info.assembly)\n                return true;\n\n            return false;\n        }\n\n        public static string ToParseable(TypeReference type)\n        {\n            if (type == null)\n                return null;\n\n            var name = new StringBuilder();\n            AppendType(type, name, true, true);\n            return name.ToString();\n        }\n\n        static void AppendType(TypeReference type, StringBuilder name, bool fq_name, bool top_level)\n        {\n            var declaring_type = type.DeclaringType;\n            if (declaring_type != null)\n            {\n                AppendType(declaring_type, name, false, top_level);\n                name.Append('+');\n            }\n\n            var @namespace = type.Namespace;\n            if (!string.IsNullOrEmpty(@namespace))\n            {\n                name.Append(@namespace);\n                name.Append('.');\n            }\n\n            name.Append(type.GetElementType().Name);\n\n            if (!fq_name)\n                return;\n\n            if (Mixin.IsTypeSpecification(type))\n                AppendTypeSpecification((TypeSpecification)type, name);\n\n            if (RequiresFullyQualifiedName(type, top_level))\n            {\n                name.Append(\", \");\n                name.Append(GetScopeFullName(type));\n            }\n        }\n\n        static string GetScopeFullName(TypeReference type)\n        {\n            var scope = type.Scope;\n            switch (scope.MetadataScopeType)\n            {\n                case MetadataScopeType.AssemblyNameReference:\n                    return ((AssemblyNameReference)scope).FullName;\n                case MetadataScopeType.ModuleDefinition:\n                    return ((ModuleDefinition)scope).Assembly.Name.FullName;\n            }\n\n            throw new ArgumentException();\n        }\n\n        static void AppendTypeSpecification(TypeSpecification type, StringBuilder name)\n        {\n            if (Mixin.IsTypeSpecification(type.ElementType))\n                AppendTypeSpecification((TypeSpecification)type.ElementType, name);\n\n            switch (type.etype)\n            {\n                case ElementType.Ptr:\n                    name.Append('*');\n                    break;\n                case ElementType.ByRef:\n                    name.Append('&');\n                    break;\n                case ElementType.SzArray:\n                case ElementType.Array:\n                    var array = (ArrayType)type;\n                    if (array.IsVector)\n                    {\n                        name.Append(\"[]\");\n                    }\n                    else\n                    {\n                        name.Append('[');\n                        for (int i = 1; i < array.Rank; i++)\n                            name.Append(',');\n                        name.Append(']');\n                    }\n                    break;\n                case ElementType.GenericInst:\n                    var instance = (GenericInstanceType)type;\n                    var arguments = instance.GenericArguments;\n\n                    name.Append('[');\n\n                    for (int i = 0; i < arguments.Count; i++)\n                    {\n                        if (i > 0)\n                            name.Append(',');\n\n                        var argument = arguments[i];\n                        var requires_fqname = argument.Scope != argument.Module;\n\n                        if (requires_fqname)\n                            name.Append('[');\n\n                        AppendType(argument, name, true, false);\n\n                        if (requires_fqname)\n                            name.Append(']');\n                    }\n\n                    name.Append(']');\n                    break;\n                default:\n                    return;\n            }\n        }\n\n        static bool RequiresFullyQualifiedName(TypeReference type, bool top_level)\n        {\n            if (type.Scope == type.Module)\n                return false;\n\n            if (type.Scope.Name == \"mscorlib\" && top_level)\n                return false;\n\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeReference.cs",
    "content": "//\n// TypeReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.Metadata;\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public enum MetadataType : byte\n    {\n        Void = ElementType.Void,\n        Boolean = ElementType.Boolean,\n        Char = ElementType.Char,\n        SByte = ElementType.I1,\n        Byte = ElementType.U1,\n        Int16 = ElementType.I2,\n        UInt16 = ElementType.U2,\n        Int32 = ElementType.I4,\n        UInt32 = ElementType.U4,\n        Int64 = ElementType.I8,\n        UInt64 = ElementType.U8,\n        Single = ElementType.R4,\n        Double = ElementType.R8,\n        String = ElementType.String,\n        Pointer = ElementType.Ptr,\n        ByReference = ElementType.ByRef,\n        ValueType = ElementType.ValueType,\n        Class = ElementType.Class,\n        Var = ElementType.Var,\n        Array = ElementType.Array,\n        GenericInstance = ElementType.GenericInst,\n        TypedByReference = ElementType.TypedByRef,\n        IntPtr = ElementType.I,\n        UIntPtr = ElementType.U,\n        FunctionPointer = ElementType.FnPtr,\n        Object = ElementType.Object,\n        MVar = ElementType.MVar,\n        RequiredModifier = ElementType.CModReqD,\n        OptionalModifier = ElementType.CModOpt,\n        Sentinel = ElementType.Sentinel,\n        Pinned = ElementType.Pinned,\n    }\n\n    public class TypeReference : MemberReference, IGenericParameterProvider, IGenericContext\n    {\n\n        string @namespace;\n        bool value_type;\n        int hashCode = -1;\n        static int instance_id;\n        internal IMetadataScope scope;\n        internal ModuleDefinition module;\n\n        internal ElementType etype = ElementType.None;\n\n        string fullname;\n\n        protected Collection<GenericParameter> generic_parameters;\n\n        public override string Name\n        {\n            get { return base.Name; }\n            set\n            {\n                base.Name = value;\n                fullname = null;\n            }\n        }\n\n        public virtual string Namespace\n        {\n            get { return @namespace; }\n            set\n            {\n                @namespace = value;\n                fullname = null;\n            }\n        }\n\n        public virtual bool IsValueType\n        {\n            get { return value_type; }\n            set { value_type = value; }\n        }\n\n        public override ModuleDefinition Module\n        {\n            get\n            {\n                if (module != null)\n                    return module;\n\n                var declaring_type = this.DeclaringType;\n                if (declaring_type != null)\n                    return declaring_type.Module;\n\n                return null;\n            }\n        }\n\n        IGenericParameterProvider IGenericContext.Type\n        {\n            get { return this; }\n        }\n\n        IGenericParameterProvider IGenericContext.Method\n        {\n            get { return null; }\n        }\n\n        GenericParameterType IGenericParameterProvider.GenericParameterType\n        {\n            get { return GenericParameterType.Type; }\n        }\n\n        public virtual bool HasGenericParameters\n        {\n            get { return !Mixin.IsNullOrEmpty(generic_parameters); }\n        }\n\n        public virtual Collection<GenericParameter> GenericParameters\n        {\n            get\n            {\n                if (generic_parameters != null)\n                    return generic_parameters;\n\n                return generic_parameters = new GenericParameterCollection(this);\n            }\n        }\n\n        public virtual IMetadataScope Scope\n        {\n            get\n            {\n                var declaring_type = this.DeclaringType;\n                if (declaring_type != null)\n                    return declaring_type.Scope;\n\n                return scope;\n            }\n        }\n\n        public bool IsNested\n        {\n            get { return this.DeclaringType != null; }\n        }\n\n        public override TypeReference DeclaringType\n        {\n            get { return base.DeclaringType; }\n            set\n            {\n                base.DeclaringType = value;\n                fullname = null;\n            }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                if (fullname != null)\n                    return fullname;\n\n                if (IsNested)\n                    return fullname = DeclaringType.FullName + \"/\" + Name;\n\n                if (string.IsNullOrEmpty(@namespace))\n                    return fullname = Name;\n\n                return fullname = @namespace + \".\" + Name;\n            }\n        }\n\n        public virtual bool IsByReference\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsPointer\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsSentinel\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsArray\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsGenericParameter\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsGenericInstance\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsRequiredModifier\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsOptionalModifier\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsPinned\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsFunctionPointer\n        {\n            get { return false; }\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n        public virtual bool IsPrimitive\n        {\n            get { return Mixin.IsPrimitive(etype); }\n        }\n\n        public virtual MetadataType MetadataType\n        {\n            get\n            {\n                switch (etype)\n                {\n                    case ElementType.None:\n                        return IsValueType ? MetadataType.ValueType : MetadataType.Class;\n                    default:\n                        return (MetadataType)etype;\n                }\n            }\n        }\n\n        protected TypeReference(string @namespace, string name)\n            : base(name)\n        {\n            this.@namespace = @namespace ?? string.Empty;\n            this.token = new MetadataToken(TokenType.TypeRef, 0);\n        }\n\n        public TypeReference(string @namespace, string name, ModuleDefinition module, IMetadataScope scope)\n            : this(@namespace, name)\n        {\n            this.module = module;\n            this.scope = scope;\n        }\n\n        public TypeReference(string @namespace, string name, ModuleDefinition module, IMetadataScope scope, bool valueType) :\n            this(@namespace, name, module, scope)\n        {\n            value_type = valueType;\n        }\n\n        public virtual TypeReference GetElementType()\n        {\n            return this;\n        }\n\n        public virtual TypeDefinition Resolve()\n        {\n            var module = this.Module;\n            if (module == null)\n                throw new NotSupportedException();\n\n            return module.Resolve(this);\n        }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool IsPrimitive(ElementType self)\n        {\n            switch (self)\n            {\n                case ElementType.Boolean:\n                case ElementType.Char:\n                case ElementType.I:\n                case ElementType.U:\n                case ElementType.I1:\n                case ElementType.U1:\n                case ElementType.I2:\n                case ElementType.U2:\n                case ElementType.I4:\n                case ElementType.U4:\n                case ElementType.I8:\n                case ElementType.U8:\n                case ElementType.R4:\n                case ElementType.R8:\n                    return true;\n                default:\n                    return false;\n            }\n        }\n\n        public static bool IsTypeOf(TypeReference self, string @namespace, string name)\n        {\n            return self.Name == name\n                && self.Namespace == @namespace;\n        }\n\n        public static bool IsTypeSpecification(TypeReference type)\n        {\n            switch (type.etype)\n            {\n                case ElementType.Array:\n                case ElementType.ByRef:\n                case ElementType.CModOpt:\n                case ElementType.CModReqD:\n                case ElementType.FnPtr:\n                case ElementType.GenericInst:\n                case ElementType.MVar:\n                case ElementType.Pinned:\n                case ElementType.Ptr:\n                case ElementType.SzArray:\n                case ElementType.Sentinel:\n                case ElementType.Var:\n                    return true;\n            }\n\n            return false;\n        }\n\n        public static TypeDefinition CheckedResolve(TypeReference self)\n        {\n            var type = self.Resolve();\n            if (type == null)\n                throw new ResolutionException(self);\n\n            return type;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeSpecification.cs",
    "content": "//\n// TypeSpecification.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class TypeSpecification : TypeReference {\n\n\t\treadonly TypeReference element_type;\n\n\t\tpublic TypeReference ElementType {\n\t\t\tget { return element_type; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return element_type.Name; }\n\t\t\tset { throw new NotSupportedException (); }\n\t\t}\n\n\t\tpublic override string Namespace {\n\t\t\tget { return element_type.Namespace; }\n\t\t\tset { throw new NotSupportedException (); }\n\t\t}\n\n\t\tpublic override IMetadataScope Scope {\n\t\t\tget { return element_type.Scope; }\n\t\t}\n\n\t\tpublic override ModuleDefinition Module {\n\t\t\tget { return element_type.Module; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return element_type.FullName; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return element_type.ContainsGenericParameter; }\n\t\t}\n\n\t\tpublic override MetadataType MetadataType {\n\t\t\tget { return (MetadataType) etype; }\n\t\t}\n\n\t\tinternal TypeSpecification (TypeReference type)\n\t\t\t: base (null, null)\n\t\t{\n\t\t\tthis.element_type = type;\n\t\t\tthis.token = new MetadataToken (TokenType.TypeSpec);\n\t\t}\n\n\t\tpublic override TypeReference GetElementType ()\n\t\t{\n\t\t\treturn element_type;\n\t\t}\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic static void CheckType (TypeReference type)\n\t\t{\n\t\t\tif (type == null)\n\t\t\t\tthrow new ArgumentNullException (\"type\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeSystem.cs",
    "content": "//\n// TypeSystem.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil\n{\n\n    public abstract class TypeSystem\n    {\n\n        sealed class CoreTypeSystem : TypeSystem\n        {\n\n            public CoreTypeSystem(ModuleDefinition module)\n                : base(module)\n            {\n            }\n\n            internal override TypeReference LookupType(string @namespace, string name)\n            {\n                var type = LookupTypeDefinition(@namespace, name) ?? LookupTypeForwarded(@namespace, name);\n                if (type != null)\n                    return type;\n\n                throw new NotSupportedException();\n            }\n\n            TypeReference LookupTypeDefinition(string @namespace, string name)\n            {\n                var metadata = module.MetadataSystem;\n                if (metadata.Types == null)\n                    Initialize(module.Types);\n\n                return module.Read(new Row<string, string>(@namespace, name), (row, reader) =>\n                {\n                    var types = reader.metadata.Types;\n\n                    for (int i = 0; i < types.Length; i++)\n                    {\n                        if (types[i] == null)\n                            types[i] = reader.GetTypeDefinition((uint)i + 1);\n\n                        var type = types[i];\n\n                        if (type.Name == row.Col2 && type.Namespace == row.Col1)\n                            return type;\n                    }\n\n                    return null;\n                });\n            }\n\n            TypeReference LookupTypeForwarded(string @namespace, string name)\n            {\n                if (!module.HasExportedTypes)\n                    return null;\n\n                var exported_types = module.ExportedTypes;\n                for (int i = 0; i < exported_types.Count; i++)\n                {\n                    var exported_type = exported_types[i];\n\n                    if (exported_type.Name == name && exported_type.Namespace == @namespace)\n                        return exported_type.CreateReference();\n                }\n\n                return null;\n            }\n\n            static void Initialize(object obj)\n            {\n            }\n        }\n\n        sealed class CommonTypeSystem : TypeSystem\n        {\n\n            AssemblyNameReference corlib;\n\n            public CommonTypeSystem(ModuleDefinition module)\n                : base(module)\n            {\n            }\n\n            internal override TypeReference LookupType(string @namespace, string name)\n            {\n                return CreateTypeReference(@namespace, name);\n            }\n\n            public AssemblyNameReference GetCorlibReference()\n            {\n                if (corlib != null)\n                    return corlib;\n\n                const string mscorlib = \"mscorlib\";\n                const string systemruntime = \"System.Runtime\";\n\n                var references = module.AssemblyReferences;\n\n                for (int i = 0; i < references.Count; i++)\n                {\n                    var reference = references[i];\n                    if (reference.Name == mscorlib || reference.Name == systemruntime)\n                        return corlib = reference;\n                }\n\n                corlib = new AssemblyNameReference\n                {\n                    Name = mscorlib,\n                    Version = GetCorlibVersion(),\n                    PublicKeyToken = new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 },\n                };\n\n                references.Add(corlib);\n\n                return corlib;\n            }\n\n            Version GetCorlibVersion()\n            {\n                switch (module.Runtime)\n                {\n                    case TargetRuntime.Net_1_0:\n                    case TargetRuntime.Net_1_1:\n                        return new Version(1, 0, 0, 0);\n                    case TargetRuntime.Net_2_0:\n                        return new Version(2, 0, 0, 0);\n                    case TargetRuntime.Net_4_0:\n                        return new Version(4, 0, 0, 0);\n                    default:\n                        throw new NotSupportedException();\n                }\n            }\n\n            TypeReference CreateTypeReference(string @namespace, string name)\n            {\n                return new TypeReference(@namespace, name, module, GetCorlibReference());\n            }\n        }\n\n        readonly ModuleDefinition module;\n\n        TypeReference type_object;\n        TypeReference type_void;\n        TypeReference type_bool;\n        TypeReference type_char;\n        TypeReference type_sbyte;\n        TypeReference type_byte;\n        TypeReference type_int16;\n        TypeReference type_uint16;\n        TypeReference type_int32;\n        TypeReference type_uint32;\n        TypeReference type_int64;\n        TypeReference type_uint64;\n        TypeReference type_single;\n        TypeReference type_double;\n        TypeReference type_intptr;\n        TypeReference type_uintptr;\n        TypeReference type_string;\n        TypeReference type_typedref;\n\n        TypeSystem(ModuleDefinition module)\n        {\n            this.module = module;\n        }\n\n        internal static TypeSystem CreateTypeSystem(ModuleDefinition module)\n        {\n            if (Mixin.IsCorlib(module))\n                return new CoreTypeSystem(module);\n\n            return new CommonTypeSystem(module);\n        }\n\n        internal abstract TypeReference LookupType(string @namespace, string name);\n\n        TypeReference LookupSystemType(ref TypeReference typeRef, string name, ElementType element_type)\n        {\n            lock (module.SyncRoot)\n            {\n                if (typeRef != null)\n                    return typeRef;\n                var type = LookupType(\"System\", name);\n                type.etype = element_type;\n                return typeRef = type;\n            }\n        }\n\n        TypeReference LookupSystemValueType(ref TypeReference typeRef, string name, ElementType element_type)\n        {\n            lock (module.SyncRoot)\n            {\n                if (typeRef != null)\n                    return typeRef;\n                var type = LookupType(\"System\", name);\n                type.etype = element_type;\n                type.IsValueType = true;\n                return typeRef = type;\n            }\n        }\n\n        public IMetadataScope Corlib\n        {\n            get\n            {\n                var common = this as CommonTypeSystem;\n                if (common == null)\n                    return module;\n\n                return common.GetCorlibReference();\n            }\n        }\n\n        public TypeReference Object\n        {\n            get { return type_object ?? (LookupSystemType(ref type_object, \"Object\", ElementType.Object)); }\n        }\n\n        public TypeReference Void\n        {\n            get { return type_void ?? (LookupSystemType(ref type_void, \"Void\", ElementType.Void)); }\n        }\n\n        public TypeReference Boolean\n        {\n            get { return type_bool ?? (LookupSystemValueType(ref type_bool, \"Boolean\", ElementType.Boolean)); }\n        }\n\n        public TypeReference Char\n        {\n            get { return type_char ?? (LookupSystemValueType(ref type_char, \"Char\", ElementType.Char)); }\n        }\n\n        public TypeReference SByte\n        {\n            get { return type_sbyte ?? (LookupSystemValueType(ref type_sbyte, \"SByte\", ElementType.I1)); }\n        }\n\n        public TypeReference Byte\n        {\n            get { return type_byte ?? (LookupSystemValueType(ref type_byte, \"Byte\", ElementType.U1)); }\n        }\n\n        public TypeReference Int16\n        {\n            get { return type_int16 ?? (LookupSystemValueType(ref type_int16, \"Int16\", ElementType.I2)); }\n        }\n\n        public TypeReference UInt16\n        {\n            get { return type_uint16 ?? (LookupSystemValueType(ref type_uint16, \"UInt16\", ElementType.U2)); }\n        }\n\n        public TypeReference Int32\n        {\n            get { return type_int32 ?? (LookupSystemValueType(ref type_int32, \"Int32\", ElementType.I4)); }\n        }\n\n        public TypeReference UInt32\n        {\n            get { return type_uint32 ?? (LookupSystemValueType(ref type_uint32, \"UInt32\", ElementType.U4)); }\n        }\n\n        public TypeReference Int64\n        {\n            get { return type_int64 ?? (LookupSystemValueType(ref type_int64, \"Int64\", ElementType.I8)); }\n        }\n\n        public TypeReference UInt64\n        {\n            get { return type_uint64 ?? (LookupSystemValueType(ref type_uint64, \"UInt64\", ElementType.U8)); }\n        }\n\n        public TypeReference Single\n        {\n            get { return type_single ?? (LookupSystemValueType(ref type_single, \"Single\", ElementType.R4)); }\n        }\n\n        public TypeReference Double\n        {\n            get { return type_double ?? (LookupSystemValueType(ref type_double, \"Double\", ElementType.R8)); }\n        }\n\n        public TypeReference IntPtr\n        {\n            get { return type_intptr ?? (LookupSystemValueType(ref type_intptr, \"IntPtr\", ElementType.I)); }\n        }\n\n        public TypeReference UIntPtr\n        {\n            get { return type_uintptr ?? (LookupSystemValueType(ref type_uintptr, \"UIntPtr\", ElementType.U)); }\n        }\n\n        public TypeReference String\n        {\n            get { return type_string ?? (LookupSystemType(ref type_string, \"String\", ElementType.String)); }\n        }\n\n        public TypeReference TypedReference\n        {\n            get { return type_typedref ?? (LookupSystemValueType(ref type_typedref, \"TypedReference\", ElementType.TypedByRef)); }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil/VariantType.cs",
    "content": "//\n// VariantType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum VariantType {\n\t\tNone = 0,\n\t\tI2 = 2,\n\t\tI4 = 3,\n\t\tR4 = 4,\n\t\tR8 = 5,\n\t\tCY = 6,\n\t\tDate = 7,\n\t\tBStr = 8,\n\t\tDispatch = 9,\n\t\tError = 10,\n\t\tBool = 11,\n\t\tVariant = 12,\n\t\tUnknown = 13,\n\t\tDecimal = 14,\n\t\tI1 = 16,\n\t\tUI1 = 17,\n\t\tUI2 = 18,\n\t\tUI4 = 19,\n\t\tInt = 22,\n\t\tUInt = 23\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/Code.cs",
    "content": "//\n// Code.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic enum Code {\n\t\tNop,\n\t\tBreak,\n\t\tLdarg_0,\n\t\tLdarg_1,\n\t\tLdarg_2,\n\t\tLdarg_3,\n\t\tLdloc_0,\n\t\tLdloc_1,\n\t\tLdloc_2,\n\t\tLdloc_3,\n\t\tStloc_0,\n\t\tStloc_1,\n\t\tStloc_2,\n\t\tStloc_3,\n\t\tLdarg_S,\n\t\tLdarga_S,\n\t\tStarg_S,\n\t\tLdloc_S,\n\t\tLdloca_S,\n\t\tStloc_S,\n\t\tLdnull,\n\t\tLdc_I4_M1,\n\t\tLdc_I4_0,\n\t\tLdc_I4_1,\n\t\tLdc_I4_2,\n\t\tLdc_I4_3,\n\t\tLdc_I4_4,\n\t\tLdc_I4_5,\n\t\tLdc_I4_6,\n\t\tLdc_I4_7,\n\t\tLdc_I4_8,\n\t\tLdc_I4_S,\n\t\tLdc_I4,\n\t\tLdc_I8,\n\t\tLdc_R4,\n\t\tLdc_R8,\n\t\tDup,\n\t\tPop,\n\t\tJmp,\n\t\tCall,\n\t\tCalli,\n\t\tRet,\n\t\tBr_S,\n\t\tBrfalse_S,\n\t\tBrtrue_S,\n\t\tBeq_S,\n\t\tBge_S,\n\t\tBgt_S,\n\t\tBle_S,\n\t\tBlt_S,\n\t\tBne_Un_S,\n\t\tBge_Un_S,\n\t\tBgt_Un_S,\n\t\tBle_Un_S,\n\t\tBlt_Un_S,\n\t\tBr,\n\t\tBrfalse,\n\t\tBrtrue,\n\t\tBeq,\n\t\tBge,\n\t\tBgt,\n\t\tBle,\n\t\tBlt,\n\t\tBne_Un,\n\t\tBge_Un,\n\t\tBgt_Un,\n\t\tBle_Un,\n\t\tBlt_Un,\n\t\tSwitch,\n\t\tLdind_I1,\n\t\tLdind_U1,\n\t\tLdind_I2,\n\t\tLdind_U2,\n\t\tLdind_I4,\n\t\tLdind_U4,\n\t\tLdind_I8,\n\t\tLdind_I,\n\t\tLdind_R4,\n\t\tLdind_R8,\n\t\tLdind_Ref,\n\t\tStind_Ref,\n\t\tStind_I1,\n\t\tStind_I2,\n\t\tStind_I4,\n\t\tStind_I8,\n\t\tStind_R4,\n\t\tStind_R8,\n\t\tAdd,\n\t\tSub,\n\t\tMul,\n\t\tDiv,\n\t\tDiv_Un,\n\t\tRem,\n\t\tRem_Un,\n\t\tAnd,\n\t\tOr,\n\t\tXor,\n\t\tShl,\n\t\tShr,\n\t\tShr_Un,\n\t\tNeg,\n\t\tNot,\n\t\tConv_I1,\n\t\tConv_I2,\n\t\tConv_I4,\n\t\tConv_I8,\n\t\tConv_R4,\n\t\tConv_R8,\n\t\tConv_U4,\n\t\tConv_U8,\n\t\tCallvirt,\n\t\tCpobj,\n\t\tLdobj,\n\t\tLdstr,\n\t\tNewobj,\n\t\tCastclass,\n\t\tIsinst,\n\t\tConv_R_Un,\n\t\tUnbox,\n\t\tThrow,\n\t\tLdfld,\n\t\tLdflda,\n\t\tStfld,\n\t\tLdsfld,\n\t\tLdsflda,\n\t\tStsfld,\n\t\tStobj,\n\t\tConv_Ovf_I1_Un,\n\t\tConv_Ovf_I2_Un,\n\t\tConv_Ovf_I4_Un,\n\t\tConv_Ovf_I8_Un,\n\t\tConv_Ovf_U1_Un,\n\t\tConv_Ovf_U2_Un,\n\t\tConv_Ovf_U4_Un,\n\t\tConv_Ovf_U8_Un,\n\t\tConv_Ovf_I_Un,\n\t\tConv_Ovf_U_Un,\n\t\tBox,\n\t\tNewarr,\n\t\tLdlen,\n\t\tLdelema,\n\t\tLdelem_I1,\n\t\tLdelem_U1,\n\t\tLdelem_I2,\n\t\tLdelem_U2,\n\t\tLdelem_I4,\n\t\tLdelem_U4,\n\t\tLdelem_I8,\n\t\tLdelem_I,\n\t\tLdelem_R4,\n\t\tLdelem_R8,\n\t\tLdelem_Ref,\n\t\tStelem_I,\n\t\tStelem_I1,\n\t\tStelem_I2,\n\t\tStelem_I4,\n\t\tStelem_I8,\n\t\tStelem_R4,\n\t\tStelem_R8,\n\t\tStelem_Ref,\n\t\tLdelem_Any,\n\t\tStelem_Any,\n\t\tUnbox_Any,\n\t\tConv_Ovf_I1,\n\t\tConv_Ovf_U1,\n\t\tConv_Ovf_I2,\n\t\tConv_Ovf_U2,\n\t\tConv_Ovf_I4,\n\t\tConv_Ovf_U4,\n\t\tConv_Ovf_I8,\n\t\tConv_Ovf_U8,\n\t\tRefanyval,\n\t\tCkfinite,\n\t\tMkrefany,\n\t\tLdtoken,\n\t\tConv_U2,\n\t\tConv_U1,\n\t\tConv_I,\n\t\tConv_Ovf_I,\n\t\tConv_Ovf_U,\n\t\tAdd_Ovf,\n\t\tAdd_Ovf_Un,\n\t\tMul_Ovf,\n\t\tMul_Ovf_Un,\n\t\tSub_Ovf,\n\t\tSub_Ovf_Un,\n\t\tEndfinally,\n\t\tLeave,\n\t\tLeave_S,\n\t\tStind_I,\n\t\tConv_U,\n\t\tArglist,\n\t\tCeq,\n\t\tCgt,\n\t\tCgt_Un,\n\t\tClt,\n\t\tClt_Un,\n\t\tLdftn,\n\t\tLdvirtftn,\n\t\tLdarg,\n\t\tLdarga,\n\t\tStarg,\n\t\tLdloc,\n\t\tLdloca,\n\t\tStloc,\n\t\tLocalloc,\n\t\tEndfilter,\n\t\tUnaligned,\n\t\tVolatile,\n\t\tTail,\n\t\tInitobj,\n\t\tConstrained,\n\t\tCpblk,\n\t\tInitblk,\n\t\tNo,\n\t\tRethrow,\n\t\tSizeof,\n\t\tRefanytype,\n\t\tReadonly,\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/CodeReader.cs",
    "content": "//\n// CodeReader.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.PE;\nusing Mono.Collections.Generic;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil.Cil\n{\n\n    sealed class CodeReader : ByteBuffer\n    {\n\n        readonly internal MetadataReader reader;\n\n        int start;\n        Section code_section;\n\n        MethodDefinition method;\n        MethodBody body;\n\n        int Offset\n        {\n            get { return base.position - start; }\n        }\n\n        public CodeReader(Section section, MetadataReader reader)\n            : base(section.Data)\n        {\n            this.code_section = section;\n            this.reader = reader;\n        }\n\n        public MethodBody ReadMethodBody(MethodDefinition method)\n        {\n            this.method = method;\n            this.body = new MethodBody(method);\n\n            reader.context = method;\n\n            ReadMethodBody();\n\n            return this.body;\n        }\n\n        public void MoveTo(int rva)\n        {\n            if (!IsInSection(rva))\n            {\n                code_section = reader.image.GetSectionAtVirtualAddress((uint)rva);\n                Reset(code_section.Data);\n            }\n\n            base.position = rva - (int)code_section.VirtualAddress;\n        }\n\n        bool IsInSection(int rva)\n        {\n            return code_section.VirtualAddress <= rva && rva < code_section.VirtualAddress + code_section.SizeOfRawData;\n        }\n\n        void ReadMethodBody()\n        {\n            MoveTo(method.RVA);\n\n            var flags = ReadByte();\n            switch (flags & 0x3)\n            {\n                case 0x2: // tiny\n                    body.code_size = flags >> 2;\n                    body.MaxStackSize = 8;\n                    ReadCode();\n                    break;\n                case 0x3: // fat\n                    base.position--;\n                    ReadFatMethod();\n                    break;\n                default:\n                    throw new InvalidOperationException();\n            }\n\n            var symbol_reader = reader.module.symbol_reader;\n\n            if (symbol_reader != null)\n            {\n                var instructions = body.Instructions;\n                symbol_reader.Read(body, offset => GetInstruction(instructions, offset));\n            }\n        }\n\n        void ReadFatMethod()\n        {\n            var flags = ReadUInt16();\n            body.max_stack_size = ReadUInt16();\n            body.code_size = (int)ReadUInt32();\n            body.local_var_token = new MetadataToken(ReadUInt32());\n            body.init_locals = (flags & 0x10) != 0;\n\n            if (body.local_var_token.RID != 0)\n                body.variables = ReadVariables(body.local_var_token);\n\n            ReadCode();\n\n            if ((flags & 0x8) != 0)\n                ReadSection();\n        }\n\n        public VariableDefinitionCollection ReadVariables(MetadataToken local_var_token)\n        {\n            var position = reader.position;\n            var variables = reader.ReadVariables(local_var_token);\n            reader.position = position;\n\n            return variables;\n        }\n\n        void ReadCode()\n        {\n            start = position;\n            var code_size = body.code_size;\n\n            if (code_size < 0 || buffer.Length <= (uint)(code_size + position))\n                code_size = 0;\n\n            var end = start + code_size;\n            var instructions = body.instructions = new InstructionCollection((code_size + 1) / 2);\n\n            while (position < end)\n            {\n                var offset = base.position - start;\n                var opcode = ReadOpCode();\n                var current = new Instruction(offset, opcode);\n\n                if (opcode.OperandType != OperandType.InlineNone)\n                    current.operand = ReadOperand(current);\n\n                instructions.Add(current);\n            }\n\n            ResolveBranches(instructions);\n        }\n\n        OpCode ReadOpCode()\n        {\n            var il_opcode = ReadByte();\n            return il_opcode != 0xfe\n                ? OpCodes.OneByteOpCode[il_opcode]\n                : OpCodes.TwoBytesOpCode[ReadByte()];\n        }\n\n        object ReadOperand(Instruction instruction)\n        {\n            switch (instruction.opcode.OperandType)\n            {\n                case OperandType.InlineSwitch:\n                    var length = ReadInt32();\n                    var base_offset = Offset + (4 * length);\n                    var branches = new int[length];\n                    for (int i = 0; i < length; i++)\n                        branches[i] = base_offset + ReadInt32();\n                    return branches;\n                case OperandType.ShortInlineBrTarget:\n                    return ReadSByte() + Offset;\n                case OperandType.InlineBrTarget:\n                    return ReadInt32() + Offset;\n                case OperandType.ShortInlineI:\n                    if (instruction.opcode == OpCodes.Ldc_I4_S)\n                        return ReadSByte();\n\n                    return ReadByte();\n                case OperandType.InlineI:\n                    return ReadInt32();\n                case OperandType.ShortInlineR:\n                    return ReadSingle();\n                case OperandType.InlineR:\n                    return ReadDouble();\n                case OperandType.InlineI8:\n                    return ReadInt64();\n                case OperandType.ShortInlineVar:\n                    return GetVariable(ReadByte());\n                case OperandType.InlineVar:\n                    return GetVariable(ReadUInt16());\n                case OperandType.ShortInlineArg:\n                    return GetParameter(ReadByte());\n                case OperandType.InlineArg:\n                    return GetParameter(ReadUInt16());\n                case OperandType.InlineSig:\n                    return GetCallSite(ReadToken());\n                case OperandType.InlineString:\n                    return GetString(ReadToken());\n                case OperandType.InlineTok:\n                case OperandType.InlineType:\n                case OperandType.InlineMethod:\n                case OperandType.InlineField:\n                    return reader.LookupToken(ReadToken());\n                default:\n                    throw new NotSupportedException();\n            }\n        }\n\n        public string GetString(MetadataToken token)\n        {\n            return reader.image.UserStringHeap.Read(token.RID);\n        }\n\n        public ParameterDefinition GetParameter(int index)\n        {\n            return Mixin.GetParameter(body, index);\n        }\n\n        public VariableDefinition GetVariable(int index)\n        {\n            return Mixin.GetVariable(body, index);\n        }\n\n        public CallSite GetCallSite(MetadataToken token)\n        {\n            return reader.ReadCallSite(token);\n        }\n\n        void ResolveBranches(Collection<Instruction> instructions)\n        {\n            var items = instructions.items;\n            var size = instructions.size;\n\n            for (int i = 0; i < size; i++)\n            {\n                var instruction = items[i];\n                switch (instruction.opcode.OperandType)\n                {\n                    case OperandType.ShortInlineBrTarget:\n                    case OperandType.InlineBrTarget:\n                        instruction.operand = GetInstruction((int)instruction.operand);\n                        break;\n                    case OperandType.InlineSwitch:\n                        var offsets = (int[])instruction.operand;\n                        var branches = new Instruction[offsets.Length];\n                        for (int j = 0; j < offsets.Length; j++)\n                            branches[j] = GetInstruction(offsets[j]);\n\n                        instruction.operand = branches;\n                        break;\n                }\n            }\n        }\n\n        Instruction GetInstruction(int offset)\n        {\n            return GetInstruction(body.Instructions, offset);\n        }\n\n        static Instruction GetInstruction(Collection<Instruction> instructions, int offset)\n        {\n            var size = instructions.size;\n            var items = instructions.items;\n            if (offset < 0 || offset > items[size - 1].offset)\n                return null;\n\n            int min = 0;\n            int max = size - 1;\n            while (min <= max)\n            {\n                int mid = min + ((max - min) / 2);\n                var instruction = items[mid];\n                var instruction_offset = instruction.offset;\n\n                if (offset == instruction_offset)\n                    return instruction;\n\n                if (offset < instruction_offset)\n                    max = mid - 1;\n                else\n                    min = mid + 1;\n            }\n\n            return null;\n        }\n\n        void ReadSection()\n        {\n            Align(4);\n\n            const byte fat_format = 0x40;\n            const byte more_sects = 0x80;\n\n            var flags = ReadByte();\n            if ((flags & fat_format) == 0)\n                ReadSmallSection();\n            else\n                ReadFatSection();\n\n            if ((flags & more_sects) != 0)\n                ReadSection();\n        }\n\n        void ReadSmallSection()\n        {\n            var count = ReadByte() / 12;\n            Advance(2);\n\n            ReadExceptionHandlers(\n                count,\n                () => (int)ReadUInt16(),\n                () => (int)ReadByte());\n        }\n\n        void ReadFatSection()\n        {\n            position--;\n            var count = (ReadInt32() >> 8) / 24;\n\n            ReadExceptionHandlers(\n                count,\n                ReadInt32,\n                ReadInt32);\n        }\n\n        // inline ?\n        void ReadExceptionHandlers(int count, Func<int> read_entry, Func<int> read_length)\n        {\n            for (int i = 0; i < count; i++)\n            {\n                var handler = new ExceptionHandler(\n                    (ExceptionHandlerType)(read_entry() & 0x7));\n\n                handler.TryStart = GetInstruction(read_entry());\n                handler.TryEnd = GetInstruction(handler.TryStart.Offset + read_length());\n\n                handler.HandlerStart = GetInstruction(read_entry());\n                handler.HandlerEnd = GetInstruction(handler.HandlerStart.Offset + read_length());\n\n                ReadExceptionHandlerSpecific(handler);\n\n                this.body.ExceptionHandlers.Add(handler);\n            }\n        }\n\n        void ReadExceptionHandlerSpecific(ExceptionHandler handler)\n        {\n            switch (handler.HandlerType)\n            {\n                case ExceptionHandlerType.Catch:\n                    handler.CatchType = (TypeReference)reader.LookupToken(ReadToken());\n                    break;\n                case ExceptionHandlerType.Filter:\n                    handler.FilterStart = GetInstruction(ReadInt32());\n                    break;\n                default:\n                    Advance(4);\n                    break;\n            }\n        }\n\n        void Align(int align)\n        {\n            align--;\n            Advance(((position + align) & ~align) - position);\n        }\n\n        public MetadataToken ReadToken()\n        {\n            return new MetadataToken(ReadUInt32());\n        }\n\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/CodeWriter.cs",
    "content": "//\n// CodeWriter.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\n\nusing Mono.Collections.Generic;\n\nusing Mono.Cecil.Metadata;\nusing Mono.Cecil.PE;\n\nusing RVA = System.UInt32;\n\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/Document.cs",
    "content": "//\n// Document.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic enum DocumentType {\n\t\tOther,\n\t\tText,\n\t}\n\n\tpublic enum DocumentHashAlgorithm {\n\t\tNone,\n\t\tMD5,\n\t\tSHA1,\n\t}\n\n\tpublic enum DocumentLanguage {\n\t\tOther,\n\t\tC,\n\t\tCpp,\n\t\tCSharp,\n\t\tBasic,\n\t\tJava,\n\t\tCobol,\n\t\tPascal,\n\t\tCil,\n\t\tJScript,\n\t\tSmc,\n\t\tMCpp,\n\t\tFSharp,\n\t}\n\n\tpublic enum DocumentLanguageVendor {\n\t\tOther,\n\t\tMicrosoft,\n\t}\n\n\tpublic sealed class Document {\n\n\t\tstring url;\n\n\t\tbyte type;\n\t\tbyte hash_algorithm;\n\t\tbyte language;\n\t\tbyte language_vendor;\n\n\t\tbyte [] hash;\n\n\t\tpublic string Url {\n\t\t\tget { return url; }\n\t\t\tset { url = value; }\n\t\t}\n\n\t\tpublic DocumentType Type {\n\t\t\tget { return (DocumentType) type; }\n\t\t\tset { type = (byte) value; }\n\t\t}\n\n\t\tpublic DocumentHashAlgorithm HashAlgorithm {\n\t\t\tget { return (DocumentHashAlgorithm) hash_algorithm; }\n\t\t\tset { hash_algorithm = (byte) value; }\n\t\t}\n\n\t\tpublic DocumentLanguage Language {\n\t\t\tget { return (DocumentLanguage) language; }\n\t\t\tset { language = (byte) value; }\n\t\t}\n\n\t\tpublic DocumentLanguageVendor LanguageVendor {\n\t\t\tget { return (DocumentLanguageVendor) language_vendor; }\n\t\t\tset { language_vendor = (byte) value; }\n\t\t}\n\n\t\tpublic byte [] Hash {\n\t\t\tget { return hash; }\n\t\t\tset { hash = value; }\n\t\t}\n\n\t\tpublic Document (string url)\n\t\t{\n\t\t\tthis.url = url;\n\t\t\tthis.hash = Empty<byte>.Array;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/ExceptionHandler.cs",
    "content": "//\n// ExceptionHandler.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic enum ExceptionHandlerType {\n\t\tCatch = 0,\n\t\tFilter = 1,\n\t\tFinally = 2,\n\t\tFault = 4,\n\t}\n\n\tpublic sealed class ExceptionHandler {\n\n\t\tInstruction try_start;\n\t\tInstruction try_end;\n\t\tInstruction filter_start;\n\t\tInstruction handler_start;\n\t\tInstruction handler_end;\n\n\t\tTypeReference catch_type;\n\t\tExceptionHandlerType handler_type;\n\n\t\tpublic Instruction TryStart {\n\t\t\tget { return try_start; }\n\t\t\tset { try_start = value; }\n\t\t}\n\n\t\tpublic Instruction TryEnd {\n\t\t\tget { return try_end; }\n\t\t\tset { try_end = value; }\n\t\t}\n\n\t\tpublic Instruction FilterStart {\n\t\t\tget { return filter_start; }\n\t\t\tset { filter_start = value; }\n\t\t}\n\n\t\tpublic Instruction HandlerStart {\n\t\t\tget { return handler_start; }\n\t\t\tset { handler_start = value; }\n\t\t}\n\n\t\tpublic Instruction HandlerEnd {\n\t\t\tget { return handler_end; }\n\t\t\tset { handler_end = value; }\n\t\t}\n\n\t\tpublic TypeReference CatchType {\n\t\t\tget { return catch_type; }\n\t\t\tset { catch_type = value; }\n\t\t}\n\n\t\tpublic ExceptionHandlerType HandlerType {\n\t\t\tget { return handler_type; }\n\t\t\tset { handler_type = value; }\n\t\t}\n\n\t\tpublic ExceptionHandler (ExceptionHandlerType handlerType)\n\t\t{\n\t\t\tthis.handler_type = handlerType;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/ILProcessor.cs",
    "content": "//\n// ILProcessor.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic sealed class ILProcessor {\n\n\t\treadonly MethodBody body;\n\t\treadonly Collection<Instruction> instructions;\n\n\t\tpublic MethodBody Body {\n\t\t\tget { return body; }\n\t\t}\n\n\t\tinternal ILProcessor (MethodBody body)\n\t\t{\n\t\t\tthis.body = body;\n\t\t\tthis.instructions = body.Instructions;\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode)\n\t\t{\n\t\t\treturn Instruction.Create (opcode);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, TypeReference type)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, type);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, CallSite site)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, site);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, MethodReference method)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, method);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, FieldReference field)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, field);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, string value)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, sbyte value)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, byte value)\n\t\t{\n\t\t\tif (opcode.OperandType == OperandType.ShortInlineVar)\n\t\t\t\treturn Instruction.Create (opcode, body.Variables [value]);\n\n\t\t\tif (opcode.OperandType == OperandType.ShortInlineArg)\n\t\t\t\treturn Instruction.Create (opcode, Mixin.GetParameter (body,value));\n\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, int value)\n\t\t{\n\t\t\tif (opcode.OperandType == OperandType.InlineVar)\n\t\t\t\treturn Instruction.Create (opcode, body.Variables [value]);\n\n\t\t\tif (opcode.OperandType == OperandType.InlineArg)\n\t\t\t\treturn Instruction.Create (opcode, Mixin.GetParameter (body,value));\n\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, long value)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, float value)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, double value)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, Instruction target)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, target);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, Instruction [] targets)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, targets);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, VariableDefinition variable)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, variable);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, ParameterDefinition parameter)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, parameter);\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode)\n\t\t{\n\t\t\tAppend (Create (opcode));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, TypeReference type)\n\t\t{\n\t\t\tAppend (Create (opcode, type));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, MethodReference method)\n\t\t{\n\t\t\tAppend (Create (opcode, method));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, CallSite site)\n\t\t{\n\t\t\tAppend (Create (opcode, site));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, FieldReference field)\n\t\t{\n\t\t\tAppend (Create (opcode, field));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, string value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, byte value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, sbyte value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, int value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, long value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, float value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, double value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, Instruction target)\n\t\t{\n\t\t\tAppend (Create (opcode, target));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, Instruction [] targets)\n\t\t{\n\t\t\tAppend (Create (opcode, targets));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, VariableDefinition variable)\n\t\t{\n\t\t\tAppend (Create (opcode, variable));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, ParameterDefinition parameter)\n\t\t{\n\t\t\tAppend (Create (opcode, parameter));\n\t\t}\n\n\t\tpublic void InsertBefore (Instruction target, Instruction instruction)\n\t\t{\n\t\t\tif (target == null)\n\t\t\t\tthrow new ArgumentNullException (\"target\");\n\t\t\tif (instruction == null)\n\t\t\t\tthrow new ArgumentNullException (\"instruction\");\n\n\t\t\tvar index = instructions.IndexOf (target);\n\t\t\tif (index == -1)\n\t\t\t\tthrow new ArgumentOutOfRangeException (\"target\");\n\n\t\t\tinstructions.Insert (index, instruction);\n\t\t}\n\n\t\tpublic void InsertAfter (Instruction target, Instruction instruction)\n\t\t{\n\t\t\tif (target == null)\n\t\t\t\tthrow new ArgumentNullException (\"target\");\n\t\t\tif (instruction == null)\n\t\t\t\tthrow new ArgumentNullException (\"instruction\");\n\n\t\t\tvar index = instructions.IndexOf (target);\n\t\t\tif (index == -1)\n\t\t\t\tthrow new ArgumentOutOfRangeException (\"target\");\n\n\t\t\tinstructions.Insert (index + 1, instruction);\n\t\t}\n\n\t\tpublic void Append (Instruction instruction)\n\t\t{\n\t\t\tif (instruction == null)\n\t\t\t\tthrow new ArgumentNullException (\"instruction\");\n\n\t\t\tinstructions.Add (instruction);\n\t\t}\n\n\t\tpublic void Replace (Instruction target, Instruction instruction)\n\t\t{\n\t\t\tif (target == null)\n\t\t\t\tthrow new ArgumentNullException (\"target\");\n\t\t\tif (instruction == null)\n\t\t\t\tthrow new ArgumentNullException (\"instruction\");\n\n\t\t\tInsertAfter (target, instruction);\n\t\t\tRemove (target);\n\t\t}\n\n\t\tpublic void Remove (Instruction instruction)\n\t\t{\n\t\t\tif (instruction == null)\n\t\t\t\tthrow new ArgumentNullException (\"instruction\");\n\n\t\t\tif (!instructions.Remove (instruction))\n\t\t\t\tthrow new ArgumentOutOfRangeException (\"instruction\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/Instruction.cs",
    "content": "//\n// Instruction.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic sealed class Instruction {\n\n\t\tinternal int offset;\n\t\tinternal OpCode opcode;\n\t\tinternal object operand;\n\n\t\tinternal Instruction previous;\n\t\tinternal Instruction next;\n\n\t\tSequencePoint sequence_point;\n\n\t\tpublic int Offset {\n\t\t\tget { return offset; }\n\t\t\tset { offset = value; }\n\t\t}\n\n\t\tpublic OpCode OpCode {\n\t\t\tget { return opcode; }\n\t\t\tset { opcode = value; }\n\t\t}\n\n\t\tpublic object Operand {\n\t\t\tget { return operand; }\n\t\t\tset { operand = value; }\n\t\t}\n\n\t\tpublic Instruction Previous {\n\t\t\tget { return previous; }\n\t\t\tset { previous = value; }\n\t\t}\n\n\t\tpublic Instruction Next {\n\t\t\tget { return next; }\n\t\t\tset { next = value; }\n\t\t}\n\n\t\tpublic SequencePoint SequencePoint {\n\t\t\tget { return sequence_point; }\n\t\t\tset { sequence_point = value; }\n\t\t}\n\n\t\tinternal Instruction (int offset, OpCode opCode)\n\t\t{\n\t\t\tthis.offset = offset;\n\t\t\tthis.opcode = opCode;\n\t\t}\n\n\t\tinternal Instruction (OpCode opcode, object operand)\n\t\t{\n\t\t\tthis.opcode = opcode;\n\t\t\tthis.operand = operand;\n\t\t}\n\n\t\tpublic int GetSize ()\n\t\t{\n\t\t\tint size = opcode.Size;\n\n\t\t\tswitch (opcode.OperandType) {\n\t\t\tcase OperandType.InlineSwitch:\n\t\t\t\treturn size + (1 + ((Instruction []) operand).Length) * 4;\n\t\t\tcase OperandType.InlineI8:\n\t\t\tcase OperandType.InlineR:\n\t\t\t\treturn size + 8;\n\t\t\tcase OperandType.InlineBrTarget:\n\t\t\tcase OperandType.InlineField:\n\t\t\tcase OperandType.InlineI:\n\t\t\tcase OperandType.InlineMethod:\n\t\t\tcase OperandType.InlineString:\n\t\t\tcase OperandType.InlineTok:\n\t\t\tcase OperandType.InlineType:\n\t\t\tcase OperandType.ShortInlineR:\n\t\t\tcase OperandType.InlineSig:\n\t\t\t\treturn size + 4;\n\t\t\tcase OperandType.InlineArg:\n\t\t\tcase OperandType.InlineVar:\n\t\t\t\treturn size + 2;\n\t\t\tcase OperandType.ShortInlineBrTarget:\n\t\t\tcase OperandType.ShortInlineI:\n\t\t\tcase OperandType.ShortInlineArg:\n\t\t\tcase OperandType.ShortInlineVar:\n\t\t\t\treturn size + 1;\n\t\t\tdefault:\n\t\t\t\treturn size;\n\t\t\t}\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\tvar instruction = new StringBuilder ();\n\n\t\t\tAppendLabel (instruction, this);\n\t\t\tinstruction.Append (':');\n\t\t\tinstruction.Append (' ');\n\t\t\tinstruction.Append (opcode.Name);\n\n\t\t\tif (operand == null)\n\t\t\t\treturn instruction.ToString ();\n\n\t\t\tinstruction.Append (' ');\n\n\t\t\tswitch (opcode.OperandType) {\n\t\t\tcase OperandType.ShortInlineBrTarget:\n\t\t\tcase OperandType.InlineBrTarget:\n\t\t\t\tAppendLabel (instruction, (Instruction) operand);\n\t\t\t\tbreak;\n\t\t\tcase OperandType.InlineSwitch:\n\t\t\t\tvar labels = (Instruction []) operand;\n\t\t\t\tfor (int i = 0; i < labels.Length; i++) {\n\t\t\t\t\tif (i > 0)\n\t\t\t\t\t\tinstruction.Append (',');\n\n\t\t\t\t\tAppendLabel (instruction, labels [i]);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OperandType.InlineString:\n\t\t\t\tinstruction.Append ('\\\"');\n\t\t\t\tinstruction.Append (operand);\n\t\t\t\tinstruction.Append ('\\\"');\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tinstruction.Append (operand);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn instruction.ToString ();\n\t\t}\n\n\t\tstatic void AppendLabel (StringBuilder builder, Instruction instruction)\n\t\t{\n\t\t\tbuilder.Append (\"IL_\");\n\t\t\tbuilder.Append (instruction.offset.ToString (\"x4\"));\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.InlineNone)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, null);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, TypeReference type)\n\t\t{\n\t\t\tif (type == null)\n\t\t\t\tthrow new ArgumentNullException (\"type\");\n\t\t\tif (opcode.OperandType != OperandType.InlineType &&\n\t\t\t\topcode.OperandType != OperandType.InlineTok)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, type);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, CallSite site)\n\t\t{\n\t\t\tif (site == null)\n\t\t\t\tthrow new ArgumentNullException (\"site\");\n\t\t\tif (opcode.Code != Code.Calli)\n\t\t\t\tthrow new ArgumentException (\"code\");\n\n\t\t\treturn new Instruction (opcode, site);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, MethodReference method)\n\t\t{\n\t\t\tif (method == null)\n\t\t\t\tthrow new ArgumentNullException (\"method\");\n\t\t\tif (opcode.OperandType != OperandType.InlineMethod &&\n\t\t\t\topcode.OperandType != OperandType.InlineTok)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, method);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, FieldReference field)\n\t\t{\n\t\t\tif (field == null)\n\t\t\t\tthrow new ArgumentNullException (\"field\");\n\t\t\tif (opcode.OperandType != OperandType.InlineField &&\n\t\t\t\topcode.OperandType != OperandType.InlineTok)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, field);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, string value)\n\t\t{\n\t\t\tif (value == null)\n\t\t\t\tthrow new ArgumentNullException (\"value\");\n\t\t\tif (opcode.OperandType != OperandType.InlineString)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, sbyte value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.ShortInlineI &&\n\t\t\t\topcode != OpCodes.Ldc_I4_S)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, byte value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.ShortInlineI ||\n\t\t\t\topcode == OpCodes.Ldc_I4_S)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, int value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.InlineI)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, long value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.InlineI8)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, float value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.ShortInlineR)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, double value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.InlineR)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, Instruction target)\n\t\t{\n\t\t\tif (target == null)\n\t\t\t\tthrow new ArgumentNullException (\"target\");\n\t\t\tif (opcode.OperandType != OperandType.InlineBrTarget &&\n\t\t\t\topcode.OperandType != OperandType.ShortInlineBrTarget)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, target);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, Instruction [] targets)\n\t\t{\n\t\t\tif (targets == null)\n\t\t\t\tthrow new ArgumentNullException (\"targets\");\n\t\t\tif (opcode.OperandType != OperandType.InlineSwitch)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, targets);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, VariableDefinition variable)\n\t\t{\n\t\t\tif (variable == null)\n\t\t\t\tthrow new ArgumentNullException (\"variable\");\n\t\t\tif (opcode.OperandType != OperandType.ShortInlineVar &&\n\t\t\t\topcode.OperandType != OperandType.InlineVar)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, variable);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, ParameterDefinition parameter)\n\t\t{\n\t\t\tif (parameter == null)\n\t\t\t\tthrow new ArgumentNullException (\"parameter\");\n\t\t\tif (opcode.OperandType != OperandType.ShortInlineArg &&\n\t\t\t\topcode.OperandType != OperandType.InlineArg)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, parameter);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/MethodBody.cs",
    "content": "//\n// MethodBody.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Threading;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil.Cil\n{\n\n    public sealed class MethodBody : IVariableDefinitionProvider\n    {\n\n        readonly internal MethodDefinition method;\n\n        internal ParameterDefinition this_parameter;\n        internal int max_stack_size;\n        internal int code_size;\n        internal bool init_locals;\n        internal MetadataToken local_var_token;\n\n        internal Collection<Instruction> instructions;\n        internal Collection<ExceptionHandler> exceptions;\n        internal Collection<VariableDefinition> variables;\n        Scope scope;\n\n        public MethodDefinition Method\n        {\n            get { return method; }\n        }\n\n        public int MaxStackSize\n        {\n            get { return max_stack_size; }\n            set { max_stack_size = value; }\n        }\n\n        public int CodeSize\n        {\n            get { return code_size; }\n        }\n\n        public bool InitLocals\n        {\n            get { return init_locals; }\n            set { init_locals = value; }\n        }\n\n        public MetadataToken LocalVarToken\n        {\n            get { return local_var_token; }\n            set { local_var_token = value; }\n        }\n\n        public Collection<Instruction> Instructions\n        {\n            get { return instructions ?? (instructions = new InstructionCollection()); }\n        }\n\n        public bool HasExceptionHandlers\n        {\n            get { return !Mixin.IsNullOrEmpty(exceptions); }\n        }\n\n        public Collection<ExceptionHandler> ExceptionHandlers\n        {\n            get { return exceptions ?? (exceptions = new Collection<ExceptionHandler>()); }\n        }\n\n        public bool HasVariables\n        {\n            get { return !Mixin.IsNullOrEmpty(variables); }\n        }\n\n        public Collection<VariableDefinition> Variables\n        {\n            get { return variables ?? (variables = new VariableDefinitionCollection()); }\n        }\n\n        public Scope Scope\n        {\n            get { return scope; }\n            set { scope = value; }\n        }\n\n        public ParameterDefinition ThisParameter\n        {\n            get\n            {\n                if (method == null || method.DeclaringType == null)\n                    throw new NotSupportedException();\n\n                if (!method.HasThis)\n                    return null;\n\n                if (this_parameter == null)\n                    this_parameter = ThisParameterFor(method);\n\n                return this_parameter;\n            }\n        }\n\n        static ParameterDefinition ThisParameterFor(MethodDefinition method)\n        {\n            var declaring_type = method.DeclaringType;\n            var type = declaring_type.IsValueType || declaring_type.IsPrimitive\n                ? new PointerType(declaring_type)\n                : declaring_type as TypeReference;\n\n            return new ParameterDefinition(type, method);\n        }\n\n        public MethodBody(MethodDefinition method)\n        {\n            this.method = method;\n        }\n\n        public ILProcessor GetILProcessor()\n        {\n            return new ILProcessor(this);\n        }\n    }\n\n    public interface IVariableDefinitionProvider\n    {\n        bool HasVariables { get; }\n        Collection<VariableDefinition> Variables { get; }\n    }\n\n    class VariableDefinitionCollection : Collection<VariableDefinition>\n    {\n\n        internal VariableDefinitionCollection()\n        {\n        }\n\n        internal VariableDefinitionCollection(int capacity)\n            : base(capacity)\n        {\n        }\n\n        protected override void OnAdd(VariableDefinition item, int index)\n        {\n            item.index = index;\n        }\n\n        protected override void OnInsert(VariableDefinition item, int index)\n        {\n            item.index = index;\n\n            for (int i = index; i < size; i++)\n                items[i].index = i + 1;\n        }\n\n        protected override void OnSet(VariableDefinition item, int index)\n        {\n            item.index = index;\n        }\n\n        protected override void OnRemove(VariableDefinition item, int index)\n        {\n            item.index = -1;\n\n            for (int i = index + 1; i < size; i++)\n                items[i].index = i - 1;\n        }\n    }\n\n    class InstructionCollection : Collection<Instruction>\n    {\n\n        internal InstructionCollection()\n        {\n        }\n\n        internal InstructionCollection(int capacity)\n            : base(capacity)\n        {\n        }\n\n        protected override void OnAdd(Instruction item, int index)\n        {\n            if (index == 0)\n                return;\n\n            var previous = items[index - 1];\n            previous.next = item;\n            item.previous = previous;\n        }\n\n        protected override void OnInsert(Instruction item, int index)\n        {\n            if (size == 0)\n                return;\n\n            var current = items[index];\n            if (current == null)\n            {\n                var last = items[index - 1];\n                last.next = item;\n                item.previous = last;\n                return;\n            }\n\n            var previous = current.previous;\n            if (previous != null)\n            {\n                previous.next = item;\n                item.previous = previous;\n            }\n\n            current.previous = item;\n            item.next = current;\n        }\n\n        protected override void OnSet(Instruction item, int index)\n        {\n            var current = items[index];\n\n            item.previous = current.previous;\n            item.next = current.next;\n\n            current.previous = null;\n            current.next = null;\n        }\n\n        protected override void OnRemove(Instruction item, int index)\n        {\n            var previous = item.previous;\n            if (previous != null)\n                previous.next = item.next;\n\n            var next = item.next;\n            if (next != null)\n                next.previous = item.previous;\n\n            item.previous = null;\n            item.next = null;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/OpCode.cs",
    "content": "//\n// OpCode.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic enum FlowControl {\n\t\tBranch,\n\t\tBreak,\n\t\tCall,\n\t\tCond_Branch,\n\t\tMeta,\n\t\tNext,\n\t\tPhi,\n\t\tReturn,\n\t\tThrow,\n\t}\n\n\tpublic enum OpCodeType {\n\t\tAnnotation,\n\t\tMacro,\n\t\tNternal,\n\t\tObjmodel,\n\t\tPrefix,\n\t\tPrimitive,\n\t}\n\n\tpublic enum OperandType {\n\t\tInlineBrTarget,\n\t\tInlineField,\n\t\tInlineI,\n\t\tInlineI8,\n\t\tInlineMethod,\n\t\tInlineNone,\n\t\tInlinePhi,\n\t\tInlineR,\n\t\tInlineSig,\n\t\tInlineString,\n\t\tInlineSwitch,\n\t\tInlineTok,\n\t\tInlineType,\n\t\tInlineVar,\n\t\tInlineArg,\n\t\tShortInlineBrTarget,\n\t\tShortInlineI,\n\t\tShortInlineR,\n\t\tShortInlineVar,\n\t\tShortInlineArg,\n\t}\n\n\tpublic enum StackBehaviour {\n\t\tPop0,\n\t\tPop1,\n\t\tPop1_pop1,\n\t\tPopi,\n\t\tPopi_pop1,\n\t\tPopi_popi,\n\t\tPopi_popi8,\n\t\tPopi_popi_popi,\n\t\tPopi_popr4,\n\t\tPopi_popr8,\n\t\tPopref,\n\t\tPopref_pop1,\n\t\tPopref_popi,\n\t\tPopref_popi_popi,\n\t\tPopref_popi_popi8,\n\t\tPopref_popi_popr4,\n\t\tPopref_popi_popr8,\n\t\tPopref_popi_popref,\n\t\tPopAll,\n\t\tPush0,\n\t\tPush1,\n\t\tPush1_push1,\n\t\tPushi,\n\t\tPushi8,\n\t\tPushr4,\n\t\tPushr8,\n\t\tPushref,\n\t\tVarpop,\n\t\tVarpush,\n\t}\n\n\tpublic struct OpCode {\n\n\t\treadonly byte op1;\n\t\treadonly byte op2;\n\t\treadonly byte code;\n\t\treadonly byte flow_control;\n\t\treadonly byte opcode_type;\n\t\treadonly byte operand_type;\n\t\treadonly byte stack_behavior_pop;\n\t\treadonly byte stack_behavior_push;\n\n\t\tpublic string Name {\n\t\t\tget { return OpCodeNames.names [(int) Code]; }\n\t\t}\n\n\t\tpublic int Size {\n\t\t\tget { return op1 == 0xff ? 1 : 2; }\n\t\t}\n\n\t\tpublic byte Op1 {\n\t\t\tget { return op1; }\n\t\t}\n\n\t\tpublic byte Op2 {\n\t\t\tget { return op2; }\n\t\t}\n\n\t\tpublic short Value {\n\t\t\tget { return op1 == 0xff ? op2 : (short) ((op1 << 8) | op2); }\n\t\t}\n\n\t\tpublic Code Code {\n\t\t\tget { return (Code) code; }\n\t\t}\n\n\t\tpublic FlowControl FlowControl {\n\t\t\tget { return (FlowControl) flow_control; }\n\t\t}\n\n\t\tpublic OpCodeType OpCodeType {\n\t\t\tget { return (OpCodeType) opcode_type; }\n\t\t}\n\n\t\tpublic OperandType OperandType {\n\t\t\tget { return (OperandType) operand_type; }\n\t\t}\n\n\t\tpublic StackBehaviour StackBehaviourPop {\n\t\t\tget { return (StackBehaviour) stack_behavior_pop; }\n\t\t}\n\n\t\tpublic StackBehaviour StackBehaviourPush {\n\t\t\tget { return (StackBehaviour) stack_behavior_push; }\n\t\t}\n\n\t\tinternal OpCode (int x, int y)\n\t\t{\n\t\t\tthis.op1 = (byte) ((x >> 0) & 0xff);\n\t\t\tthis.op2 = (byte) ((x >> 8) & 0xff);\n\t\t\tthis.code = (byte) ((x >> 16) & 0xff);\n\t\t\tthis.flow_control = (byte) ((x >> 24) & 0xff);\n\n\t\t\tthis.opcode_type = (byte) ((y >> 0) & 0xff);\n\t\t\tthis.operand_type = (byte) ((y >> 8) & 0xff);\n\t\t\tthis.stack_behavior_pop = (byte) ((y >> 16) & 0xff);\n\t\t\tthis.stack_behavior_push = (byte) ((y >> 24) & 0xff);\n\n\t\t\tif (op1 == 0xff)\n\t\t\t\tOpCodes.OneByteOpCode [op2] = this;\n\t\t\telse\n\t\t\t\tOpCodes.TwoBytesOpCode [op2] = this;\n\t\t}\n\n\t\tpublic override int GetHashCode ()\n\t\t{\n\t\t\treturn Value;\n\t\t}\n\n\t\tpublic override bool Equals (object obj)\n\t\t{\n\t\t\tif (!(obj is OpCode))\n\t\t\t\treturn false;\n\n\t\t\tvar opcode = (OpCode) obj;\n\t\t\treturn op1 == opcode.op1 && op2 == opcode.op2;\n\t\t}\n\n\t\tpublic bool Equals (OpCode opcode)\n\t\t{\n\t\t\treturn op1 == opcode.op1 && op2 == opcode.op2;\n\t\t}\n\n\t\tpublic static bool operator == (OpCode one, OpCode other)\n\t\t{\n\t\t\treturn one.op1 == other.op1 && one.op2 == other.op2;\n\t\t}\n\n\t\tpublic static bool operator != (OpCode one, OpCode other)\n\t\t{\n\t\t\treturn one.op1 != other.op1 || one.op2 != other.op2;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn Name;\n\t\t}\n\t}\n\n\tstatic class OpCodeNames {\n\n\t\tinternal static readonly string [] names;\n\n\t\tstatic OpCodeNames ()\n\t\t{\n\t\t\tvar table = new byte [] {\n\t\t\t\t3, 110, 111, 112,\n\t\t\t\t5, 98, 114, 101, 97, 107,\n\t\t\t\t7, 108, 100, 97, 114, 103, 46, 48,\n\t\t\t\t7, 108, 100, 97, 114, 103, 46, 49,\n\t\t\t\t7, 108, 100, 97, 114, 103, 46, 50,\n\t\t\t\t7, 108, 100, 97, 114, 103, 46, 51,\n\t\t\t\t7, 108, 100, 108, 111, 99, 46, 48,\n\t\t\t\t7, 108, 100, 108, 111, 99, 46, 49,\n\t\t\t\t7, 108, 100, 108, 111, 99, 46, 50,\n\t\t\t\t7, 108, 100, 108, 111, 99, 46, 51,\n\t\t\t\t7, 115, 116, 108, 111, 99, 46, 48,\n\t\t\t\t7, 115, 116, 108, 111, 99, 46, 49,\n\t\t\t\t7, 115, 116, 108, 111, 99, 46, 50,\n\t\t\t\t7, 115, 116, 108, 111, 99, 46, 51,\n\t\t\t\t7, 108, 100, 97, 114, 103, 46, 115,\n\t\t\t\t8, 108, 100, 97, 114, 103, 97, 46, 115,\n\t\t\t\t7, 115, 116, 97, 114, 103, 46, 115,\n\t\t\t\t7, 108, 100, 108, 111, 99, 46, 115,\n\t\t\t\t8, 108, 100, 108, 111, 99, 97, 46, 115,\n\t\t\t\t7, 115, 116, 108, 111, 99, 46, 115,\n\t\t\t\t6, 108, 100, 110, 117, 108, 108,\n\t\t\t\t9, 108, 100, 99, 46, 105, 52, 46, 109, 49,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 48,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 49,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 50,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 51,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 52,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 53,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 54,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 55,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 56,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 115,\n\t\t\t\t6, 108, 100, 99, 46, 105, 52,\n\t\t\t\t6, 108, 100, 99, 46, 105, 56,\n\t\t\t\t6, 108, 100, 99, 46, 114, 52,\n\t\t\t\t6, 108, 100, 99, 46, 114, 56,\n\t\t\t\t3, 100, 117, 112,\n\t\t\t\t3, 112, 111, 112,\n\t\t\t\t3, 106, 109, 112,\n\t\t\t\t4, 99, 97, 108, 108,\n\t\t\t\t5, 99, 97, 108, 108, 105,\n\t\t\t\t3, 114, 101, 116,\n\t\t\t\t4, 98, 114, 46, 115,\n\t\t\t\t9, 98, 114, 102, 97, 108, 115, 101, 46, 115,\n\t\t\t\t8, 98, 114, 116, 114, 117, 101, 46, 115,\n\t\t\t\t5, 98, 101, 113, 46, 115,\n\t\t\t\t5, 98, 103, 101, 46, 115,\n\t\t\t\t5, 98, 103, 116, 46, 115,\n\t\t\t\t5, 98, 108, 101, 46, 115,\n\t\t\t\t5, 98, 108, 116, 46, 115,\n\t\t\t\t8, 98, 110, 101, 46, 117, 110, 46, 115,\n\t\t\t\t8, 98, 103, 101, 46, 117, 110, 46, 115,\n\t\t\t\t8, 98, 103, 116, 46, 117, 110, 46, 115,\n\t\t\t\t8, 98, 108, 101, 46, 117, 110, 46, 115,\n\t\t\t\t8, 98, 108, 116, 46, 117, 110, 46, 115,\n\t\t\t\t2, 98, 114,\n\t\t\t\t7, 98, 114, 102, 97, 108, 115, 101,\n\t\t\t\t6, 98, 114, 116, 114, 117, 101,\n\t\t\t\t3, 98, 101, 113,\n\t\t\t\t3, 98, 103, 101,\n\t\t\t\t3, 98, 103, 116,\n\t\t\t\t3, 98, 108, 101,\n\t\t\t\t3, 98, 108, 116,\n\t\t\t\t6, 98, 110, 101, 46, 117, 110,\n\t\t\t\t6, 98, 103, 101, 46, 117, 110,\n\t\t\t\t6, 98, 103, 116, 46, 117, 110,\n\t\t\t\t6, 98, 108, 101, 46, 117, 110,\n\t\t\t\t6, 98, 108, 116, 46, 117, 110,\n\t\t\t\t6, 115, 119, 105, 116, 99, 104,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 105, 49,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 117, 49,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 105, 50,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 117, 50,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 105, 52,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 117, 52,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 105, 56,\n\t\t\t\t7, 108, 100, 105, 110, 100, 46, 105,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 114, 52,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 114, 56,\n\t\t\t\t9, 108, 100, 105, 110, 100, 46, 114, 101, 102,\n\t\t\t\t9, 115, 116, 105, 110, 100, 46, 114, 101, 102,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 105, 49,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 105, 50,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 105, 52,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 105, 56,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 114, 52,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 114, 56,\n\t\t\t\t3, 97, 100, 100,\n\t\t\t\t3, 115, 117, 98,\n\t\t\t\t3, 109, 117, 108,\n\t\t\t\t3, 100, 105, 118,\n\t\t\t\t6, 100, 105, 118, 46, 117, 110,\n\t\t\t\t3, 114, 101, 109,\n\t\t\t\t6, 114, 101, 109, 46, 117, 110,\n\t\t\t\t3, 97, 110, 100,\n\t\t\t\t2, 111, 114,\n\t\t\t\t3, 120, 111, 114,\n\t\t\t\t3, 115, 104, 108,\n\t\t\t\t3, 115, 104, 114,\n\t\t\t\t6, 115, 104, 114, 46, 117, 110,\n\t\t\t\t3, 110, 101, 103,\n\t\t\t\t3, 110, 111, 116,\n\t\t\t\t7, 99, 111, 110, 118, 46, 105, 49,\n\t\t\t\t7, 99, 111, 110, 118, 46, 105, 50,\n\t\t\t\t7, 99, 111, 110, 118, 46, 105, 52,\n\t\t\t\t7, 99, 111, 110, 118, 46, 105, 56,\n\t\t\t\t7, 99, 111, 110, 118, 46, 114, 52,\n\t\t\t\t7, 99, 111, 110, 118, 46, 114, 56,\n\t\t\t\t7, 99, 111, 110, 118, 46, 117, 52,\n\t\t\t\t7, 99, 111, 110, 118, 46, 117, 56,\n\t\t\t\t8, 99, 97, 108, 108, 118, 105, 114, 116,\n\t\t\t\t5, 99, 112, 111, 98, 106,\n\t\t\t\t5, 108, 100, 111, 98, 106,\n\t\t\t\t5, 108, 100, 115, 116, 114,\n\t\t\t\t6, 110, 101, 119, 111, 98, 106,\n\t\t\t\t9, 99, 97, 115, 116, 99, 108, 97, 115, 115,\n\t\t\t\t6, 105, 115, 105, 110, 115, 116,\n\t\t\t\t9, 99, 111, 110, 118, 46, 114, 46, 117, 110,\n\t\t\t\t5, 117, 110, 98, 111, 120,\n\t\t\t\t5, 116, 104, 114, 111, 119,\n\t\t\t\t5, 108, 100, 102, 108, 100,\n\t\t\t\t6, 108, 100, 102, 108, 100, 97,\n\t\t\t\t5, 115, 116, 102, 108, 100,\n\t\t\t\t6, 108, 100, 115, 102, 108, 100,\n\t\t\t\t7, 108, 100, 115, 102, 108, 100, 97,\n\t\t\t\t6, 115, 116, 115, 102, 108, 100,\n\t\t\t\t5, 115, 116, 111, 98, 106,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 49, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 50, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 52, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 56, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 49, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 50, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 52, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 56, 46, 117, 110,\n\t\t\t\t13, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 46, 117, 110,\n\t\t\t\t13, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 46, 117, 110,\n\t\t\t\t3, 98, 111, 120,\n\t\t\t\t6, 110, 101, 119, 97, 114, 114,\n\t\t\t\t5, 108, 100, 108, 101, 110,\n\t\t\t\t7, 108, 100, 101, 108, 101, 109, 97,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 105, 49,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 117, 49,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 105, 50,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 117, 50,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 105, 52,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 117, 52,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 105, 56,\n\t\t\t\t8, 108, 100, 101, 108, 101, 109, 46, 105,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 114, 52,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 114, 56,\n\t\t\t\t10, 108, 100, 101, 108, 101, 109, 46, 114, 101, 102,\n\t\t\t\t8, 115, 116, 101, 108, 101, 109, 46, 105,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 105, 49,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 105, 50,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 105, 52,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 105, 56,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 114, 52,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 114, 56,\n\t\t\t\t10, 115, 116, 101, 108, 101, 109, 46, 114, 101, 102,\n\t\t\t\t10, 108, 100, 101, 108, 101, 109, 46, 97, 110, 121,\n\t\t\t\t10, 115, 116, 101, 108, 101, 109, 46, 97, 110, 121,\n\t\t\t\t9, 117, 110, 98, 111, 120, 46, 97, 110, 121,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 49,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 49,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 50,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 50,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 52,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 52,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 56,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 56,\n\t\t\t\t9, 114, 101, 102, 97, 110, 121, 118, 97, 108,\n\t\t\t\t8, 99, 107, 102, 105, 110, 105, 116, 101,\n\t\t\t\t8, 109, 107, 114, 101, 102, 97, 110, 121,\n\t\t\t\t7, 108, 100, 116, 111, 107, 101, 110,\n\t\t\t\t7, 99, 111, 110, 118, 46, 117, 50,\n\t\t\t\t7, 99, 111, 110, 118, 46, 117, 49,\n\t\t\t\t6, 99, 111, 110, 118, 46, 105,\n\t\t\t\t10, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105,\n\t\t\t\t10, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117,\n\t\t\t\t7, 97, 100, 100, 46, 111, 118, 102,\n\t\t\t\t10, 97, 100, 100, 46, 111, 118, 102, 46, 117, 110,\n\t\t\t\t7, 109, 117, 108, 46, 111, 118, 102,\n\t\t\t\t10, 109, 117, 108, 46, 111, 118, 102, 46, 117, 110,\n\t\t\t\t7, 115, 117, 98, 46, 111, 118, 102,\n\t\t\t\t10, 115, 117, 98, 46, 111, 118, 102, 46, 117, 110,\n\t\t\t\t10, 101, 110, 100, 102, 105, 110, 97, 108, 108, 121,\n\t\t\t\t5, 108, 101, 97, 118, 101,\n\t\t\t\t7, 108, 101, 97, 118, 101, 46, 115,\n\t\t\t\t7, 115, 116, 105, 110, 100, 46, 105,\n\t\t\t\t6, 99, 111, 110, 118, 46, 117,\n\t\t\t\t7, 97, 114, 103, 108, 105, 115, 116,\n\t\t\t\t3, 99, 101, 113,\n\t\t\t\t3, 99, 103, 116,\n\t\t\t\t6, 99, 103, 116, 46, 117, 110,\n\t\t\t\t3, 99, 108, 116,\n\t\t\t\t6, 99, 108, 116, 46, 117, 110,\n\t\t\t\t5, 108, 100, 102, 116, 110,\n\t\t\t\t9, 108, 100, 118, 105, 114, 116, 102, 116, 110,\n\t\t\t\t5, 108, 100, 97, 114, 103,\n\t\t\t\t6, 108, 100, 97, 114, 103, 97,\n\t\t\t\t5, 115, 116, 97, 114, 103,\n\t\t\t\t5, 108, 100, 108, 111, 99,\n\t\t\t\t6, 108, 100, 108, 111, 99, 97,\n\t\t\t\t5, 115, 116, 108, 111, 99,\n\t\t\t\t8, 108, 111, 99, 97, 108, 108, 111, 99,\n\t\t\t\t9, 101, 110, 100, 102, 105, 108, 116, 101, 114,\n\t\t\t\t10, 117, 110, 97, 108, 105, 103, 110, 101, 100, 46,\n\t\t\t\t9, 118, 111, 108, 97, 116, 105, 108, 101, 46,\n\t\t\t\t5, 116, 97, 105, 108, 46,\n\t\t\t\t7, 105, 110, 105, 116, 111, 98, 106,\n\t\t\t\t12, 99, 111, 110, 115, 116, 114, 97, 105, 110, 101, 100, 46,\n\t\t\t\t5, 99, 112, 98, 108, 107,\n\t\t\t\t7, 105, 110, 105, 116, 98, 108, 107,\n\t\t\t\t3, 110, 111, 46,\n\t\t\t\t7, 114, 101, 116, 104, 114, 111, 119,\n\t\t\t\t6, 115, 105, 122, 101, 111, 102,\n\t\t\t\t10, 114, 101, 102, 97, 110, 121, 116, 121, 112, 101,\n\t\t\t\t9, 114, 101, 97, 100, 111, 110, 108, 121, 46,\n\t\t\t};\n\n\t\t\tnames = new string [219];\n\n\t\t\tfor (int i = 0, p = 0; i < names.Length; i++) {\n\t\t\t\tvar buffer = new char [table [p++]];\n\n\t\t\t\tfor (int j = 0; j < buffer.Length; j++)\n\t\t\t\t\tbuffer [j] = (char) table [p++];\n\n\t\t\t\tnames [i] = new string (buffer);\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/OpCodes.cs",
    "content": "//\n// OpCodes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic static class OpCodes {\n\n\t\tinternal static readonly OpCode [] OneByteOpCode = new OpCode [0xe0 + 1];\n\t\tinternal static readonly OpCode [] TwoBytesOpCode = new OpCode [0x1e + 1];\n\n\t\tpublic static readonly OpCode Nop = new OpCode (\n\t\t\t0xff << 0 | 0x00 << 8 | (byte) Code.Nop << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Break = new OpCode (\n\t\t\t0xff << 0 | 0x01 << 8 | (byte) Code.Break << 16 | (byte) FlowControl.Break << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldarg_0 = new OpCode (\n\t\t\t0xff << 0 | 0x02 << 8 | (byte) Code.Ldarg_0 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldarg_1 = new OpCode (\n\t\t\t0xff << 0 | 0x03 << 8 | (byte) Code.Ldarg_1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldarg_2 = new OpCode (\n\t\t\t0xff << 0 | 0x04 << 8 | (byte) Code.Ldarg_2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldarg_3 = new OpCode (\n\t\t\t0xff << 0 | 0x05 << 8 | (byte) Code.Ldarg_3 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloc_0 = new OpCode (\n\t\t\t0xff << 0 | 0x06 << 8 | (byte) Code.Ldloc_0 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloc_1 = new OpCode (\n\t\t\t0xff << 0 | 0x07 << 8 | (byte) Code.Ldloc_1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloc_2 = new OpCode (\n\t\t\t0xff << 0 | 0x08 << 8 | (byte) Code.Ldloc_2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloc_3 = new OpCode (\n\t\t\t0xff << 0 | 0x09 << 8 | (byte) Code.Ldloc_3 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Stloc_0 = new OpCode (\n\t\t\t0xff << 0 | 0x0a << 8 | (byte) Code.Stloc_0 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stloc_1 = new OpCode (\n\t\t\t0xff << 0 | 0x0b << 8 | (byte) Code.Stloc_1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stloc_2 = new OpCode (\n\t\t\t0xff << 0 | 0x0c << 8 | (byte) Code.Stloc_2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stloc_3 = new OpCode (\n\t\t\t0xff << 0 | 0x0d << 8 | (byte) Code.Stloc_3 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldarg_S = new OpCode (\n\t\t\t0xff << 0 | 0x0e << 8 | (byte) Code.Ldarg_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldarga_S = new OpCode (\n\t\t\t0xff << 0 | 0x0f << 8 | (byte) Code.Ldarga_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Starg_S = new OpCode (\n\t\t\t0xff << 0 | 0x10 << 8 | (byte) Code.Starg_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineArg << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldloc_S = new OpCode (\n\t\t\t0xff << 0 | 0x11 << 8 | (byte) Code.Ldloc_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloca_S = new OpCode (\n\t\t\t0xff << 0 | 0x12 << 8 | (byte) Code.Ldloca_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Stloc_S = new OpCode (\n\t\t\t0xff << 0 | 0x13 << 8 | (byte) Code.Stloc_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineVar << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldnull = new OpCode (\n\t\t\t0xff << 0 | 0x14 << 8 | (byte) Code.Ldnull << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_M1 = new OpCode (\n\t\t\t0xff << 0 | 0x15 << 8 | (byte) Code.Ldc_I4_M1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_0 = new OpCode (\n\t\t\t0xff << 0 | 0x16 << 8 | (byte) Code.Ldc_I4_0 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_1 = new OpCode (\n\t\t\t0xff << 0 | 0x17 << 8 | (byte) Code.Ldc_I4_1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_2 = new OpCode (\n\t\t\t0xff << 0 | 0x18 << 8 | (byte) Code.Ldc_I4_2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_3 = new OpCode (\n\t\t\t0xff << 0 | 0x19 << 8 | (byte) Code.Ldc_I4_3 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_4 = new OpCode (\n\t\t\t0xff << 0 | 0x1a << 8 | (byte) Code.Ldc_I4_4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_5 = new OpCode (\n\t\t\t0xff << 0 | 0x1b << 8 | (byte) Code.Ldc_I4_5 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_6 = new OpCode (\n\t\t\t0xff << 0 | 0x1c << 8 | (byte) Code.Ldc_I4_6 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_7 = new OpCode (\n\t\t\t0xff << 0 | 0x1d << 8 | (byte) Code.Ldc_I4_7 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_8 = new OpCode (\n\t\t\t0xff << 0 | 0x1e << 8 | (byte) Code.Ldc_I4_8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_S = new OpCode (\n\t\t\t0xff << 0 | 0x1f << 8 | (byte) Code.Ldc_I4_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x20 << 8 | (byte) Code.Ldc_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x21 << 8 | (byte) Code.Ldc_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineI8 << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Ldc_R4 = new OpCode (\n\t\t\t0xff << 0 | 0x22 << 8 | (byte) Code.Ldc_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.ShortInlineR << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushr4 << 24);\n\n\t\tpublic static readonly OpCode Ldc_R8 = new OpCode (\n\t\t\t0xff << 0 | 0x23 << 8 | (byte) Code.Ldc_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineR << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Dup = new OpCode (\n\t\t\t0xff << 0 | 0x25 << 8 | (byte) Code.Dup << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push1_push1 << 24);\n\n\t\tpublic static readonly OpCode Pop = new OpCode (\n\t\t\t0xff << 0 | 0x26 << 8 | (byte) Code.Pop << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Jmp = new OpCode (\n\t\t\t0xff << 0 | 0x27 << 8 | (byte) Code.Jmp << 16 | (byte) FlowControl.Call << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Call = new OpCode (\n\t\t\t0xff << 0 | 0x28 << 8 | (byte) Code.Call << 16 | (byte) FlowControl.Call << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Varpush << 24);\n\n\t\tpublic static readonly OpCode Calli = new OpCode (\n\t\t\t0xff << 0 | 0x29 << 8 | (byte) Code.Calli << 16 | (byte) FlowControl.Call << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineSig << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Varpush << 24);\n\n\t\tpublic static readonly OpCode Ret = new OpCode (\n\t\t\t0xff << 0 | 0x2a << 8 | (byte) Code.Ret << 16 | (byte) FlowControl.Return << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Br_S = new OpCode (\n\t\t\t0xff << 0 | 0x2b << 8 | (byte) Code.Br_S << 16 | (byte) FlowControl.Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Brfalse_S = new OpCode (\n\t\t\t0xff << 0 | 0x2c << 8 | (byte) Code.Brfalse_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Brtrue_S = new OpCode (\n\t\t\t0xff << 0 | 0x2d << 8 | (byte) Code.Brtrue_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Beq_S = new OpCode (\n\t\t\t0xff << 0 | 0x2e << 8 | (byte) Code.Beq_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bge_S = new OpCode (\n\t\t\t0xff << 0 | 0x2f << 8 | (byte) Code.Bge_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bgt_S = new OpCode (\n\t\t\t0xff << 0 | 0x30 << 8 | (byte) Code.Bgt_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ble_S = new OpCode (\n\t\t\t0xff << 0 | 0x31 << 8 | (byte) Code.Ble_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Blt_S = new OpCode (\n\t\t\t0xff << 0 | 0x32 << 8 | (byte) Code.Blt_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bne_Un_S = new OpCode (\n\t\t\t0xff << 0 | 0x33 << 8 | (byte) Code.Bne_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bge_Un_S = new OpCode (\n\t\t\t0xff << 0 | 0x34 << 8 | (byte) Code.Bge_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bgt_Un_S = new OpCode (\n\t\t\t0xff << 0 | 0x35 << 8 | (byte) Code.Bgt_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ble_Un_S = new OpCode (\n\t\t\t0xff << 0 | 0x36 << 8 | (byte) Code.Ble_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Blt_Un_S = new OpCode (\n\t\t\t0xff << 0 | 0x37 << 8 | (byte) Code.Blt_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Br = new OpCode (\n\t\t\t0xff << 0 | 0x38 << 8 | (byte) Code.Br << 16 | (byte) FlowControl.Branch << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Brfalse = new OpCode (\n\t\t\t0xff << 0 | 0x39 << 8 | (byte) Code.Brfalse << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Brtrue = new OpCode (\n\t\t\t0xff << 0 | 0x3a << 8 | (byte) Code.Brtrue << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Beq = new OpCode (\n\t\t\t0xff << 0 | 0x3b << 8 | (byte) Code.Beq << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bge = new OpCode (\n\t\t\t0xff << 0 | 0x3c << 8 | (byte) Code.Bge << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bgt = new OpCode (\n\t\t\t0xff << 0 | 0x3d << 8 | (byte) Code.Bgt << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ble = new OpCode (\n\t\t\t0xff << 0 | 0x3e << 8 | (byte) Code.Ble << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Blt = new OpCode (\n\t\t\t0xff << 0 | 0x3f << 8 | (byte) Code.Blt << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bne_Un = new OpCode (\n\t\t\t0xff << 0 | 0x40 << 8 | (byte) Code.Bne_Un << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bge_Un = new OpCode (\n\t\t\t0xff << 0 | 0x41 << 8 | (byte) Code.Bge_Un << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bgt_Un = new OpCode (\n\t\t\t0xff << 0 | 0x42 << 8 | (byte) Code.Bgt_Un << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ble_Un = new OpCode (\n\t\t\t0xff << 0 | 0x43 << 8 | (byte) Code.Ble_Un << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Blt_Un = new OpCode (\n\t\t\t0xff << 0 | 0x44 << 8 | (byte) Code.Blt_Un << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Switch = new OpCode (\n\t\t\t0xff << 0 | 0x45 << 8 | (byte) Code.Switch << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineSwitch << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldind_I1 = new OpCode (\n\t\t\t0xff << 0 | 0x46 << 8 | (byte) Code.Ldind_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_U1 = new OpCode (\n\t\t\t0xff << 0 | 0x47 << 8 | (byte) Code.Ldind_U1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_I2 = new OpCode (\n\t\t\t0xff << 0 | 0x48 << 8 | (byte) Code.Ldind_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_U2 = new OpCode (\n\t\t\t0xff << 0 | 0x49 << 8 | (byte) Code.Ldind_U2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x4a << 8 | (byte) Code.Ldind_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_U4 = new OpCode (\n\t\t\t0xff << 0 | 0x4b << 8 | (byte) Code.Ldind_U4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x4c << 8 | (byte) Code.Ldind_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Ldind_I = new OpCode (\n\t\t\t0xff << 0 | 0x4d << 8 | (byte) Code.Ldind_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_R4 = new OpCode (\n\t\t\t0xff << 0 | 0x4e << 8 | (byte) Code.Ldind_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushr4 << 24);\n\n\t\tpublic static readonly OpCode Ldind_R8 = new OpCode (\n\t\t\t0xff << 0 | 0x4f << 8 | (byte) Code.Ldind_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Ldind_Ref = new OpCode (\n\t\t\t0xff << 0 | 0x50 << 8 | (byte) Code.Ldind_Ref << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Stind_Ref = new OpCode (\n\t\t\t0xff << 0 | 0x51 << 8 | (byte) Code.Stind_Ref << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_I1 = new OpCode (\n\t\t\t0xff << 0 | 0x52 << 8 | (byte) Code.Stind_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_I2 = new OpCode (\n\t\t\t0xff << 0 | 0x53 << 8 | (byte) Code.Stind_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x54 << 8 | (byte) Code.Stind_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x55 << 8 | (byte) Code.Stind_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi8 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_R4 = new OpCode (\n\t\t\t0xff << 0 | 0x56 << 8 | (byte) Code.Stind_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popr4 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_R8 = new OpCode (\n\t\t\t0xff << 0 | 0x57 << 8 | (byte) Code.Stind_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popr8 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Add = new OpCode (\n\t\t\t0xff << 0 | 0x58 << 8 | (byte) Code.Add << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Sub = new OpCode (\n\t\t\t0xff << 0 | 0x59 << 8 | (byte) Code.Sub << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Mul = new OpCode (\n\t\t\t0xff << 0 | 0x5a << 8 | (byte) Code.Mul << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Div = new OpCode (\n\t\t\t0xff << 0 | 0x5b << 8 | (byte) Code.Div << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Div_Un = new OpCode (\n\t\t\t0xff << 0 | 0x5c << 8 | (byte) Code.Div_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Rem = new OpCode (\n\t\t\t0xff << 0 | 0x5d << 8 | (byte) Code.Rem << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Rem_Un = new OpCode (\n\t\t\t0xff << 0 | 0x5e << 8 | (byte) Code.Rem_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode And = new OpCode (\n\t\t\t0xff << 0 | 0x5f << 8 | (byte) Code.And << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Or = new OpCode (\n\t\t\t0xff << 0 | 0x60 << 8 | (byte) Code.Or << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Xor = new OpCode (\n\t\t\t0xff << 0 | 0x61 << 8 | (byte) Code.Xor << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Shl = new OpCode (\n\t\t\t0xff << 0 | 0x62 << 8 | (byte) Code.Shl << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Shr = new OpCode (\n\t\t\t0xff << 0 | 0x63 << 8 | (byte) Code.Shr << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Shr_Un = new OpCode (\n\t\t\t0xff << 0 | 0x64 << 8 | (byte) Code.Shr_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Neg = new OpCode (\n\t\t\t0xff << 0 | 0x65 << 8 | (byte) Code.Neg << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Not = new OpCode (\n\t\t\t0xff << 0 | 0x66 << 8 | (byte) Code.Not << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Conv_I1 = new OpCode (\n\t\t\t0xff << 0 | 0x67 << 8 | (byte) Code.Conv_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_I2 = new OpCode (\n\t\t\t0xff << 0 | 0x68 << 8 | (byte) Code.Conv_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x69 << 8 | (byte) Code.Conv_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x6a << 8 | (byte) Code.Conv_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Conv_R4 = new OpCode (\n\t\t\t0xff << 0 | 0x6b << 8 | (byte) Code.Conv_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr4 << 24);\n\n\t\tpublic static readonly OpCode Conv_R8 = new OpCode (\n\t\t\t0xff << 0 | 0x6c << 8 | (byte) Code.Conv_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Conv_U4 = new OpCode (\n\t\t\t0xff << 0 | 0x6d << 8 | (byte) Code.Conv_U4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_U8 = new OpCode (\n\t\t\t0xff << 0 | 0x6e << 8 | (byte) Code.Conv_U8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Callvirt = new OpCode (\n\t\t\t0xff << 0 | 0x6f << 8 | (byte) Code.Callvirt << 16 | (byte) FlowControl.Call << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Varpush << 24);\n\n\t\tpublic static readonly OpCode Cpobj = new OpCode (\n\t\t\t0xff << 0 | 0x70 << 8 | (byte) Code.Cpobj << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldobj = new OpCode (\n\t\t\t0xff << 0 | 0x71 << 8 | (byte) Code.Ldobj << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldstr = new OpCode (\n\t\t\t0xff << 0 | 0x72 << 8 | (byte) Code.Ldstr << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineString << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Newobj = new OpCode (\n\t\t\t0xff << 0 | 0x73 << 8 | (byte) Code.Newobj << 16 | (byte) FlowControl.Call << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Castclass = new OpCode (\n\t\t\t0xff << 0 | 0x74 << 8 | (byte) Code.Castclass << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Isinst = new OpCode (\n\t\t\t0xff << 0 | 0x75 << 8 | (byte) Code.Isinst << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_R_Un = new OpCode (\n\t\t\t0xff << 0 | 0x76 << 8 | (byte) Code.Conv_R_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Unbox = new OpCode (\n\t\t\t0xff << 0 | 0x79 << 8 | (byte) Code.Unbox << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Throw = new OpCode (\n\t\t\t0xff << 0 | 0x7a << 8 | (byte) Code.Throw << 16 | (byte) FlowControl.Throw << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldfld = new OpCode (\n\t\t\t0xff << 0 | 0x7b << 8 | (byte) Code.Ldfld << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldflda = new OpCode (\n\t\t\t0xff << 0 | 0x7c << 8 | (byte) Code.Ldflda << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Stfld = new OpCode (\n\t\t\t0xff << 0 | 0x7d << 8 | (byte) Code.Stfld << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Popref_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldsfld = new OpCode (\n\t\t\t0xff << 0 | 0x7e << 8 | (byte) Code.Ldsfld << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldsflda = new OpCode (\n\t\t\t0xff << 0 | 0x7f << 8 | (byte) Code.Ldsflda << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Stsfld = new OpCode (\n\t\t\t0xff << 0 | 0x80 << 8 | (byte) Code.Stsfld << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stobj = new OpCode (\n\t\t\t0xff << 0 | 0x81 << 8 | (byte) Code.Stobj << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I1_Un = new OpCode (\n\t\t\t0xff << 0 | 0x82 << 8 | (byte) Code.Conv_Ovf_I1_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I2_Un = new OpCode (\n\t\t\t0xff << 0 | 0x83 << 8 | (byte) Code.Conv_Ovf_I2_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I4_Un = new OpCode (\n\t\t\t0xff << 0 | 0x84 << 8 | (byte) Code.Conv_Ovf_I4_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I8_Un = new OpCode (\n\t\t\t0xff << 0 | 0x85 << 8 | (byte) Code.Conv_Ovf_I8_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U1_Un = new OpCode (\n\t\t\t0xff << 0 | 0x86 << 8 | (byte) Code.Conv_Ovf_U1_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U2_Un = new OpCode (\n\t\t\t0xff << 0 | 0x87 << 8 | (byte) Code.Conv_Ovf_U2_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U4_Un = new OpCode (\n\t\t\t0xff << 0 | 0x88 << 8 | (byte) Code.Conv_Ovf_U4_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U8_Un = new OpCode (\n\t\t\t0xff << 0 | 0x89 << 8 | (byte) Code.Conv_Ovf_U8_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I_Un = new OpCode (\n\t\t\t0xff << 0 | 0x8a << 8 | (byte) Code.Conv_Ovf_I_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U_Un = new OpCode (\n\t\t\t0xff << 0 | 0x8b << 8 | (byte) Code.Conv_Ovf_U_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Box = new OpCode (\n\t\t\t0xff << 0 | 0x8c << 8 | (byte) Code.Box << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Newarr = new OpCode (\n\t\t\t0xff << 0 | 0x8d << 8 | (byte) Code.Newarr << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Ldlen = new OpCode (\n\t\t\t0xff << 0 | 0x8e << 8 | (byte) Code.Ldlen << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelema = new OpCode (\n\t\t\t0xff << 0 | 0x8f << 8 | (byte) Code.Ldelema << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_I1 = new OpCode (\n\t\t\t0xff << 0 | 0x90 << 8 | (byte) Code.Ldelem_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_U1 = new OpCode (\n\t\t\t0xff << 0 | 0x91 << 8 | (byte) Code.Ldelem_U1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_I2 = new OpCode (\n\t\t\t0xff << 0 | 0x92 << 8 | (byte) Code.Ldelem_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_U2 = new OpCode (\n\t\t\t0xff << 0 | 0x93 << 8 | (byte) Code.Ldelem_U2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x94 << 8 | (byte) Code.Ldelem_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_U4 = new OpCode (\n\t\t\t0xff << 0 | 0x95 << 8 | (byte) Code.Ldelem_U4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x96 << 8 | (byte) Code.Ldelem_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Ldelem_I = new OpCode (\n\t\t\t0xff << 0 | 0x97 << 8 | (byte) Code.Ldelem_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_R4 = new OpCode (\n\t\t\t0xff << 0 | 0x98 << 8 | (byte) Code.Ldelem_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushr4 << 24);\n\n\t\tpublic static readonly OpCode Ldelem_R8 = new OpCode (\n\t\t\t0xff << 0 | 0x99 << 8 | (byte) Code.Ldelem_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Ldelem_Ref = new OpCode (\n\t\t\t0xff << 0 | 0x9a << 8 | (byte) Code.Ldelem_Ref << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Stelem_I = new OpCode (\n\t\t\t0xff << 0 | 0x9b << 8 | (byte) Code.Stelem_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_I1 = new OpCode (\n\t\t\t0xff << 0 | 0x9c << 8 | (byte) Code.Stelem_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_I2 = new OpCode (\n\t\t\t0xff << 0 | 0x9d << 8 | (byte) Code.Stelem_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x9e << 8 | (byte) Code.Stelem_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x9f << 8 | (byte) Code.Stelem_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi8 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_R4 = new OpCode (\n\t\t\t0xff << 0 | 0xa0 << 8 | (byte) Code.Stelem_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popr4 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_R8 = new OpCode (\n\t\t\t0xff << 0 | 0xa1 << 8 | (byte) Code.Stelem_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popr8 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_Ref = new OpCode (\n\t\t\t0xff << 0 | 0xa2 << 8 | (byte) Code.Stelem_Ref << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popref << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldelem_Any = new OpCode (\n\t\t\t0xff << 0 | 0xa3 << 8 | (byte) Code.Ldelem_Any << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Stelem_Any = new OpCode (\n\t\t\t0xff << 0 | 0xa4 << 8 | (byte) Code.Stelem_Any << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref_popi_popref << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Unbox_Any = new OpCode (\n\t\t\t0xff << 0 | 0xa5 << 8 | (byte) Code.Unbox_Any << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I1 = new OpCode (\n\t\t\t0xff << 0 | 0xb3 << 8 | (byte) Code.Conv_Ovf_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U1 = new OpCode (\n\t\t\t0xff << 0 | 0xb4 << 8 | (byte) Code.Conv_Ovf_U1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I2 = new OpCode (\n\t\t\t0xff << 0 | 0xb5 << 8 | (byte) Code.Conv_Ovf_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U2 = new OpCode (\n\t\t\t0xff << 0 | 0xb6 << 8 | (byte) Code.Conv_Ovf_U2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I4 = new OpCode (\n\t\t\t0xff << 0 | 0xb7 << 8 | (byte) Code.Conv_Ovf_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U4 = new OpCode (\n\t\t\t0xff << 0 | 0xb8 << 8 | (byte) Code.Conv_Ovf_U4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I8 = new OpCode (\n\t\t\t0xff << 0 | 0xb9 << 8 | (byte) Code.Conv_Ovf_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U8 = new OpCode (\n\t\t\t0xff << 0 | 0xba << 8 | (byte) Code.Conv_Ovf_U8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Refanyval = new OpCode (\n\t\t\t0xff << 0 | 0xc2 << 8 | (byte) Code.Refanyval << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ckfinite = new OpCode (\n\t\t\t0xff << 0 | 0xc3 << 8 | (byte) Code.Ckfinite << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Mkrefany = new OpCode (\n\t\t\t0xff << 0 | 0xc6 << 8 | (byte) Code.Mkrefany << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldtoken = new OpCode (\n\t\t\t0xff << 0 | 0xd0 << 8 | (byte) Code.Ldtoken << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineTok << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_U2 = new OpCode (\n\t\t\t0xff << 0 | 0xd1 << 8 | (byte) Code.Conv_U2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_U1 = new OpCode (\n\t\t\t0xff << 0 | 0xd2 << 8 | (byte) Code.Conv_U1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_I = new OpCode (\n\t\t\t0xff << 0 | 0xd3 << 8 | (byte) Code.Conv_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I = new OpCode (\n\t\t\t0xff << 0 | 0xd4 << 8 | (byte) Code.Conv_Ovf_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U = new OpCode (\n\t\t\t0xff << 0 | 0xd5 << 8 | (byte) Code.Conv_Ovf_U << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Add_Ovf = new OpCode (\n\t\t\t0xff << 0 | 0xd6 << 8 | (byte) Code.Add_Ovf << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Add_Ovf_Un = new OpCode (\n\t\t\t0xff << 0 | 0xd7 << 8 | (byte) Code.Add_Ovf_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Mul_Ovf = new OpCode (\n\t\t\t0xff << 0 | 0xd8 << 8 | (byte) Code.Mul_Ovf << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Mul_Ovf_Un = new OpCode (\n\t\t\t0xff << 0 | 0xd9 << 8 | (byte) Code.Mul_Ovf_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Sub_Ovf = new OpCode (\n\t\t\t0xff << 0 | 0xda << 8 | (byte) Code.Sub_Ovf << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Sub_Ovf_Un = new OpCode (\n\t\t\t0xff << 0 | 0xdb << 8 | (byte) Code.Sub_Ovf_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Endfinally = new OpCode (\n\t\t\t0xff << 0 | 0xdc << 8 | (byte) Code.Endfinally << 16 | (byte) FlowControl.Return << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Leave = new OpCode (\n\t\t\t0xff << 0 | 0xdd << 8 | (byte) Code.Leave << 16 | (byte) FlowControl.Branch << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.PopAll << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Leave_S = new OpCode (\n\t\t\t0xff << 0 | 0xde << 8 | (byte) Code.Leave_S << 16 | (byte) FlowControl.Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.PopAll << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_I = new OpCode (\n\t\t\t0xff << 0 | 0xdf << 8 | (byte) Code.Stind_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Conv_U = new OpCode (\n\t\t\t0xff << 0 | 0xe0 << 8 | (byte) Code.Conv_U << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Arglist = new OpCode (\n\t\t\t0xfe << 0 | 0x00 << 8 | (byte) Code.Arglist << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ceq = new OpCode (\n\t\t\t0xfe << 0 | 0x01 << 8 | (byte) Code.Ceq << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Cgt = new OpCode (\n\t\t\t0xfe << 0 | 0x02 << 8 | (byte) Code.Cgt << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Cgt_Un = new OpCode (\n\t\t\t0xfe << 0 | 0x03 << 8 | (byte) Code.Cgt_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Clt = new OpCode (\n\t\t\t0xfe << 0 | 0x04 << 8 | (byte) Code.Clt << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Clt_Un = new OpCode (\n\t\t\t0xfe << 0 | 0x05 << 8 | (byte) Code.Clt_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldftn = new OpCode (\n\t\t\t0xfe << 0 | 0x06 << 8 | (byte) Code.Ldftn << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldvirtftn = new OpCode (\n\t\t\t0xfe << 0 | 0x07 << 8 | (byte) Code.Ldvirtftn << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldarg = new OpCode (\n\t\t\t0xfe << 0 | 0x09 << 8 | (byte) Code.Ldarg << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldarga = new OpCode (\n\t\t\t0xfe << 0 | 0x0a << 8 | (byte) Code.Ldarga << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Starg = new OpCode (\n\t\t\t0xfe << 0 | 0x0b << 8 | (byte) Code.Starg << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineArg << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldloc = new OpCode (\n\t\t\t0xfe << 0 | 0x0c << 8 | (byte) Code.Ldloc << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloca = new OpCode (\n\t\t\t0xfe << 0 | 0x0d << 8 | (byte) Code.Ldloca << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Stloc = new OpCode (\n\t\t\t0xfe << 0 | 0x0e << 8 | (byte) Code.Stloc << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineVar << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Localloc = new OpCode (\n\t\t\t0xfe << 0 | 0x0f << 8 | (byte) Code.Localloc << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Endfilter = new OpCode (\n\t\t\t0xfe << 0 | 0x11 << 8 | (byte) Code.Endfilter << 16 | (byte) FlowControl.Return << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Unaligned = new OpCode (\n\t\t\t0xfe << 0 | 0x12 << 8 | (byte) Code.Unaligned << 16 | (byte) FlowControl.Meta << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.ShortInlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Volatile = new OpCode (\n\t\t\t0xfe << 0 | 0x13 << 8 | (byte) Code.Volatile << 16 | (byte) FlowControl.Meta << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Tail = new OpCode (\n\t\t\t0xfe << 0 | 0x14 << 8 | (byte) Code.Tail << 16 | (byte) FlowControl.Meta << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Initobj = new OpCode (\n\t\t\t0xfe << 0 | 0x15 << 8 | (byte) Code.Initobj << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Constrained = new OpCode (\n\t\t\t0xfe << 0 | 0x16 << 8 | (byte) Code.Constrained << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Cpblk = new OpCode (\n\t\t\t0xfe << 0 | 0x17 << 8 | (byte) Code.Cpblk << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Initblk = new OpCode (\n\t\t\t0xfe << 0 | 0x18 << 8 | (byte) Code.Initblk << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode No = new OpCode (\n\t\t\t0xfe << 0 | 0x19 << 8 | (byte) Code.No << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.ShortInlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Rethrow = new OpCode (\n\t\t\t0xfe << 0 | 0x1a << 8 | (byte) Code.Rethrow << 16 | (byte) FlowControl.Throw << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Sizeof = new OpCode (\n\t\t\t0xfe << 0 | 0x1c << 8 | (byte) Code.Sizeof << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Refanytype = new OpCode (\n\t\t\t0xfe << 0 | 0x1d << 8 | (byte) Code.Refanytype << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Readonly = new OpCode (\n\t\t\t0xfe << 0 | 0x1e << 8 | (byte) Code.Readonly << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/SequencePoint.cs",
    "content": "//\n// SequencePoint.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic sealed class SequencePoint {\n\n\t\tDocument document;\n\n\t\tint start_line;\n\t\tint start_column;\n\t\tint end_line;\n\t\tint end_column;\n\n\t\tpublic int StartLine {\n\t\t\tget { return start_line; }\n\t\t\tset { start_line = value; }\n\t\t}\n\n\t\tpublic int StartColumn {\n\t\t\tget { return start_column; }\n\t\t\tset { start_column = value; }\n\t\t}\n\n\t\tpublic int EndLine {\n\t\t\tget { return end_line; }\n\t\t\tset { end_line = value; }\n\t\t}\n\n\t\tpublic int EndColumn {\n\t\t\tget { return end_column; }\n\t\t\tset { end_column = value; }\n\t\t}\n\n\t\tpublic Document Document {\n\t\t\tget { return document; }\n\t\t\tset { document = value; }\n\t\t}\n\n\t\tpublic SequencePoint (Document document)\n\t\t{\n\t\t\tthis.document = document;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/Symbols.cs",
    "content": "//\n// Symbols.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\nusing System.Runtime.InteropServices;\nusing SR = System.Reflection;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil.Cil {\n\n\t[StructLayout (LayoutKind.Sequential)]\n\tpublic struct ImageDebugDirectory {\n\t\tpublic int Characteristics;\n\t\tpublic int TimeDateStamp;\n\t\tpublic short MajorVersion;\n\t\tpublic short MinorVersion;\n\t\tpublic int Type;\n\t\tpublic int SizeOfData;\n\t\tpublic int AddressOfRawData;\n\t\tpublic int PointerToRawData;\n\t}\n\n\tpublic sealed class Scope : IVariableDefinitionProvider {\n\n\t\tInstruction start;\n\t\tInstruction end;\n\n\t\tCollection<Scope> scopes;\n\t\tCollection<VariableDefinition> variables;\n\n\t\tpublic Instruction Start {\n\t\t\tget { return start; }\n\t\t\tset { start = value; }\n\t\t}\n\n\t\tpublic Instruction End {\n\t\t\tget { return end; }\n\t\t\tset { end = value; }\n\t\t}\n\n\t\tpublic bool HasScopes {\n\t\t\tget { return !Mixin.IsNullOrEmpty (scopes); }\n\t\t}\n\n\t\tpublic Collection<Scope> Scopes {\n\t\t\tget {\n\t\t\t\tif (scopes == null)\n\t\t\t\t\tscopes = new Collection<Scope> ();\n\n\t\t\t\treturn scopes;\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasVariables {\n\t\t\tget { return !Mixin.IsNullOrEmpty (variables); }\n\t\t}\n\n\t\tpublic Collection<VariableDefinition> Variables {\n\t\t\tget {\n\t\t\t\tif (variables == null)\n\t\t\t\t\tvariables = new Collection<VariableDefinition> ();\n\n\t\t\t\treturn variables;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic struct InstructionSymbol {\n\n\t\tpublic readonly int Offset;\n\t\tpublic readonly SequencePoint SequencePoint;\n\n\t\tpublic InstructionSymbol (int offset, SequencePoint sequencePoint)\n\t\t{\n\t\t\tthis.Offset = offset;\n\t\t\tthis.SequencePoint = sequencePoint;\n\t\t}\n\t}\n\n\tpublic sealed class MethodSymbols {\n\n\t\tinternal int code_size;\n\t\tinternal string method_name;\n\t\tinternal MetadataToken method_token;\n\t\tinternal MetadataToken local_var_token;\n\t\tinternal Collection<VariableDefinition> variables;\n\t\tpublic Collection<InstructionSymbol> instructions;\n\n\t\tpublic bool HasVariables {\n\t\t\tget { return !Mixin.IsNullOrEmpty (variables); }\n\t\t}\n\n\t\tpublic Collection<VariableDefinition> Variables {\n\t\t\tget {\n\t\t\t\tif (variables == null)\n\t\t\t\t\tvariables = new Collection<VariableDefinition> ();\n\n\t\t\t\treturn variables;\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<InstructionSymbol> Instructions {\n\t\t\tget {\n\t\t\t\tif (instructions == null)\n\t\t\t\t\tinstructions = new Collection<InstructionSymbol> ();\n\n\t\t\t\treturn instructions;\n\t\t\t}\n\t\t}\n\n\t\tpublic int CodeSize {\n\t\t\tget { return code_size; }\n\t\t}\n\n\t\tpublic string MethodName {\n\t\t\tget { return method_name; }\n\t\t}\n\n\t\tpublic MetadataToken MethodToken {\n\t\t\tget { return method_token; }\n\t\t}\n\n\t\tpublic MetadataToken LocalVarToken {\n\t\t\tget { return local_var_token; }\n\t\t}\n\n\t\tinternal MethodSymbols (string methodName)\n\t\t{\n\t\t\tthis.method_name = methodName;\n\t\t}\n\n\t\tpublic MethodSymbols (MetadataToken methodToken)\n\t\t{\n\t\t\tthis.method_token = methodToken;\n\t\t}\n\t}\n\n\tpublic delegate Instruction InstructionMapper (int offset);\n\n\tpublic interface ISymbolReader : IDisposable {\n\n\t\tbool ProcessDebugHeader (ImageDebugDirectory directory, byte [] header);\n\t\tvoid Read (MethodBody body, InstructionMapper mapper);\n\t\tvoid Read (MethodSymbols symbols);\n\t}\n\n\tpublic interface ISymbolReaderProvider {\n\n\t\tISymbolReader GetSymbolReader (ModuleDefinition module, string fileName);\n\t\tISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream);\n\t}\n\n\tstatic class SymbolProvider {\n\n\t\tstatic readonly string symbol_kind = Type.GetType (\"Mono.Runtime\") != null ? \"Mdb\" : \"Pdb\";\n\n\t\tstatic SR.AssemblyName GetPlatformSymbolAssemblyName ()\n\t\t{\n\t\t\tvar cecil_name = typeof (SymbolProvider).Assembly.GetName ();\n\n\t\t\tvar name = new SR.AssemblyName {\n\t\t\t\tName = \"Mono.Cecil.\" + symbol_kind,\n\t\t\t\tVersion = cecil_name.Version,\n\t\t\t};\n\n\t\t\tname.SetPublicKeyToken (cecil_name.GetPublicKeyToken ());\n\n\t\t\treturn name;\n\t\t}\n\n\t\tstatic Type GetPlatformType (string fullname)\n\t\t{\n\t\t\tvar type = Type.GetType (fullname);\n\t\t\tif (type != null)\n\t\t\t\treturn type;\n\n\t\t\tvar assembly_name = GetPlatformSymbolAssemblyName ();\n\n\t\t\ttype = Type.GetType (fullname + \", \" + assembly_name.FullName);\n\t\t\tif (type != null)\n\t\t\t\treturn type;\n\n\t\t\ttry {\n\t\t\t\tvar assembly = SR.Assembly.Load (assembly_name);\n\t\t\t\tif (assembly != null)\n\t\t\t\t\treturn assembly.GetType (fullname);\n\t\t\t} catch (FileNotFoundException) {\n\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\n\t\tstatic ISymbolReaderProvider reader_provider;\n\n\t\tpublic static ISymbolReaderProvider GetPlatformReaderProvider ()\n\t\t{\n\t\t\tif (reader_provider != null)\n\t\t\t\treturn reader_provider;\n\n\t\t\tvar type = GetPlatformType (GetProviderTypeName (\"ReaderProvider\"));\n\t\t\tif (type == null)\n\t\t\t\treturn null;\n\n\t\t\treturn reader_provider = (ISymbolReaderProvider) Activator.CreateInstance (type);\n\t\t}\n\n\t\tstatic string GetProviderTypeName (string name)\n\t\t{\n\t\t\treturn \"Mono.Cecil.\" + symbol_kind + \".\" + symbol_kind + name;\n\t\t}\n\n\n\t}\n\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/VariableDefinition.cs",
    "content": "//\n// VariableDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic sealed class VariableDefinition : VariableReference {\n\n\t\tpublic bool IsPinned {\n\t\t\tget { return variable_type.IsPinned; }\n\t\t}\n\n\t\tpublic VariableDefinition (TypeReference variableType)\n\t\t\t: base (variableType)\n\t\t{\n\t\t}\n\n\t\tpublic VariableDefinition (string name, TypeReference variableType)\n\t\t\t: base (name, variableType)\n\t\t{\n\t\t}\n\n\t\tpublic override VariableDefinition Resolve ()\n\t\t{\n\t\t\treturn this;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/VariableReference.cs",
    "content": "//\n// VariableReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic abstract class VariableReference {\n\n\t\tstring name;\n\t\tinternal int index = -1;\n\t\tprotected TypeReference variable_type;\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic TypeReference VariableType {\n\t\t\tget { return variable_type; }\n\t\t\tset { variable_type = value; }\n\t\t}\n\n\t\tpublic int Index {\n\t\t\tget { return index; }\n\t\t}\n\n\t\tinternal VariableReference (TypeReference variable_type)\n\t\t\t: this (string.Empty, variable_type)\n\t\t{\n\t\t}\n\n\t\tinternal VariableReference (string name, TypeReference variable_type)\n\t\t{\n\t\t\tthis.name = name;\n\t\t\tthis.variable_type = variable_type;\n\t\t}\n\n\t\tpublic abstract VariableDefinition Resolve ();\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\tif (!string.IsNullOrEmpty (name))\n\t\t\t\treturn name;\n\n\t\t\tif (index >= 0)\n\t\t\t\treturn \"V_\" + index;\n\n\t\t\treturn string.Empty;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/BlobHeap.cs",
    "content": "//\n// BlobHeap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata\n{\n\n    sealed class BlobHeap : Heap\n    {\n\n        public BlobHeap(Section section, uint start, uint size)\n            : base(section, start, size)\n        {\n        }\n\n        public byte[] Read(uint index)\n        {\n            if (index == 0 || index > Size - 1)\n                return Empty<byte>.Array;\n\n            var data = Section.Data;\n\n            int position = (int)(index + Offset);\n            int length = (int)Mixin.ReadCompressedUInt32(data, ref position);\n\n            var buffer = new byte[length];\n\n            Buffer.BlockCopy(data, position, buffer, 0, length);\n\n            return buffer;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/Buffers.cs",
    "content": "//\n// TableHeapBuffer.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nusing Mono.Cecil.PE;\n\nusing RVA = System.UInt32;\n\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/CodedIndex.cs",
    "content": "//\n// CodedIndex.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Metadata {\n\n\tenum CodedIndex {\n\t\tTypeDefOrRef,\n\t\tHasConstant,\n\t\tHasCustomAttribute,\n\t\tHasFieldMarshal,\n\t\tHasDeclSecurity,\n\t\tMemberRefParent,\n\t\tHasSemantics,\n\t\tMethodDefOrRef,\n\t\tMemberForwarded,\n\t\tImplementation,\n\t\tCustomAttributeType,\n\t\tResolutionScope,\n\t\tTypeOrMethodDef\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/ElementType.cs",
    "content": "//\n// ElementType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Metadata {\n\n\tenum ElementType : byte {\n\t\tNone = 0x00,\n\t\tVoid = 0x01,\n\t\tBoolean = 0x02,\n\t\tChar = 0x03,\n\t\tI1 = 0x04,\n\t\tU1 = 0x05,\n\t\tI2 = 0x06,\n\t\tU2 = 0x07,\n\t\tI4 = 0x08,\n\t\tU4 = 0x09,\n\t\tI8 = 0x0a,\n\t\tU8 = 0x0b,\n\t\tR4 = 0x0c,\n\t\tR8 = 0x0d,\n\t\tString = 0x0e,\n\t\tPtr = 0x0f,   // Followed by <type> token\n\t\tByRef = 0x10,   // Followed by <type> token\n\t\tValueType = 0x11,   // Followed by <type> token\n\t\tClass = 0x12,   // Followed by <type> token\n\t\tVar = 0x13,   // Followed by generic parameter number\n\t\tArray = 0x14,   // <type> <rank> <boundsCount> <bound1>  <loCount> <lo1>\n\t\tGenericInst = 0x15,   // <type> <type-arg-count> <type-1> ... <type-n> */\n\t\tTypedByRef = 0x16,\n\t\tI = 0x18,   // System.IntPtr\n\t\tU = 0x19,   // System.UIntPtr\n\t\tFnPtr = 0x1b,   // Followed by full method signature\n\t\tObject = 0x1c,   // System.Object\n\t\tSzArray = 0x1d,   // Single-dim array with 0 lower bound\n\t\tMVar = 0x1e,   // Followed by generic parameter number\n\t\tCModReqD = 0x1f,   // Required modifier : followed by a TypeDef or TypeRef token\n\t\tCModOpt = 0x20,   // Optional modifier : followed by a TypeDef or TypeRef token\n\t\tInternal = 0x21,   // Implemented within the CLI\n\t\tModifier = 0x40,   // Or'd with following element types\n\t\tSentinel = 0x41,   // Sentinel for varargs method signature\n\t\tPinned = 0x45,   // Denotes a local variable that points at a pinned object\n\n\t\t// special undocumented constants\n\t\tType = 0x50,\n\t\tBoxed = 0x51,\n\t\tEnum = 0x55\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/GuidHeap.cs",
    "content": "//\n// GuidHeap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata {\n\n\tsealed class GuidHeap : Heap {\n\n\t\tpublic GuidHeap (Section section, uint start, uint size)\n\t\t\t: base (section, start, size)\n\t\t{\n\t\t}\n\n\t\tpublic Guid Read (uint index)\n\t\t{\n\t\t\tif (index == 0)\n\t\t\t\treturn new Guid ();\n\n\t\t\tconst int guid_size = 16;\n\n\t\t\tvar buffer = new byte [guid_size];\n\n\t\t\tindex--;\n\n\t\t\tBuffer.BlockCopy (Section.Data, (int) (Offset + index), buffer, 0, guid_size);\n\n\t\t\treturn new Guid (buffer);\n\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/Heap.cs",
    "content": "//\n// Heap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata {\n\n\tabstract class Heap {\n\n\t\tpublic int IndexSize;\n\n\t\tpublic readonly Section Section;\n\t\tpublic readonly uint Offset;\n\t\tpublic readonly uint Size;\n\n\t\tprotected Heap (Section section, uint offset, uint size)\n\t\t{\n\t\t\tthis.Section = section;\n\t\t\tthis.Offset = offset;\n\t\t\tthis.Size = size;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/MetadataToken.cs",
    "content": "//\n// MetadataToken.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic struct MetadataToken {\n\n\t\treadonly uint token;\n\n\t\tpublic uint RID\t{\n\t\t\tget { return token & 0x00ffffff; }\n\t\t}\n\n\t\tpublic TokenType TokenType {\n\t\t\tget { return (TokenType) (token & 0xff000000); }\n\t\t}\n\n\t\tpublic static readonly MetadataToken Zero = new MetadataToken ((uint) 0);\n\n\t\tpublic MetadataToken (uint token)\n\t\t{\n\t\t\tthis.token = token;\n\t\t}\n\n\t\tpublic MetadataToken (TokenType type)\n\t\t\t: this (type, 0)\n\t\t{\n\t\t}\n\n\t\tpublic MetadataToken (TokenType type, uint rid)\n\t\t{\n\t\t\ttoken = (uint) type | rid;\n\t\t}\n\n\t\tpublic MetadataToken (TokenType type, int rid)\n\t\t{\n\t\t\ttoken = (uint) type | (uint) rid;\n\t\t}\n\n\t\tpublic int ToInt32 ()\n\t\t{\n\t\t\treturn (int) token;\n\t\t}\n\n\t\tpublic uint ToUInt32 ()\n\t\t{\n\t\t\treturn token;\n\t\t}\n\n\t\tpublic override int GetHashCode ()\n\t\t{\n\t\t\treturn (int) token;\n\t\t}\n\n\t\tpublic override bool Equals (object obj)\n\t\t{\n\t\t\tif (obj is MetadataToken) {\n\t\t\t\tvar other = (MetadataToken) obj;\n\t\t\t\treturn other.token == token;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tpublic static bool operator == (MetadataToken one, MetadataToken other)\n\t\t{\n\t\t\treturn one.token == other.token;\n\t\t}\n\n\t\tpublic static bool operator != (MetadataToken one, MetadataToken other)\n\t\t{\n\t\t\treturn one.token != other.token;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn string.Format (\"[{0}:0x{1}]\", TokenType, RID.ToString (\"x4\"));\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/Row.cs",
    "content": "//\n// Row.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.Collections.Generic;\n\nnamespace Mono.Cecil.Metadata {\n\n\tclass Row<T1, T2> {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\n\t\tpublic Row (T1 col1, T2 col2)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t}\n\t}\n\n    class Row<T1, T2, T3>\n    {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\t\tinternal T3 Col3;\n\n\t\tpublic Row (T1 col1, T2 col2, T3 col3)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t\tCol3 = col3;\n\t\t}\n\t}\n\n    class Row<T1, T2, T3, T4>\n    {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\t\tinternal T3 Col3;\n\t\tinternal T4 Col4;\n\n\t\tpublic Row (T1 col1, T2 col2, T3 col3, T4 col4)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t\tCol3 = col3;\n\t\t\tCol4 = col4;\n\t\t}\n\t}\n\n    class Row<T1, T2, T3, T4, T5>\n    {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\t\tinternal T3 Col3;\n\t\tinternal T4 Col4;\n\t\tinternal T5 Col5;\n\n\t\tpublic Row (T1 col1, T2 col2, T3 col3, T4 col4, T5 col5)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t\tCol3 = col3;\n\t\t\tCol4 = col4;\n\t\t\tCol5 = col5;\n\t\t}\n\t}\n\n    class Row<T1, T2, T3, T4, T5, T6>\n    {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\t\tinternal T3 Col3;\n\t\tinternal T4 Col4;\n\t\tinternal T5 Col5;\n\t\tinternal T6 Col6;\n\n\t\tpublic Row (T1 col1, T2 col2, T3 col3, T4 col4, T5 col5, T6 col6)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t\tCol3 = col3;\n\t\t\tCol4 = col4;\n\t\t\tCol5 = col5;\n\t\t\tCol6 = col6;\n\t\t}\n\t}\n\n    class Row<T1, T2, T3, T4, T5, T6, T7, T8, T9>\n    {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\t\tinternal T3 Col3;\n\t\tinternal T4 Col4;\n\t\tinternal T5 Col5;\n\t\tinternal T6 Col6;\n\t\tinternal T7 Col7;\n\t\tinternal T8 Col8;\n\t\tinternal T9 Col9;\n\n\t\tpublic Row (T1 col1, T2 col2, T3 col3, T4 col4, T5 col5, T6 col6, T7 col7, T8 col8, T9 col9)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t\tCol3 = col3;\n\t\t\tCol4 = col4;\n\t\t\tCol5 = col5;\n\t\t\tCol6 = col6;\n\t\t\tCol7 = col7;\n\t\t\tCol8 = col8;\n\t\t\tCol9 = col9;\n\t\t}\n\t}\n\n\tsealed class RowEqualityComparer : IEqualityComparer<Row<string, string>>, IEqualityComparer<Row<uint, uint>>, IEqualityComparer<Row<uint, uint, uint>> {\n\n\t\tpublic bool Equals (Row<string, string> x, Row<string, string> y)\n\t\t{\n\t\t\treturn x.Col1 == y.Col1\n\t\t\t\t&& x.Col2 == y.Col2;\n\t\t}\n\n\t\tpublic int GetHashCode (Row<string, string> obj)\n\t\t{\n\t\t\tstring x = obj.Col1, y = obj.Col2;\n\t\t\treturn (x != null ? x.GetHashCode () : 0) ^ (y != null ? y.GetHashCode () : 0);\n\t\t}\n\n\t\tpublic bool Equals (Row<uint, uint> x, Row<uint, uint> y)\n\t\t{\n\t\t\treturn x.Col1 == y.Col1\n\t\t\t\t&& x.Col2 == y.Col2;\n\t\t}\n\n\t\tpublic int GetHashCode (Row<uint, uint> obj)\n\t\t{\n\t\t\treturn (int) (obj.Col1 ^ obj.Col2);\n\t\t}\n\n\t\tpublic bool Equals (Row<uint, uint, uint> x, Row<uint, uint, uint> y)\n\t\t{\n\t\t\treturn x.Col1 == y.Col1\n\t\t\t\t&& x.Col2 == y.Col2\n\t\t\t\t&& x.Col3 == y.Col3;\n\t\t}\n\n\t\tpublic int GetHashCode (Row<uint, uint, uint> obj)\n\t\t{\n\t\t\treturn (int) (obj.Col1 ^ obj.Col2 ^ obj.Col3);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/StringHeap.cs",
    "content": "//\n// StringHeap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata {\n\n\tclass StringHeap : Heap {\n\n\t\treadonly Dictionary<uint, string> strings = new Dictionary<uint, string> ();\n\n\t\tpublic StringHeap (Section section, uint start, uint size)\n\t\t\t: base (section, start, size)\n\t\t{\n\t\t}\n\n\t\tpublic string Read (uint index)\n\t\t{\n\t\t\tif (index == 0)\n\t\t\t\treturn string.Empty;\n\n\t\t\tstring @string;\n\t\t\tif (strings.TryGetValue (index, out @string))\n\t\t\t\treturn @string;\n\n\t\t\tif (index > Size - 1)\n\t\t\t\treturn string.Empty;\n\n\t\t\t@string = ReadStringAt (index);\n\t\t\tif (@string.Length != 0)\n\t\t\t\tstrings.Add (index, @string);\n\n\t\t\treturn @string;\n\t\t}\n\n\t\tprotected virtual string ReadStringAt (uint index)\n\t\t{\n\t\t\tint length = 0;\n\t\t\tbyte [] data = Section.Data;\n\t\t\tint start = (int) (index + Offset);\n\n\t\t\tfor (int i = start; ; i++) {\n\t\t\t\tif (data [i] == 0)\n\t\t\t\t\tbreak;\n\n\t\t\t\tlength++;\n\t\t\t}\n\n\t\t\treturn Encoding.UTF8.GetString (data, start, length);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/TableHeap.cs",
    "content": "//\n// TableHeap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata {\n\n\tenum Table : byte {\n\t\tModule = 0x00,\n\t\tTypeRef = 0x01,\n\t\tTypeDef = 0x02,\n\t\tFieldPtr = 0x03,\n\t\tField = 0x04,\n\t\tMethodPtr = 0x05,\n\t\tMethod = 0x06,\n\t\tParamPtr = 0x07,\n\t\tParam = 0x08,\n\t\tInterfaceImpl = 0x09,\n\t\tMemberRef = 0x0a,\n\t\tConstant = 0x0b,\n\t\tCustomAttribute = 0x0c,\n\t\tFieldMarshal = 0x0d,\n\t\tDeclSecurity = 0x0e,\n\t\tClassLayout = 0x0f,\n\t\tFieldLayout = 0x10,\n\t\tStandAloneSig = 0x11,\n\t\tEventMap = 0x12,\n\t\tEventPtr = 0x13,\n\t\tEvent = 0x14,\n\t\tPropertyMap = 0x15,\n\t\tPropertyPtr = 0x16,\n\t\tProperty = 0x17,\n\t\tMethodSemantics = 0x18,\n\t\tMethodImpl = 0x19,\n\t\tModuleRef = 0x1a,\n\t\tTypeSpec = 0x1b,\n\t\tImplMap = 0x1c,\n\t\tFieldRVA = 0x1d,\n\t\tEncLog = 0x1e,\n\t\tEncMap = 0x1f,\n\t\tAssembly = 0x20,\n\t\tAssemblyProcessor = 0x21,\n\t\tAssemblyOS = 0x22,\n\t\tAssemblyRef = 0x23,\n\t\tAssemblyRefProcessor = 0x24,\n\t\tAssemblyRefOS = 0x25,\n\t\tFile = 0x26,\n\t\tExportedType = 0x27,\n\t\tManifestResource = 0x28,\n\t\tNestedClass = 0x29,\n\t\tGenericParam = 0x2a,\n\t\tMethodSpec = 0x2b,\n\t\tGenericParamConstraint = 0x2c,\n\t}\n\n\tstruct TableInformation {\n\t\tpublic uint Offset;\n\t\tpublic uint Length;\n\t\tpublic uint RowSize;\n\t}\n\n\tsealed class TableHeap : Heap {\n\n\t\tpublic long Valid;\n\t\tpublic long Sorted;\n\n\t\tpublic const int TableCount = 45;\n\n\t\tpublic readonly TableInformation [] Tables = new TableInformation [TableCount];\n\n\t\tpublic TableInformation this [Table table] {\n\t\t\tget { return Tables [(int) table]; }\n\t\t}\n\n\t\tpublic TableHeap (Section section, uint start, uint size)\n\t\t\t: base (section, start, size)\n\t\t{\n\t\t}\n\n\t\tpublic bool HasTable (Table table)\n\t\t{\n\t\t\treturn (Valid & (1L << (int) table)) != 0;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/TokenType.cs",
    "content": "//\n// TokenType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum TokenType : uint {\n\t\tModule = 0x00000000,\n\t\tTypeRef = 0x01000000,\n\t\tTypeDef = 0x02000000,\n\t\tField = 0x04000000,\n\t\tMethod = 0x06000000,\n\t\tParam = 0x08000000,\n\t\tInterfaceImpl = 0x09000000,\n\t\tMemberRef = 0x0a000000,\n\t\tCustomAttribute = 0x0c000000,\n\t\tPermission = 0x0e000000,\n\t\tSignature = 0x11000000,\n\t\tEvent = 0x14000000,\n\t\tProperty = 0x17000000,\n\t\tModuleRef = 0x1a000000,\n\t\tTypeSpec = 0x1b000000,\n\t\tAssembly = 0x20000000,\n\t\tAssemblyRef = 0x23000000,\n\t\tFile = 0x26000000,\n\t\tExportedType = 0x27000000,\n\t\tManifestResource = 0x28000000,\n\t\tGenericParam = 0x2a000000,\n\t\tMethodSpec = 0x2b000000,\n\t\tString = 0x70000000,\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/UserStringHeap.cs",
    "content": "//\n// UserStringHeap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata\n{\n\n    sealed class UserStringHeap : StringHeap\n    {\n\n        public UserStringHeap(Section section, uint start, uint size)\n            : base(section, start, size)\n        {\n        }\n\n        protected override string ReadStringAt(uint index)\n        {\n            byte[] data = Section.Data;\n            int start = (int)(index + Offset);\n\n            uint length = (uint)(Mixin.ReadCompressedUInt32(data, ref start) & ~1);\n            if (length < 1)\n                return string.Empty;\n\n            var chars = new char[length / 2];\n\n            for (int i = start, j = 0; i < start + length; i += 2)\n                chars[j++] = (char)(data[i] | (data[i + 1] << 8));\n\n            return new string(chars);\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/Utilities.cs",
    "content": "//\n// Utilities.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil\n{\n\n    static partial class Mixin\n    {\n\n        public static uint ReadCompressedUInt32(byte[] data, ref int position)\n        {\n            uint integer;\n            if ((data[position] & 0x80) == 0)\n            {\n                integer = data[position];\n                position++;\n            }\n            else if ((data[position] & 0x40) == 0)\n            {\n                integer = (uint)(data[position] & ~0x80) << 8;\n                integer |= data[position + 1];\n                position += 2;\n            }\n            else\n            {\n                integer = (uint)(data[position] & ~0xc0) << 24;\n                integer |= (uint)data[position + 1] << 16;\n                integer |= (uint)data[position + 2] << 8;\n                integer |= (uint)data[position + 3];\n                position += 4;\n            }\n            return integer;\n        }\n\n        public static MetadataToken GetMetadataToken(CodedIndex self, uint data)\n        {\n            uint rid;\n            TokenType token_type;\n            switch (self)\n            {\n                case CodedIndex.TypeDefOrRef:\n                    rid = data >> 2;\n                    switch (data & 3)\n                    {\n                        case 0:\n                            token_type = TokenType.TypeDef; goto ret;\n                        case 1:\n                            token_type = TokenType.TypeRef; goto ret;\n                        case 2:\n                            token_type = TokenType.TypeSpec; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.HasConstant:\n                    rid = data >> 2;\n                    switch (data & 3)\n                    {\n                        case 0:\n                            token_type = TokenType.Field; goto ret;\n                        case 1:\n                            token_type = TokenType.Param; goto ret;\n                        case 2:\n                            token_type = TokenType.Property; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.HasCustomAttribute:\n                    rid = data >> 5;\n                    switch (data & 31)\n                    {\n                        case 0:\n                            token_type = TokenType.Method; goto ret;\n                        case 1:\n                            token_type = TokenType.Field; goto ret;\n                        case 2:\n                            token_type = TokenType.TypeRef; goto ret;\n                        case 3:\n                            token_type = TokenType.TypeDef; goto ret;\n                        case 4:\n                            token_type = TokenType.Param; goto ret;\n                        case 5:\n                            token_type = TokenType.InterfaceImpl; goto ret;\n                        case 6:\n                            token_type = TokenType.MemberRef; goto ret;\n                        case 7:\n                            token_type = TokenType.Module; goto ret;\n                        case 8:\n                            token_type = TokenType.Permission; goto ret;\n                        case 9:\n                            token_type = TokenType.Property; goto ret;\n                        case 10:\n                            token_type = TokenType.Event; goto ret;\n                        case 11:\n                            token_type = TokenType.Signature; goto ret;\n                        case 12:\n                            token_type = TokenType.ModuleRef; goto ret;\n                        case 13:\n                            token_type = TokenType.TypeSpec; goto ret;\n                        case 14:\n                            token_type = TokenType.Assembly; goto ret;\n                        case 15:\n                            token_type = TokenType.AssemblyRef; goto ret;\n                        case 16:\n                            token_type = TokenType.File; goto ret;\n                        case 17:\n                            token_type = TokenType.ExportedType; goto ret;\n                        case 18:\n                            token_type = TokenType.ManifestResource; goto ret;\n                        case 19:\n                            token_type = TokenType.GenericParam; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.HasFieldMarshal:\n                    rid = data >> 1;\n                    switch (data & 1)\n                    {\n                        case 0:\n                            token_type = TokenType.Field; goto ret;\n                        case 1:\n                            token_type = TokenType.Param; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.HasDeclSecurity:\n                    rid = data >> 2;\n                    switch (data & 3)\n                    {\n                        case 0:\n                            token_type = TokenType.TypeDef; goto ret;\n                        case 1:\n                            token_type = TokenType.Method; goto ret;\n                        case 2:\n                            token_type = TokenType.Assembly; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.MemberRefParent:\n                    rid = data >> 3;\n                    switch (data & 7)\n                    {\n                        case 0:\n                            token_type = TokenType.TypeDef; goto ret;\n                        case 1:\n                            token_type = TokenType.TypeRef; goto ret;\n                        case 2:\n                            token_type = TokenType.ModuleRef; goto ret;\n                        case 3:\n                            token_type = TokenType.Method; goto ret;\n                        case 4:\n                            token_type = TokenType.TypeSpec; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.HasSemantics:\n                    rid = data >> 1;\n                    switch (data & 1)\n                    {\n                        case 0:\n                            token_type = TokenType.Event; goto ret;\n                        case 1:\n                            token_type = TokenType.Property; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.MethodDefOrRef:\n                    rid = data >> 1;\n                    switch (data & 1)\n                    {\n                        case 0:\n                            token_type = TokenType.Method; goto ret;\n                        case 1:\n                            token_type = TokenType.MemberRef; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.MemberForwarded:\n                    rid = data >> 1;\n                    switch (data & 1)\n                    {\n                        case 0:\n                            token_type = TokenType.Field; goto ret;\n                        case 1:\n                            token_type = TokenType.Method; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.Implementation:\n                    rid = data >> 2;\n                    switch (data & 3)\n                    {\n                        case 0:\n                            token_type = TokenType.File; goto ret;\n                        case 1:\n                            token_type = TokenType.AssemblyRef; goto ret;\n                        case 2:\n                            token_type = TokenType.ExportedType; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.CustomAttributeType:\n                    rid = data >> 3;\n                    switch (data & 7)\n                    {\n                        case 2:\n                            token_type = TokenType.Method; goto ret;\n                        case 3:\n                            token_type = TokenType.MemberRef; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.ResolutionScope:\n                    rid = data >> 2;\n                    switch (data & 3)\n                    {\n                        case 0:\n                            token_type = TokenType.Module; goto ret;\n                        case 1:\n                            token_type = TokenType.ModuleRef; goto ret;\n                        case 2:\n                            token_type = TokenType.AssemblyRef; goto ret;\n                        case 3:\n                            token_type = TokenType.TypeRef; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.TypeOrMethodDef:\n                    rid = data >> 1;\n                    switch (data & 1)\n                    {\n                        case 0:\n                            token_type = TokenType.TypeDef; goto ret;\n                        case 1:\n                            token_type = TokenType.Method; goto ret;\n                        default: goto exit;\n                    }\n                default:\n                    goto exit;\n            }\n        ret:\n            return new MetadataToken(token_type, rid);\n        exit:\n            return MetadataToken.Zero;\n        }\n\n\n        public static int GetSize(CodedIndex self, Func<Table, int> counter)\n        {\n            int bits;\n            Table[] tables;\n\n            switch (self)\n            {\n                case CodedIndex.TypeDefOrRef:\n                    bits = 2;\n                    tables = new[] { Table.TypeDef, Table.TypeRef, Table.TypeSpec };\n                    break;\n                case CodedIndex.HasConstant:\n                    bits = 2;\n                    tables = new[] { Table.Field, Table.Param, Table.Property };\n                    break;\n                case CodedIndex.HasCustomAttribute:\n                    bits = 5;\n                    tables = new[] {\n\t\t\t\t\tTable.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef,\n\t\t\t\t\tTable.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef,\n\t\t\t\t\tTable.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType,\n\t\t\t\t\tTable.ManifestResource, Table.GenericParam\n\t\t\t\t};\n                    break;\n                case CodedIndex.HasFieldMarshal:\n                    bits = 1;\n                    tables = new[] { Table.Field, Table.Param };\n                    break;\n                case CodedIndex.HasDeclSecurity:\n                    bits = 2;\n                    tables = new[] { Table.TypeDef, Table.Method, Table.Assembly };\n                    break;\n                case CodedIndex.MemberRefParent:\n                    bits = 3;\n                    tables = new[] { Table.TypeDef, Table.TypeRef, Table.ModuleRef, Table.Method, Table.TypeSpec };\n                    break;\n                case CodedIndex.HasSemantics:\n                    bits = 1;\n                    tables = new[] { Table.Event, Table.Property };\n                    break;\n                case CodedIndex.MethodDefOrRef:\n                    bits = 1;\n                    tables = new[] { Table.Method, Table.MemberRef };\n                    break;\n                case CodedIndex.MemberForwarded:\n                    bits = 1;\n                    tables = new[] { Table.Field, Table.Method };\n                    break;\n                case CodedIndex.Implementation:\n                    bits = 2;\n                    tables = new[] { Table.File, Table.AssemblyRef, Table.ExportedType };\n                    break;\n                case CodedIndex.CustomAttributeType:\n                    bits = 3;\n                    tables = new[] { Table.Method, Table.MemberRef };\n                    break;\n                case CodedIndex.ResolutionScope:\n                    bits = 2;\n                    tables = new[] { Table.Module, Table.ModuleRef, Table.AssemblyRef, Table.TypeRef };\n                    break;\n                case CodedIndex.TypeOrMethodDef:\n                    bits = 1;\n                    tables = new[] { Table.TypeDef, Table.Method };\n                    break;\n                default:\n                    throw new ArgumentException();\n            }\n\n            int max = 0;\n\n            for (int i = 0; i < tables.Length; i++)\n            {\n                max = System.Math.Max(counter(tables[i]), max);\n            }\n\n            return max < (1 << (16 - bits)) ? 2 : 4;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/BinaryStreamReader.cs",
    "content": "//\n// BinaryStreamReader.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\n\nnamespace Mono.Cecil.PE {\n\n\tclass BinaryStreamReader : BinaryReader {\n\n\t\tpublic BinaryStreamReader (Stream stream)\n\t\t\t: base (stream)\n\t\t{\n\t\t}\n\n\t\tprotected void Advance (int bytes)\n\t\t{\n\t\t\tBaseStream.Seek (bytes, SeekOrigin.Current);\n\t\t}\n\n\t\tprotected DataDirectory ReadDataDirectory ()\n\t\t{\n\t\t\treturn new DataDirectory (ReadUInt32 (), ReadUInt32 ());\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/BinaryStreamWriter.cs",
    "content": "//\n// BinaryStreamWriter.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\n\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/ByteBuffer.cs",
    "content": "//\n// ByteBuffer.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil.PE {\n\n\tclass ByteBuffer {\n\n\t\tinternal byte [] buffer;\n\t\tinternal int length;\n\t\tinternal int position;\n\n\t\tpublic ByteBuffer ()\n\t\t{\n\t\t\tthis.buffer = Empty<byte>.Array;\n\t\t}\n\n\t\tpublic ByteBuffer (int length)\n\t\t{\n\t\t\tthis.buffer = new byte [length];\n\t\t}\n\n\t\tpublic ByteBuffer (byte [] buffer)\n\t\t{\n\t\t\tthis.buffer = buffer ?? Empty<byte>.Array;\n\t\t\tthis.length = this.buffer.Length;\n\t\t}\n\n\t\tpublic void Reset (byte [] buffer)\n\t\t{\n\t\t\tthis.buffer = buffer ?? Empty<byte>.Array;\n\t\t\tthis.length = this.buffer.Length;\n\t\t}\n\n\t\tpublic void Advance (int length)\n\t\t{\n\t\t\tposition += length;\n\t\t}\n\n\t\tpublic byte ReadByte ()\n\t\t{\n\t\t\treturn buffer [position++];\n\t\t}\n\n\t\tpublic sbyte ReadSByte ()\n\t\t{\n\t\t\treturn (sbyte) ReadByte ();\n\t\t}\n\n\t\tpublic byte [] ReadBytes (int length)\n\t\t{\n\t\t\tvar bytes = new byte [length];\n\t\t\tBuffer.BlockCopy (buffer, position, bytes, 0, length);\n\t\t\tposition += length;\n\t\t\treturn bytes;\n\t\t}\n\n\t\tpublic ushort ReadUInt16 ()\n\t\t{\n\t\t\tushort value = (ushort) (buffer [position]\n\t\t\t\t| (buffer [position + 1] << 8));\n\t\t\tposition += 2;\n\t\t\treturn value;\n\t\t}\n\n\t\tpublic short ReadInt16 ()\n\t\t{\n\t\t\treturn (short) ReadUInt16 ();\n\t\t}\n\n\t\tpublic uint ReadUInt32 ()\n\t\t{\n\t\t\tuint value = (uint) (buffer [position]\n\t\t\t\t| (buffer [position + 1] << 8)\n\t\t\t\t| (buffer [position + 2] << 16)\n\t\t\t\t| (buffer [position + 3] << 24));\n\t\t\tposition += 4;\n\t\t\treturn value;\n\t\t}\n\n\t\tpublic int ReadInt32 ()\n\t\t{\n\t\t\treturn (int) ReadUInt32 ();\n\t\t}\n\n\t\tpublic ulong ReadUInt64 ()\n\t\t{\n\t\t\tuint low = ReadUInt32 ();\n\t\t\tuint high = ReadUInt32 ();\n\n\t\t\treturn (((ulong) high) << 32) | low;\n\t\t}\n\n\t\tpublic long ReadInt64 ()\n\t\t{\n\t\t\treturn (long) ReadUInt64 ();\n\t\t}\n\n\t\tpublic uint ReadCompressedUInt32 ()\n\t\t{\n\t\t\tbyte first = ReadByte ();\n\t\t\tif ((first & 0x80) == 0)\n\t\t\t\treturn first;\n\n\t\t\tif ((first & 0x40) == 0)\n\t\t\t\treturn ((uint) (first & ~0x80) << 8)\n\t\t\t\t\t| ReadByte ();\n\n\t\t\treturn ((uint) (first & ~0xc0) << 24)\n\t\t\t\t| (uint) ReadByte () << 16\n\t\t\t\t| (uint) ReadByte () << 8\n\t\t\t\t| ReadByte ();\n\t\t}\n\n\t\tpublic int ReadCompressedInt32 ()\n\t\t{\n\t\t\tvar value = (int) (ReadCompressedUInt32 () >> 1);\n\t\t\tif ((value & 1) == 0)\n\t\t\t\treturn value;\n\t\t\tif (value < 0x40)\n\t\t\t\treturn value - 0x40;\n\t\t\tif (value < 0x2000)\n\t\t\t\treturn value - 0x2000;\n\t\t\tif (value < 0x10000000)\n\t\t\t\treturn value - 0x10000000;\n\t\t\treturn value - 0x20000000;\n\t\t}\n\n\t\tpublic float ReadSingle ()\n\t\t{\n\t\t\tif (!BitConverter.IsLittleEndian) {\n\t\t\t\tvar bytes = ReadBytes (4);\n\t\t\t\tArray.Reverse (bytes);\n\t\t\t\treturn BitConverter.ToSingle (bytes, 0);\n\t\t\t}\n\n\t\t\tfloat value = BitConverter.ToSingle (buffer, position);\n\t\t\tposition += 4;\n\t\t\treturn value;\n\t\t}\n\n\t\tpublic double ReadDouble ()\n\t\t{\n\t\t\tif (!BitConverter.IsLittleEndian) {\n\t\t\t\tvar bytes = ReadBytes (8);\n\t\t\t\tArray.Reverse (bytes);\n\t\t\t\treturn BitConverter.ToDouble (bytes, 0);\n\t\t\t}\n\n\t\t\tdouble value = BitConverter.ToDouble (buffer, position);\n\t\t\tposition += 8;\n\t\t\treturn value;\n\t\t}\n\n\n\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/ByteBufferEqualityComparer.cs",
    "content": "//\n// ByteBufferEqualityComparer.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\n\nnamespace Mono.Cecil.PE {\n\n\tsealed class ByteBufferEqualityComparer : IEqualityComparer<ByteBuffer> {\n\n\t\tpublic bool Equals (ByteBuffer x, ByteBuffer y)\n\t\t{\n\t\t\tif (x.length != y.length)\n\t\t\t\treturn false;\n\n\t\t\tvar x_buffer = x.buffer;\n\t\t\tvar y_buffer = y.buffer;\n\n\t\t\tfor (int i = 0; i < x.length; i++)\n\t\t\t\tif (x_buffer [i] != y_buffer [i])\n\t\t\t\t\treturn false;\n\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic int GetHashCode (ByteBuffer buffer)\n\t\t{\n#if !BYTE_BUFFER_WELL_DISTRIBUTED_HASH\n\t\t\tvar hash = 0;\n\t\t\tvar bytes = buffer.buffer;\n\t\t\tfor (int i = 0; i < buffer.length; i++)\n\t\t\t\thash = (hash * 37) ^ bytes [i];\n\n\t\t\treturn hash;\n#else\n\t\t\tconst uint p = 16777619;\n\t\t\tuint hash = 2166136261;\n\n\t\t\tvar bytes = buffer.buffer;\n\t\t\tfor (int i = 0; i < buffer.length; i++)\n\t\t\t    hash = (hash ^ bytes [i]) * p;\n\n\t\t\thash += hash << 13;\n\t\t\thash ^= hash >> 7;\n\t\t\thash += hash << 3;\n\t\t\thash ^= hash >> 17;\n\t\t\thash += hash << 5;\n\n\t\t\treturn (int) hash;\n#endif\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/DataDirectory.cs",
    "content": "//\n// DataDirectory.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil.PE {\n\n\tstruct DataDirectory {\n\n\t\tpublic readonly RVA VirtualAddress;\n\t\tpublic readonly uint Size;\n\n\t\tpublic bool IsZero {\n\t\t\tget { return VirtualAddress == 0 && Size == 0; }\n\t\t}\n\n\t\tpublic DataDirectory (RVA rva, uint size)\n\t\t{\n\t\t\tthis.VirtualAddress = rva;\n\t\t\tthis.Size = size;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/Image.cs",
    "content": "//\n// Image.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono;\nusing Mono.Cecil.Cil;\nusing Mono.Cecil.Metadata;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil.PE\n{\n\n    sealed class Image\n    {\n\n        public ModuleKind Kind;\n        public TargetRuntime Runtime;\n        public TargetArchitecture Architecture;\n        public ModuleCharacteristics Characteristics;\n        public string FileName;\n\n        public Section[] Sections;\n\n        public Section MetadataSection;\n\n        public uint EntryPointToken;\n        public ModuleAttributes Attributes;\n\n        public DataDirectory Debug;\n        public DataDirectory Resources;\n        public DataDirectory StrongName;\n\n        public StringHeap StringHeap;\n        public BlobHeap BlobHeap;\n        public UserStringHeap UserStringHeap;\n        public GuidHeap GuidHeap;\n        public TableHeap TableHeap;\n\n        readonly int[] coded_index_sizes = new int[13];\n\n        readonly Func<Table, int> counter;\n\n        public Image()\n        {\n            counter = GetTableLength;\n        }\n\n        public bool HasTable(Table table)\n        {\n            return GetTableLength(table) > 0;\n        }\n\n        public int GetTableLength(Table table)\n        {\n            return (int)TableHeap[table].Length;\n        }\n\n        public int GetTableIndexSize(Table table)\n        {\n            return GetTableLength(table) < 65536 ? 2 : 4;\n        }\n\n        public int GetCodedIndexSize(CodedIndex coded_index)\n        {\n            var index = (int)coded_index;\n            var size = coded_index_sizes[index];\n            if (size != 0)\n                return size;\n\n            return coded_index_sizes[index] = Mixin.GetSize(coded_index, counter);\n        }\n\n        public uint ResolveVirtualAddress(RVA rva)\n        {\n            var section = GetSectionAtVirtualAddress(rva);\n            if (section == null)\n                throw new ArgumentOutOfRangeException();\n\n            return ResolveVirtualAddressInSection(rva, section);\n        }\n\n        public uint ResolveVirtualAddressInSection(RVA rva, Section section)\n        {\n            return rva + section.PointerToRawData - section.VirtualAddress;\n        }\n\n        public Section GetSection(string name)\n        {\n            var sections = this.Sections;\n            for (int i = 0; i < sections.Length; i++)\n            {\n                var section = sections[i];\n                if (section.Name == name)\n                    return section;\n            }\n\n            return null;\n        }\n\n        public Section GetSectionAtVirtualAddress(RVA rva)\n        {\n            var sections = this.Sections;\n            for (int i = 0; i < sections.Length; i++)\n            {\n                var section = sections[i];\n                if (rva >= section.VirtualAddress && rva < section.VirtualAddress + section.SizeOfRawData)\n                    return section;\n            }\n\n            return null;\n        }\n\n        public ImageDebugDirectory GetDebugHeader(out byte[] header)\n        {\n            var section = GetSectionAtVirtualAddress(Debug.VirtualAddress);\n            var buffer = new ByteBuffer(section.Data);\n            buffer.position = (int)(Debug.VirtualAddress - section.VirtualAddress);\n\n            var directory = new ImageDebugDirectory\n            {\n                Characteristics = buffer.ReadInt32(),\n                TimeDateStamp = buffer.ReadInt32(),\n                MajorVersion = buffer.ReadInt16(),\n                MinorVersion = buffer.ReadInt16(),\n                Type = buffer.ReadInt32(),\n                SizeOfData = buffer.ReadInt32(),\n                AddressOfRawData = buffer.ReadInt32(),\n                PointerToRawData = buffer.ReadInt32(),\n            };\n\n            buffer.position = (int)(directory.PointerToRawData - section.PointerToRawData);\n\n            header = new byte[directory.SizeOfData];\n            Buffer.BlockCopy(buffer.buffer, buffer.position, header, 0, header.Length);\n\n            return directory;\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/ImageReader.cs",
    "content": "//\n// ImageReader.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\n\nusing Mono.Cecil.Metadata;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil.PE\n{\n\n    sealed class ImageReader : BinaryStreamReader\n    {\n\n        readonly Image image;\n\n        DataDirectory cli;\n        DataDirectory metadata;\n\n        public ImageReader(Stream stream)\n            : base(stream)\n        {\n            image = new Image();\n\n            image.FileName = Mixin.GetFullyQualifiedName(stream);\n        }\n\n        void MoveTo(DataDirectory directory)\n        {\n            BaseStream.Position = image.ResolveVirtualAddress(directory.VirtualAddress);\n        }\n\n        void MoveTo(uint position)\n        {\n            BaseStream.Position = position;\n        }\n\n        void ReadImage()\n        {\n            if (BaseStream.Length < 128)\n                throw new BadImageFormatException();\n\n            // - DOSHeader\n\n            // PE\t\t\t\t\t2\n            // Start\t\t\t\t58\n            // Lfanew\t\t\t\t4\n            // End\t\t\t\t\t64\n\n            if (ReadUInt16() != 0x5a4d)\n                throw new BadImageFormatException();\n\n            Advance(58);\n\n            MoveTo(ReadUInt32());\n\n            if (ReadUInt32() != 0x00004550)\n                throw new BadImageFormatException();\n\n            // - PEFileHeader\n\n            // Machine\t\t\t\t2\n            image.Architecture = ReadArchitecture();\n\n            // NumberOfSections\t\t2\n            ushort sections = ReadUInt16();\n\n            // TimeDateStamp\t\t4\n            // PointerToSymbolTable\t4\n            // NumberOfSymbols\t\t4\n            // OptionalHeaderSize\t2\n            Advance(14);\n\n            // Characteristics\t\t2\n            ushort characteristics = ReadUInt16();\n\n            ushort subsystem, dll_characteristics;\n            ReadOptionalHeaders(out subsystem, out dll_characteristics);\n            ReadSections(sections);\n            ReadCLIHeader();\n            ReadMetadata();\n\n            image.Kind = GetModuleKind(characteristics, subsystem);\n            image.Characteristics = (ModuleCharacteristics)dll_characteristics;\n        }\n\n        TargetArchitecture ReadArchitecture()\n        {\n            var machine = ReadUInt16();\n            switch (machine)\n            {\n                case 0x014c:\n                    return TargetArchitecture.I386;\n                case 0x8664:\n                    return TargetArchitecture.AMD64;\n                case 0x0200:\n                    return TargetArchitecture.IA64;\n                case 0x01c4:\n                    return TargetArchitecture.ARMv7;\n            }\n\n            throw new NotSupportedException();\n        }\n\n        static ModuleKind GetModuleKind(ushort characteristics, ushort subsystem)\n        {\n            if ((characteristics & 0x2000) != 0) // ImageCharacteristics.Dll\n                return ModuleKind.Dll;\n\n            if (subsystem == 0x2 || subsystem == 0x9) // SubSystem.WindowsGui || SubSystem.WindowsCeGui\n                return ModuleKind.Windows;\n\n            return ModuleKind.Console;\n        }\n\n        void ReadOptionalHeaders(out ushort subsystem, out ushort dll_characteristics)\n        {\n            // - PEOptionalHeader\n            //   - StandardFieldsHeader\n\n            // Magic\t\t\t\t2\n            bool pe64 = ReadUInt16() == 0x20b;\n\n            //\t\t\t\t\t\tpe32 || pe64\n\n            // LMajor\t\t\t\t1\n            // LMinor\t\t\t\t1\n            // CodeSize\t\t\t\t4\n            // InitializedDataSize\t4\n            // UninitializedDataSize4\n            // EntryPointRVA\t\t4\n            // BaseOfCode\t\t\t4\n            // BaseOfData\t\t\t4 || 0\n\n            //   - NTSpecificFieldsHeader\n\n            // ImageBase\t\t\t4 || 8\n            // SectionAlignment\t\t4\n            // FileAlignement\t\t4\n            // OSMajor\t\t\t\t2\n            // OSMinor\t\t\t\t2\n            // UserMajor\t\t\t2\n            // UserMinor\t\t\t2\n            // SubSysMajor\t\t\t2\n            // SubSysMinor\t\t\t2\n            // Reserved\t\t\t\t4\n            // ImageSize\t\t\t4\n            // HeaderSize\t\t\t4\n            // FileChecksum\t\t\t4\n            Advance(66);\n\n            // SubSystem\t\t\t2\n            subsystem = ReadUInt16();\n\n            // DLLFlags\t\t\t\t2\n            dll_characteristics = ReadUInt16();\n            // StackReserveSize\t\t4 || 8\n            // StackCommitSize\t\t4 || 8\n            // HeapReserveSize\t\t4 || 8\n            // HeapCommitSize\t\t4 || 8\n            // LoaderFlags\t\t\t4\n            // NumberOfDataDir\t\t4\n\n            //   - DataDirectoriesHeader\n\n            // ExportTable\t\t\t8\n            // ImportTable\t\t\t8\n            // ResourceTable\t\t8\n            // ExceptionTable\t\t8\n            // CertificateTable\t\t8\n            // BaseRelocationTable\t8\n\n            Advance(pe64 ? 88 : 72);\n\n            // Debug\t\t\t\t8\n            image.Debug = ReadDataDirectory();\n\n            // Copyright\t\t\t8\n            // GlobalPtr\t\t\t8\n            // TLSTable\t\t\t\t8\n            // LoadConfigTable\t\t8\n            // BoundImport\t\t\t8\n            // IAT\t\t\t\t\t8\n            // DelayImportDescriptor8\n            Advance(56);\n\n            // CLIHeader\t\t\t8\n            cli = ReadDataDirectory();\n\n            if (cli.IsZero)\n                throw new BadImageFormatException();\n\n            // Reserved\t\t\t\t8\n            Advance(8);\n        }\n\n        string ReadAlignedString(int length)\n        {\n            int read = 0;\n            var buffer = new char[length];\n            while (read < length)\n            {\n                var current = ReadByte();\n                if (current == 0)\n                    break;\n\n                buffer[read++] = (char)current;\n            }\n\n            Advance(-1 + ((read + 4) & ~3) - read);\n\n            return new string(buffer, 0, read);\n        }\n\n        string ReadZeroTerminatedString(int length)\n        {\n            int read = 0;\n            var buffer = new char[length];\n            var bytes = ReadBytes(length);\n            while (read < length)\n            {\n                var current = bytes[read];\n                if (current == 0)\n                    break;\n\n                buffer[read++] = (char)current;\n            }\n\n            return new string(buffer, 0, read);\n        }\n\n        void ReadSections(ushort count)\n        {\n            var sections = new Section[count];\n\n            for (int i = 0; i < count; i++)\n            {\n                var section = new Section();\n\n                // Name\n                section.Name = ReadZeroTerminatedString(8);\n\n                // VirtualSize\t\t4\n                Advance(4);\n\n                // VirtualAddress\t4\n                section.VirtualAddress = ReadUInt32();\n                // SizeOfRawData\t4\n                section.SizeOfRawData = ReadUInt32();\n                // PointerToRawData\t4\n                section.PointerToRawData = ReadUInt32();\n\n                // PointerToRelocations\t\t4\n                // PointerToLineNumbers\t\t4\n                // NumberOfRelocations\t\t2\n                // NumberOfLineNumbers\t\t2\n                // Characteristics\t\t\t4\n                Advance(16);\n\n                sections[i] = section;\n\n                ReadSectionData(section);\n            }\n\n            image.Sections = sections;\n        }\n\n        void ReadSectionData(Section section)\n        {\n            var position = BaseStream.Position;\n\n            MoveTo(section.PointerToRawData);\n\n            var length = (int)section.SizeOfRawData;\n            var data = new byte[length];\n            int offset = 0, read;\n\n            while ((read = Read(data, offset, length - offset)) > 0)\n                offset += read;\n\n            section.Data = data;\n\n            BaseStream.Position = position;\n        }\n\n        void ReadCLIHeader()\n        {\n            MoveTo(cli);\n\n            // - CLIHeader\n\n            // Cb\t\t\t\t\t\t4\n            // MajorRuntimeVersion\t\t2\n            // MinorRuntimeVersion\t\t2\n            Advance(8);\n\n            // Metadata\t\t\t\t\t8\n            metadata = ReadDataDirectory();\n            // Flags\t\t\t\t\t4\n            image.Attributes = (ModuleAttributes)ReadUInt32();\n            // EntryPointToken\t\t\t4\n            image.EntryPointToken = ReadUInt32();\n            // Resources\t\t\t\t8\n            image.Resources = ReadDataDirectory();\n            // StrongNameSignature\t\t8\n            image.StrongName = ReadDataDirectory();\n            // CodeManagerTable\t\t\t8\n            // VTableFixups\t\t\t\t8\n            // ExportAddressTableJumps\t8\n            // ManagedNativeHeader\t\t8\n        }\n\n        void ReadMetadata()\n        {\n            MoveTo(metadata);\n\n            if (ReadUInt32() != 0x424a5342)\n                throw new BadImageFormatException();\n\n            // MajorVersion\t\t\t2\n            // MinorVersion\t\t\t2\n            // Reserved\t\t\t\t4\n            Advance(8);\n\n            var version = ReadZeroTerminatedString(ReadInt32());\n            image.Runtime = Mixin.ParseRuntime(version);\n\n            // Flags\t\t2\n            Advance(2);\n\n            var streams = ReadUInt16();\n\n            var section = image.GetSectionAtVirtualAddress(metadata.VirtualAddress);\n            if (section == null)\n                throw new BadImageFormatException();\n\n            image.MetadataSection = section;\n\n            for (int i = 0; i < streams; i++)\n                ReadMetadataStream(section);\n\n            if (image.TableHeap != null)\n                ReadTableHeap();\n        }\n\n        void ReadMetadataStream(Section section)\n        {\n            // Offset\t\t4\n            uint start = metadata.VirtualAddress - section.VirtualAddress + ReadUInt32(); // relative to the section start\n\n            // Size\t\t\t4\n            uint size = ReadUInt32();\n\n            var name = ReadAlignedString(16);\n            switch (name)\n            {\n                case \"#~\":\n                case \"#-\":\n                    image.TableHeap = new TableHeap(section, start, size);\n                    break;\n                case \"#Strings\":\n                    image.StringHeap = new StringHeap(section, start, size);\n                    break;\n                case \"#Blob\":\n                    image.BlobHeap = new BlobHeap(section, start, size);\n                    break;\n                case \"#GUID\":\n                    image.GuidHeap = new GuidHeap(section, start, size);\n                    break;\n                case \"#US\":\n                    image.UserStringHeap = new UserStringHeap(section, start, size);\n                    break;\n            }\n        }\n\n        void ReadTableHeap()\n        {\n            var heap = image.TableHeap;\n\n            uint start = heap.Section.PointerToRawData;\n\n            MoveTo(heap.Offset + start);\n\n            // Reserved\t\t\t4\n            // MajorVersion\t\t1\n            // MinorVersion\t\t1\n            Advance(6);\n\n            // HeapSizes\t\t1\n            var sizes = ReadByte();\n\n            // Reserved2\t\t1\n            Advance(1);\n\n            // Valid\t\t\t8\n            heap.Valid = ReadInt64();\n\n            // Sorted\t\t\t8\n            heap.Sorted = ReadInt64();\n\n            for (int i = 0; i < TableHeap.TableCount; i++)\n            {\n                if (!heap.HasTable((Table)i))\n                    continue;\n\n                heap.Tables[i].Length = ReadUInt32();\n            }\n\n            SetIndexSize(image.StringHeap, sizes, 0x1);\n            SetIndexSize(image.GuidHeap, sizes, 0x2);\n            SetIndexSize(image.BlobHeap, sizes, 0x4);\n\n            ComputeTableInformations();\n        }\n\n        static void SetIndexSize(Heap heap, uint sizes, byte flag)\n        {\n            if (heap == null)\n                return;\n\n            heap.IndexSize = (sizes & flag) > 0 ? 4 : 2;\n        }\n\n        int GetTableIndexSize(Table table)\n        {\n            return image.GetTableIndexSize(table);\n        }\n\n        int GetCodedIndexSize(CodedIndex index)\n        {\n            return image.GetCodedIndexSize(index);\n        }\n\n        void ComputeTableInformations()\n        {\n            uint offset = (uint)BaseStream.Position - image.MetadataSection.PointerToRawData; // header\n\n            int stridx_size = image.StringHeap.IndexSize;\n            int blobidx_size = image.BlobHeap != null ? image.BlobHeap.IndexSize : 2;\n\n            var heap = image.TableHeap;\n            var tables = heap.Tables;\n\n            for (int i = 0; i < TableHeap.TableCount; i++)\n            {\n                var table = (Table)i;\n                if (!heap.HasTable(table))\n                    continue;\n\n                int size;\n                switch (table)\n                {\n                    case Table.Module:\n                        size = 2\t// Generation\n                            + stridx_size\t// Name\n                            + (image.GuidHeap.IndexSize * 3);\t// Mvid, EncId, EncBaseId\n                        break;\n                    case Table.TypeRef:\n                        size = GetCodedIndexSize(CodedIndex.ResolutionScope)\t// ResolutionScope\n                            + (stridx_size * 2);\t// Name, Namespace\n                        break;\n                    case Table.TypeDef:\n                        size = 4\t// Flags\n                            + (stridx_size * 2)\t// Name, Namespace\n                            + GetCodedIndexSize(CodedIndex.TypeDefOrRef)\t// BaseType\n                            + GetTableIndexSize(Table.Field)\t// FieldList\n                            + GetTableIndexSize(Table.Method);\t// MethodList\n                        break;\n                    case Table.FieldPtr:\n                        size = GetTableIndexSize(Table.Field);\t// Field\n                        break;\n                    case Table.Field:\n                        size = 2\t// Flags\n                            + stridx_size\t// Name\n                            + blobidx_size;\t// Signature\n                        break;\n                    case Table.MethodPtr:\n                        size = GetTableIndexSize(Table.Method);\t// Method\n                        break;\n                    case Table.Method:\n                        size = 8\t// Rva 4, ImplFlags 2, Flags 2\n                            + stridx_size\t// Name\n                            + blobidx_size\t// Signature\n                            + GetTableIndexSize(Table.Param); // ParamList\n                        break;\n                    case Table.ParamPtr:\n                        size = GetTableIndexSize(Table.Param); // Param\n                        break;\n                    case Table.Param:\n                        size = 4\t// Flags 2, Sequence 2\n                            + stridx_size;\t// Name\n                        break;\n                    case Table.InterfaceImpl:\n                        size = GetTableIndexSize(Table.TypeDef)\t// Class\n                            + GetCodedIndexSize(CodedIndex.TypeDefOrRef);\t// Interface\n                        break;\n                    case Table.MemberRef:\n                        size = GetCodedIndexSize(CodedIndex.MemberRefParent)\t// Class\n                            + stridx_size\t// Name\n                            + blobidx_size;\t// Signature\n                        break;\n                    case Table.Constant:\n                        size = 2\t// Type\n                            + GetCodedIndexSize(CodedIndex.HasConstant)\t// Parent\n                            + blobidx_size;\t// Value\n                        break;\n                    case Table.CustomAttribute:\n                        size = GetCodedIndexSize(CodedIndex.HasCustomAttribute)\t// Parent\n                            + GetCodedIndexSize(CodedIndex.CustomAttributeType)\t// Type\n                            + blobidx_size;\t// Value\n                        break;\n                    case Table.FieldMarshal:\n                        size = GetCodedIndexSize(CodedIndex.HasFieldMarshal)\t// Parent\n                            + blobidx_size;\t// NativeType\n                        break;\n                    case Table.DeclSecurity:\n                        size = 2\t// Action\n                            + GetCodedIndexSize(CodedIndex.HasDeclSecurity)\t// Parent\n                            + blobidx_size;\t// PermissionSet\n                        break;\n                    case Table.ClassLayout:\n                        size = 6\t// PackingSize 2, ClassSize 4\n                            + GetTableIndexSize(Table.TypeDef);\t// Parent\n                        break;\n                    case Table.FieldLayout:\n                        size = 4\t// Offset\n                            + GetTableIndexSize(Table.Field);\t// Field\n                        break;\n                    case Table.StandAloneSig:\n                        size = blobidx_size;\t// Signature\n                        break;\n                    case Table.EventMap:\n                        size = GetTableIndexSize(Table.TypeDef)\t// Parent\n                            + GetTableIndexSize(Table.Event);\t// EventList\n                        break;\n                    case Table.EventPtr:\n                        size = GetTableIndexSize(Table.Event);\t// Event\n                        break;\n                    case Table.Event:\n                        size = 2\t// Flags\n                            + stridx_size // Name\n                            + GetCodedIndexSize(CodedIndex.TypeDefOrRef);\t// EventType\n                        break;\n                    case Table.PropertyMap:\n                        size = GetTableIndexSize(Table.TypeDef)\t// Parent\n                            + GetTableIndexSize(Table.Property);\t// PropertyList\n                        break;\n                    case Table.PropertyPtr:\n                        size = GetTableIndexSize(Table.Property);\t// Property\n                        break;\n                    case Table.Property:\n                        size = 2\t// Flags\n                            + stridx_size\t// Name\n                            + blobidx_size;\t// Type\n                        break;\n                    case Table.MethodSemantics:\n                        size = 2\t// Semantics\n                            + GetTableIndexSize(Table.Method)\t// Method\n                            + GetCodedIndexSize(CodedIndex.HasSemantics);\t// Association\n                        break;\n                    case Table.MethodImpl:\n                        size = GetTableIndexSize(Table.TypeDef)\t// Class\n                            + GetCodedIndexSize(CodedIndex.MethodDefOrRef)\t// MethodBody\n                            + GetCodedIndexSize(CodedIndex.MethodDefOrRef);\t// MethodDeclaration\n                        break;\n                    case Table.ModuleRef:\n                        size = stridx_size;\t// Name\n                        break;\n                    case Table.TypeSpec:\n                        size = blobidx_size;\t// Signature\n                        break;\n                    case Table.ImplMap:\n                        size = 2\t// MappingFlags\n                            + GetCodedIndexSize(CodedIndex.MemberForwarded)\t// MemberForwarded\n                            + stridx_size\t// ImportName\n                            + GetTableIndexSize(Table.ModuleRef);\t// ImportScope\n                        break;\n                    case Table.FieldRVA:\n                        size = 4\t// RVA\n                            + GetTableIndexSize(Table.Field);\t// Field\n                        break;\n                    case Table.EncLog:\n                    case Table.EncMap:\n                        size = 4;\n                        break;\n                    case Table.Assembly:\n                        size = 16 // HashAlgId 4, Version 4 * 2, Flags 4\n                            + blobidx_size\t// PublicKey\n                            + (stridx_size * 2);\t// Name, Culture\n                        break;\n                    case Table.AssemblyProcessor:\n                        size = 4;\t// Processor\n                        break;\n                    case Table.AssemblyOS:\n                        size = 12;\t// Platform 4, Version 2 * 4\n                        break;\n                    case Table.AssemblyRef:\n                        size = 12\t// Version 2 * 4 + Flags 4\n                            + (blobidx_size * 2)\t// PublicKeyOrToken, HashValue\n                            + (stridx_size * 2);\t// Name, Culture\n                        break;\n                    case Table.AssemblyRefProcessor:\n                        size = 4\t// Processor\n                            + GetTableIndexSize(Table.AssemblyRef);\t// AssemblyRef\n                        break;\n                    case Table.AssemblyRefOS:\n                        size = 12\t// Platform 4, Version 2 * 4\n                            + GetTableIndexSize(Table.AssemblyRef);\t// AssemblyRef\n                        break;\n                    case Table.File:\n                        size = 4\t// Flags\n                            + stridx_size\t// Name\n                            + blobidx_size;\t// HashValue\n                        break;\n                    case Table.ExportedType:\n                        size = 8\t// Flags 4, TypeDefId 4\n                            + (stridx_size * 2)\t// Name, Namespace\n                            + GetCodedIndexSize(CodedIndex.Implementation);\t// Implementation\n                        break;\n                    case Table.ManifestResource:\n                        size = 8\t// Offset, Flags\n                            + stridx_size\t// Name\n                            + GetCodedIndexSize(CodedIndex.Implementation);\t// Implementation\n                        break;\n                    case Table.NestedClass:\n                        size = GetTableIndexSize(Table.TypeDef)\t// NestedClass\n                            + GetTableIndexSize(Table.TypeDef);\t// EnclosingClass\n                        break;\n                    case Table.GenericParam:\n                        size = 4\t// Number, Flags\n                            + GetCodedIndexSize(CodedIndex.TypeOrMethodDef)\t// Owner\n                            + stridx_size;\t// Name\n                        break;\n                    case Table.MethodSpec:\n                        size = GetCodedIndexSize(CodedIndex.MethodDefOrRef)\t// Method\n                            + blobidx_size;\t// Instantiation\n                        break;\n                    case Table.GenericParamConstraint:\n                        size = GetTableIndexSize(Table.GenericParam)\t// Owner\n                            + GetCodedIndexSize(CodedIndex.TypeDefOrRef);\t// Constraint\n                        break;\n                    default:\n                        throw new NotSupportedException();\n                }\n\n                tables[i].RowSize = (uint)size;\n                tables[i].Offset = offset;\n\n                offset += (uint)size * tables[i].Length;\n            }\n        }\n\n        public static Image ReadImageFrom(Stream stream)\n        {\n            try\n            {\n                var reader = new ImageReader(stream);\n                reader.ReadImage();\n                return reader.image;\n            }\n            catch (EndOfStreamException e)\n            {\n                throw new BadImageFormatException(Mixin.GetFullyQualifiedName(stream), e);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/ImageWriter.cs",
    "content": ""
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/Section.cs",
    "content": "//\n// Section.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil.PE {\n\n\tsealed class Section {\n\t\tpublic string Name;\n\t\tpublic RVA VirtualAddress;\n\t\tpublic uint VirtualSize;\n\t\tpublic uint SizeOfRawData;\n\t\tpublic uint PointerToRawData;\n\t\tpublic byte [] Data;\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/TextMap.cs",
    "content": ""
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Collections.Generic/Collection.cs",
    "content": "//\n// Collection.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace Mono.Collections.Generic {\n\n\tpublic class Collection<T> : IList<T>, IList {\n\n\t\tinternal T [] items;\n\t\tinternal int size;\n\t\tint version;\n\n\t\tpublic int Count {\n\t\t\tget { return size; }\n\t\t}\n\n\t\tpublic T this [int index] {\n\t\t\tget {\n\t\t\t\tif (index >= size)\n\t\t\t\t\tthrow new ArgumentOutOfRangeException ();\n\n\t\t\t\treturn items [index];\n\t\t\t}\n\t\t\tset {\n\t\t\t\tCheckIndex (index);\n\t\t\t\tif (index == size)\n\t\t\t\t\tthrow new ArgumentOutOfRangeException ();\n\n\t\t\t\tOnSet (value, index);\n\n\t\t\t\titems [index] = value;\n\t\t\t}\n\t\t}\n\n\t\tbool ICollection<T>.IsReadOnly {\n\t\t\tget { return false; }\n\t\t}\n\n\t\tbool IList.IsFixedSize {\n\t\t\tget { return false; }\n\t\t}\n\n\t\tbool IList.IsReadOnly {\n\t\t\tget { return false; }\n\t\t}\n\n\t\tobject IList.this [int index] {\n\t\t\tget { return this [index]; }\n\t\t\tset {\n\t\t\t\tCheckIndex (index);\n\n\t\t\t\ttry {\n\t\t\t\t\tthis [index] = (T) value;\n\t\t\t\t\treturn;\n\t\t\t\t} catch (InvalidCastException) {\n\t\t\t\t} catch (NullReferenceException) {\n\t\t\t\t}\n\n\t\t\t\tthrow new ArgumentException ();\n\t\t\t}\n\t\t}\n\n\t\tint ICollection.Count {\n\t\t\tget { return Count; }\n\t\t}\n\n\t\tbool ICollection.IsSynchronized {\n\t\t\tget { return false; }\n\t\t}\n\n\t\tobject ICollection.SyncRoot {\n\t\t\tget { return this; }\n\t\t}\n\n\t\tpublic Collection ()\n\t\t{\n\t\t\titems = Empty<T>.Array;\n\t\t}\n\n\t\tpublic Collection (int capacity)\n\t\t{\n\t\t\tif (capacity < 0)\n\t\t\t\tthrow new ArgumentOutOfRangeException ();\n\n\t\t\titems = new T [capacity];\n\t\t}\n\n\t\tpublic Collection (ICollection<T> items)\n\t\t{\n\t\t\tif (items == null)\n\t\t\t\tthrow new ArgumentNullException (\"items\");\n\n\t\t\tthis.items = new T [items.Count];\n\t\t\titems.CopyTo (this.items, 0);\n\t\t\tthis.size = this.items.Length;\n\t\t}\n\n\t\tpublic void Add (T item)\n\t\t{\n\t\t\tif (size == items.Length)\n\t\t\t\tGrow (1);\n\n\t\t\tOnAdd (item, size);\n\n\t\t\titems [size++] = item;\n\t\t\tversion++;\n\t\t}\n\n\t\tpublic bool Contains (T item)\n\t\t{\n\t\t\treturn IndexOf (item) != -1;\n\t\t}\n\n\t\tpublic int IndexOf (T item)\n\t\t{\n\t\t\treturn Array.IndexOf (items, item, 0, size);\n\t\t}\n\n\t\tpublic void Insert (int index, T item)\n\t\t{\n\t\t\tCheckIndex (index);\n\t\t\tif (size == items.Length)\n\t\t\t\tGrow (1);\n\n\t\t\tOnInsert (item, index);\n\n\t\t\tShift (index, 1);\n\t\t\titems [index] = item;\n\t\t\tversion++;\n\t\t}\n\n\t\tpublic void RemoveAt (int index)\n\t\t{\n\t\t\tif (index < 0 || index >= size)\n\t\t\t\tthrow new ArgumentOutOfRangeException ();\n\n\t\t\tvar item = items [index];\n\n\t\t\tOnRemove (item, index);\n\n\t\t\tShift (index, -1);\n\t\t\tArray.Clear (items, size, 1);\n\t\t\tversion++;\n\t\t}\n\n\t\tpublic bool Remove (T item)\n\t\t{\n\t\t\tvar index = IndexOf (item);\n\t\t\tif (index == -1)\n\t\t\t\treturn false;\n\n\t\t\tOnRemove (item, index);\n\n\t\t\tShift (index, -1);\n\t\t\tArray.Clear (items, size, 1);\n\t\t\tversion++;\n\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic void Clear ()\n\t\t{\n\t\t\tOnClear ();\n\n\t\t\tArray.Clear (items, 0, size);\n\t\t\tsize = 0;\n\t\t\tversion++;\n\t\t}\n\n\t\tpublic void CopyTo (T [] array, int arrayIndex)\n\t\t{\n\t\t\tArray.Copy (items, 0, array, arrayIndex, size);\n\t\t}\n\n\t\tpublic T [] ToArray ()\n\t\t{\n\t\t\tvar array = new T [size];\n\t\t\tArray.Copy (items, 0, array, 0, size);\n\t\t\treturn array;\n\t\t}\n\n\t\tvoid CheckIndex (int index)\n\t\t{\n\t\t\tif (index < 0 || index > size)\n\t\t\t\tthrow new ArgumentOutOfRangeException ();\n\t\t}\n\n\t\tvoid Shift (int start, int delta)\n\t\t{\n\t\t\tif (delta < 0)\n\t\t\t\tstart -= delta;\n\n\t\t\tif (start < size)\n\t\t\t\tArray.Copy (items, start, items, start + delta, size - start);\n\n\t\t\tsize += delta;\n\n\t\t\tif (delta < 0)\n\t\t\t\tArray.Clear (items, size, -delta);\n\t\t}\n\n\t\tprotected virtual void OnAdd (T item, int index)\n\t\t{\n\t\t}\n\n\t\tprotected virtual void OnInsert (T item, int index)\n\t\t{\n\t\t}\n\n\t\tprotected virtual void OnSet (T item, int index)\n\t\t{\n\t\t}\n\n\t\tprotected virtual void OnRemove (T item, int index)\n\t\t{\n\t\t}\n\n\t\tprotected virtual void OnClear ()\n\t\t{\n\t\t}\n\n\t\tinternal virtual void Grow (int desired)\n\t\t{\n\t\t\tint new_size = size + desired;\n\t\t\tif (new_size <= items.Length)\n\t\t\t\treturn;\n\n\t\t\tconst int default_capacity = 4;\n\n\t\t\tnew_size = System.Math.Max (\n\t\t\t\tSystem.Math.Max (items.Length * 2, default_capacity),\n\t\t\t\tnew_size);\n\n#if !CF\n\t\t\tArray.Resize (ref items, new_size);\n#else\n\t\t\tvar array = new T [new_size];\n\t\t\tArray.Copy (items, array, size);\n\t\t\titems = array;\n#endif\n\t\t}\n\n\t\tint IList.Add (object value)\n\t\t{\n\t\t\ttry {\n\t\t\t\tAdd ((T) value);\n\t\t\t\treturn size - 1;\n\t\t\t} catch (InvalidCastException) {\n\t\t\t} catch (NullReferenceException) {\n\t\t\t}\n\n\t\t\tthrow new ArgumentException ();\n\t\t}\n\n\t\tvoid IList.Clear ()\n\t\t{\n\t\t\tClear ();\n\t\t}\n\n\t\tbool IList.Contains (object value)\n\t\t{\n\t\t\treturn ((IList) this).IndexOf (value) > -1;\n\t\t}\n\n\t\tint IList.IndexOf (object value)\n\t\t{\n\t\t\ttry {\n\t\t\t\treturn IndexOf ((T) value);\n\t\t\t} catch (InvalidCastException) {\n\t\t\t} catch (NullReferenceException) {\n\t\t\t}\n\n\t\t\treturn -1;\n\t\t}\n\n\t\tvoid IList.Insert (int index, object value)\n\t\t{\n\t\t\tCheckIndex (index);\n\n\t\t\ttry {\n\t\t\t\tInsert (index, (T) value);\n\t\t\t\treturn;\n\t\t\t} catch (InvalidCastException) {\n\t\t\t} catch (NullReferenceException) {\n\t\t\t}\n\n\t\t\tthrow new ArgumentException ();\n\t\t}\n\n\t\tvoid IList.Remove (object value)\n\t\t{\n\t\t\ttry {\n\t\t\t\tRemove ((T) value);\n\t\t\t} catch (InvalidCastException) {\n\t\t\t} catch (NullReferenceException) {\n\t\t\t}\n\t\t}\n\n\t\tvoid IList.RemoveAt (int index)\n\t\t{\n\t\t\tRemoveAt (index);\n\t\t}\n\n\t\tvoid ICollection.CopyTo (Array array, int index)\n\t\t{\n\t\t\tArray.Copy (items, 0, array, index, size);\n\t\t}\n\n\t\tpublic Enumerator GetEnumerator ()\n\t\t{\n\t\t\treturn new Enumerator (this);\n\t\t}\n\n\t\tIEnumerator IEnumerable.GetEnumerator ()\n\t\t{\n\t\t\treturn new Enumerator (this);\n\t\t}\n\n\t\tIEnumerator<T> IEnumerable<T>.GetEnumerator ()\n\t\t{\n\t\t\treturn new Enumerator (this);\n\t\t}\n\n\t\tpublic struct Enumerator : IEnumerator<T>, IDisposable {\n\n\t\t\tCollection<T> collection;\n\t\t\tT current;\n\n\t\t\tint next;\n\t\t\treadonly int version;\n\n\t\t\tpublic T Current {\n\t\t\t\tget { return current; }\n\t\t\t}\n\n\t\t\tobject IEnumerator.Current {\n\t\t\t\tget {\n\t\t\t\t\tCheckState ();\n\n\t\t\t\t\tif (next <= 0)\n\t\t\t\t\t\tthrow new InvalidOperationException ();\n\n\t\t\t\t\treturn current;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinternal Enumerator (Collection<T> collection)\n\t\t\t\t: this ()\n\t\t\t{\n\t\t\t\tthis.collection = collection;\n\t\t\t\tthis.version = collection.version;\n\t\t\t}\n\n\t\t\tpublic bool MoveNext ()\n\t\t\t{\n\t\t\t\tCheckState ();\n\n\t\t\t\tif (next < 0)\n\t\t\t\t\treturn false;\n\n\t\t\t\tif (next < collection.size) {\n\t\t\t\t\tcurrent = collection.items [next++];\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\tnext = -1;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tpublic void Reset ()\n\t\t\t{\n\t\t\t\tCheckState ();\n\n\t\t\t\tnext = 0;\n\t\t\t}\n\n\t\t\tvoid CheckState ()\n\t\t\t{\n\t\t\t\tif (collection == null)\n\t\t\t\t\tthrow new ObjectDisposedException (GetType ().FullName);\n\n\t\t\t\tif (version != collection.version)\n\t\t\t\t\tthrow new InvalidOperationException ();\n\t\t\t}\n\n\t\t\tpublic void Dispose ()\n\t\t\t{\n\t\t\t\tcollection = null;\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Collections.Generic/ReadOnlyCollection.cs",
    "content": "//\n// ReadOnlyCollection.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections;\nusing System .Collections.Generic;\n\nnamespace Mono.Collections.Generic {\n\n\tpublic sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IList {\n\n\t\tstatic ReadOnlyCollection<T> empty;\n\n\t\tpublic static ReadOnlyCollection<T> Empty {\n\t\t\tget { return empty ?? (empty = new ReadOnlyCollection<T> ()); }\n\t\t}\n\n\t\tbool ICollection<T>.IsReadOnly {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tbool IList.IsFixedSize {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tbool IList.IsReadOnly {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tprivate ReadOnlyCollection ()\n\t\t{\n\t\t}\n\n\t\tpublic ReadOnlyCollection (T [] array)\n\t\t{\n\t\t\tif (array == null)\n\t\t\t\tthrow new ArgumentNullException ();\n\n\t\t\tInitialize (array, array.Length);\n\t\t}\n\n\t\tpublic ReadOnlyCollection (Collection<T> collection)\n\t\t{\n\t\t\tif (collection == null)\n\t\t\t\tthrow new ArgumentNullException ();\n\n\t\t\tInitialize (collection.items, collection.size);\n\t\t}\n\n\t\tvoid Initialize (T [] items, int size)\n\t\t{\n\t\t\tthis.items = new T [size];\n\t\t\tArray.Copy (items, 0, this.items, 0, size);\n\t\t\tthis.size = size;\n\t\t}\n\n\t\tinternal override void Grow (int desired)\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tprotected override void OnAdd (T item, int index)\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tprotected override void OnClear ()\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tprotected override void OnInsert (T item, int index)\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tprotected override void OnRemove (T item, int index)\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tprotected override void OnSet (T item, int index)\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Security.Cryptography/CryptoConvert.cs",
    "content": ""
  },
  {
    "path": "ILRuntime/Mono.Cecil.20/MonoCecil/Mono.Security.Cryptography/CryptoService.cs",
    "content": "//\n// CryptoService.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\nusing System.Reflection;\nusing System.Security.Cryptography;\n\n"
  },
  {
    "path": "ILRuntime/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// 有关程序集的一般信息由以下\n// 控制。更改这些特性值可修改\n// 与程序集关联的信息。\n[assembly: AssemblyTitle(\"ILRuntime\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"HP Inc.\")]\n[assembly: AssemblyProduct(\"ILRuntime\")]\n[assembly: AssemblyCopyright(\"Copyright © HP Inc. 2017\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// 将 ComVisible 设置为 false 会使此程序集中的类型\n//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型\n//请将此类型的 ComVisible 特性设置为 true。\n[assembly: ComVisible(false)]\n\n// 如果此项目向 COM 公开，则下列 GUID 用于类型库的 ID\n[assembly: Guid(\"eeb72dfc-0fa5-44de-b75a-586f69377aa7\")]\n\n// 程序集的版本信息由下列四个值组成: \n//\n//      主版本\n//      次版本\n//      生成号\n//      修订号\n//\n// 可以指定所有值，也可以使用以下所示的 \"*\" 预置版本号和修订号\n// 方法是按如下所示使用“*”: :\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "Libs/PublishLibrary.bat",
    "content": "set CurDir=%~dp0\nset LibName=%1\necho LibName=%LibName%\npdb2mdb %LibName%.dll\nxcopy %LibName%.dll %CurDir%..\\..\\SpiceUnity\\SpiceUnity\\LinkGameApp\\Assets\\Plugins\\ManagedLibs\\  /y\nxcopy %LibName%.dll.mdb %CurDir%..\\..\\SpiceUnity\\SpiceUnity\\LinkGameApp\\Assets\\Plugins\\ManagedLibs\\  /y\n"
  },
  {
    "path": "Libs/SGFAppDemo.exe.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "Libs/SGFAppILRScript.dll.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "Libs/SGFCore.dll.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "README.md",
    "content": "# SGF \nthe Smart Game Foundation\n\nQQ交流群：809637084\n\n它主要由3个工程组成：\n\n* SGFCore：与Unity无关的功能模块。\n* SGFUnity：与Unity相关的功能模块。\n* SGFDebuger：一个日志输出工具。\n\n其余工程说明：\n* ILRuntime：一个ILRuntime的第3方库。由于官方不推荐以DLL的形式用于项目中，所以该工程将不再维护。\n* SGFServerLite：一个服务器的示例。\n* SGFAppCommon/SGFAppILRScript/SGFAppDemo：一个客户端的综合演示示例，它包括与服务器通讯，热更新等等逻辑。\n\n其余目录：\n* Libs：以上工程编译好的Dll，如果不需要修改代码的话，你可以直接使用这些Dll。\n* Apps：以上示例编译好的Exe，你可以尝试运行一下，可能在不同的机器上运行会有问题，你最好直接打开对应的示例工程来调试运行。\n\n其它：\n* SGF库发源于我的一个GAD课程项目：《贪吃蛇大作战》\n* 其相关的视频链接为：\n    * 第一季： http://gameinstitute.qq.com/lore/index/10007\n    * 第二季： http://gameinstitute.qq.com/lore/index/10017\n\n## 1.SGFCore\n### Codec\n* 收集或者实现一些常用编解码库，或者对一些编解码库进行易用性封装。\n    * MiniJson，一个常用的轻量Json编解码库（Copyright (c) 2013 Calvin Rien）\n    * PBSerializer，对Protobuf的封装，使之在一般场合下非常易用。\n    * SGFEncoding，一些自己实现的编解码相关算法，比如:\n        * XOR\n        * CheckSum\n        * BytesToHex,HexToBytes\n        * 等等\n    \n### Common\n* 将来可能放一些数据结构相关的类，或者易用性封装。\n    * DictionarySafe，是对Dictionary做一个易用性封装。\n    * MapList，是将List与Dictionary结合起来做一个易用性封装。\n \n### Console\n* 控制台相关的功能。\n    * ConsoleInput：使控制台应用程序可以接受命令行输入。\n\n### Event\n* 事件系统。\n* 它的思路与系统自带的Action类似，但是在性能与逻辑上比原生的Action更加可控，并且能够以日志的方式进行追踪和调试。\n* 这在实际应用中非常有用。\n\n### G3Lite\n* 轻量级几何库。\n* 考虑到很多时候需要脱离Unity进行开发，所以需要一套脱离Unity的几何类库。这里部分移植了geometry3Sharp里的一些基础类：\n    - Vector2/Vector3/Vector4\n    - Matrix3\n    - Quaternion\n    - MathUtil\n    - IndexTypes\n\n### IPCWork\n* 进程通讯模块。\n* 它基于UdpSocket实现，以RPC的方式进行调用。\n    * 由于是基于Udp的简单实现，所以对单次通讯的数据大小有要求，不能超过当前系统的MTU。\n    * 如果需要在进程间进行大数据通讯，可以使用Network模块，建立可靠UDP连接，或者TCP连接。当然也可以采用共享内存和管道方案，期待后续有人来完善。\n\n### Marshals\n* 提供非托管相关的功能模块\n* 利用它可以避开C#的内存管理，自己控制内存的分配和释放，避免GC\n    - MarshalArray：参照托管Array来封装，使用方法上基本与Array相同\n    - MarshalList：参照托管List来封装，使用方法上基本与List相同\n\n### MathLite\n* 计划实现一套轻量级的数学库。\n* 目前只有随机数生成算法。\n\n### Module\n* 模块管理器。\n* 当项目的规模足够大时，就需要将整个系统划分为若干个模块。这些模块需要一套系统进行管理。\n* 它具备很好的扩展性，结合ILRuntime可以实现iOS版本中模块级别的热更新。\n* 它实现了模块间的消息通讯，并以此来解耦。\n\n### Network\n* 网络模块。\n* 它实现了与网络通讯相关的绝大部分功能。\n    * Core，这里实现了一些数据、协议头、消息格式等的定义。还有一个轻量的RPC实现方案。\n    * FSPLite，实现了一个轻量级的【帧同步】通讯方案的前台与后台模块。使用它，你可以很快搭建出一个帧同步运行环境，包括帧同步服务器和客户端。\n    * General，实现了一个【通用】的网络通讯方案的前台与后台模块。使用它，你可以很容易实现游戏的状态同步，包括服务器和客户端。\n\n### Server\n* 服务器模块管理器。\n* 在服务器开发中，当项目规范足够大时，也需要像客户端一样将整个系统划分为若干模块。这些模块需要进行管理。\n* 目前该功能还比较简单，需要进一步完善。\n\n### Time\n* 与时间相关的类。\n    - SGFTime，类似Unity里的Time类。需要在App启动时，进行初始化。\n\n### Utils\n* 一些工具类。\n    - FileUtils，文件相关功能。\n    - PathUtils，路径相关功能。\n    - TimeUtils，时间相关功能。\n    - 等等\n\n\n\n\n## 2.SGFUnity\n### DebugerGUI\n* 一个可扩展的运行时调试和测试工具GUI。\n* 可以很方便地在其上扩展自己的工具页签。\n\n### ILR\n* 热更新相关的功能模块。\n    - DebugerILR，为热更模块提供日志输出功能。\n    - ModuleILR，支持模块级别的热更。\n    - UIILR，支持UI系统调用热更模块。\n* 本热更方案可以实现在开发时，采用原生C#模式进行开发和单步调试。在发布时，无逢切换为热更模式。整个过程对于开发者是无感知的。\n\n### ILRuntime\n* 用于热更新的运行时库。因为需要支持IL2CPP的缘故，将直接使用其源代码，而非DLL。\n* 于是，如果需要使用ILRuntime，你需要将SGFUnity这个库的源代码直接Copy到Unity工程中。\n\n### Mono.Cecil.20与Mono.Cecil.Pdb\n* 如果将SGFUnity以源代码的形式Copy到 Unity工程中，那么它们有可能与Unity新版本自带的库重复，如果这样的话，可以将其删除。\n\n### UI\n* UI系统。\n* 这是一个基于UGUI的UI管理系统，封装了游戏开发中常用的几种UI元素。并且将这些元素分为2类，UIPage和UIPanel：页面。游戏的基础UI就是Page，它是全屏的。所有的游戏Panel都是显示在一个页面上的。\n* 而UIPanel又可以分为以下几类：\n    - UIWindow，游戏中的窗口。\n    - UILoading，游戏中的Loading。\n    - UIWidget，游戏中依附于窗口的一些小UI，或者会自动消失的小UI。\n* 顺便封装了一些常用的通用UI面板和控件。\n    - UIMsgBox，继承自UIWindow。\n    - UIMsgTips，继承自UIWidget。\n    - UISimpleLoading，继承自UILoading。\n    - CtlList/CtlListItem\n    - CtlProgressBar\n    - 等等\n    \n### Utils\n* 一些工具类。\n\n## 3.SGFDebuger\n* 一个日志工具类。\n* 支持在非Unity环境和Unity环境下都能输出格式化日志。\n* 并且支持日志保存为文件。 \n"
  },
  {
    "path": "SGF.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 14\nVisualStudioVersion = 14.0.25420.1\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"SGFCore\", \"SGFCore\\SGFCore.csproj\", \"{EEB72DFC-0FA5-44DE-B75A-586F69377AA6}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"SGFAppDemo\", \"SGFAppDemo\\SGFAppDemo.csproj\", \"{3FACC3DD-FFA2-4FE7-B9B6-063260594AF1}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"SGFUnity\", \"SGFUnity\\SGFUnity.csproj\", \"{64ECFF78-EE1F-432B-A581-A70E8EB6DE83}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"SGFDebuger\", \"SGFDebuger\\SGFDebuger.csproj\", \"{DC1D8B0A-9C8C-4911-AAFE-D7D958EC4044}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"SGFAppILRScript\", \"SGFAppILRScript\\SGFAppILRScript.csproj\", \"{4704169C-4BAD-4CFB-842A-2F4E3FC60375}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"SGFServerDemo\", \"SGFServerLite\\SGFServerDemo.csproj\", \"{D1ACC88B-2B6E-43E5-8314-DD64C2F25AA7}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"SGFAppCommon\", \"SGFAppCommon\\SGFAppCommon.csproj\", \"{A1BF1B00-7CDF-4A48-8D33-98645E5DF606}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug|Any CPU = Debug|Any CPU\n\t\tRelease|Any CPU = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{EEB72DFC-0FA5-44DE-B75A-586F69377AA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{EEB72DFC-0FA5-44DE-B75A-586F69377AA6}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{EEB72DFC-0FA5-44DE-B75A-586F69377AA6}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{EEB72DFC-0FA5-44DE-B75A-586F69377AA6}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{3FACC3DD-FFA2-4FE7-B9B6-063260594AF1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{3FACC3DD-FFA2-4FE7-B9B6-063260594AF1}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{3FACC3DD-FFA2-4FE7-B9B6-063260594AF1}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{3FACC3DD-FFA2-4FE7-B9B6-063260594AF1}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{64ECFF78-EE1F-432B-A581-A70E8EB6DE83}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{64ECFF78-EE1F-432B-A581-A70E8EB6DE83}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{64ECFF78-EE1F-432B-A581-A70E8EB6DE83}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{64ECFF78-EE1F-432B-A581-A70E8EB6DE83}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{DC1D8B0A-9C8C-4911-AAFE-D7D958EC4044}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{DC1D8B0A-9C8C-4911-AAFE-D7D958EC4044}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{DC1D8B0A-9C8C-4911-AAFE-D7D958EC4044}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{DC1D8B0A-9C8C-4911-AAFE-D7D958EC4044}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{4704169C-4BAD-4CFB-842A-2F4E3FC60375}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{4704169C-4BAD-4CFB-842A-2F4E3FC60375}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{4704169C-4BAD-4CFB-842A-2F4E3FC60375}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{4704169C-4BAD-4CFB-842A-2F4E3FC60375}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{D1ACC88B-2B6E-43E5-8314-DD64C2F25AA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{D1ACC88B-2B6E-43E5-8314-DD64C2F25AA7}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{D1ACC88B-2B6E-43E5-8314-DD64C2F25AA7}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{D1ACC88B-2B6E-43E5-8314-DD64C2F25AA7}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{A1BF1B00-7CDF-4A48-8D33-98645E5DF606}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{A1BF1B00-7CDF-4A48-8D33-98645E5DF606}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{A1BF1B00-7CDF-4A48-8D33-98645E5DF606}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{A1BF1B00-7CDF-4A48-8D33-98645E5DF606}.Release|Any CPU.Build.0 = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(SolutionProperties) = preSolution\n\t\tHideSolutionNode = FALSE\n\tEndGlobalSection\n\tGlobalSection(ExtensibilityGlobals) = postSolution\n\t\tSolutionGuid = {03B7BAC5-A958-46AB-9392-318A99832A01}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "SGFAppCommon/Data/PlayerData.cs",
    "content": "﻿using ProtoBuf;\n\nnamespace SGFAppDemo.Common.Data\n{\n\t[ProtoContract]\n    public class PlayerData\n    {\n\t\t[ProtoMember(1)]\n        public uint id;\n\t\t[ProtoMember(2)]\n        public string name;\n\t\t[ProtoMember(3)]\n        public uint userId;\n\t\t[ProtoMember(4)]\n        public uint sid;\n\t\t[ProtoMember(5)]\n        public bool isReady;\n        \n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn string.Format (\"<id:{0}, name:{1}, userId:{2}, sid:{3}, isReady:{4}>\", id, name, userId, sid, isReady);\n\t\t}\n    }\n}\n"
  },
  {
    "path": "SGFAppCommon/Data/RoomData.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing ProtoBuf;\nusing SGF.Extension;\n\n\nnamespace SGFAppDemo.Common.Data\n{\n\t[ProtoContract]\n    public class RoomData\n    {\n\t\t[ProtoMember(1)]\n        public uint id;\n        [ProtoMember(2)]\n        public string name;\n        [ProtoMember(3)]\n        public uint owner;\n        [ProtoMember(4)]\n        public List<PlayerData> players = new List<PlayerData>();\n\n        public override string ToString()\n        {\n            return string.Format(\"<id:{0}, name:{1}, owner:{2}, players:{3}>\",id,name,owner,players.ToListString());\n        }\n\n\n    }\n\n    [ProtoContract]\n    public class RoomListData\n    {\n        [ProtoMember(1)]\n        public List<RoomData> rooms = new List<RoomData>();\n    }\n\n\n}\n"
  },
  {
    "path": "SGFAppCommon/Data/UserData.cs",
    "content": "﻿using ProtoBuf;\nusing SGF.Utils;\n\nnamespace SGFAppDemo.Common.Data\n{\n    [ProtoContract]\n    public class UserData\n    {\n        public static int OnlineTimeout = 40;\n\n        [ProtoMember(1)] public uint id;\n        [ProtoMember(2)] public string name;\n        [ProtoMember(3)] public string pwd;\n\n\n\n        public UserServerData svrdata = new UserServerData();\n\n\n        public override string ToString()\n        {\n            return string.Format(\"<id:{0}, name:{1}, online:{2}>\", id, name, svrdata.online);\n\n        }\n    }\n\n    public class UserServerData\n    {\n        public uint lastHeartBeatTime = 0;\n        private bool m_online = false;\n        public bool online\n        {\n            get\n            {\n                if (m_online)\n                {\n                    uint dt = (uint)TimeUtils.GetTotalSecondsSince1970() - lastHeartBeatTime;\n                    if (dt > UserData.OnlineTimeout)\n                    {\n                        m_online = false;\n                    }\n                }\n                return m_online;\n            }\n            set { m_online = value; }\n        }\n\n    }\n\n}"
  },
  {
    "path": "SGFAppCommon/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// 有关程序集的一般信息由以下\n// 控制。更改这些特性值可修改\n// 与程序集关联的信息。\n[assembly: AssemblyTitle(\"SGFAppCommon\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"Microsoft\")]\n[assembly: AssemblyProduct(\"SGFAppCommon\")]\n[assembly: AssemblyCopyright(\"Copyright © Microsoft 2017\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n//将 ComVisible 设置为 false 将使此程序集中的类型\n//对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型，\n//请将此类型的 ComVisible 特性设置为 true。\n[assembly: ComVisible(false)]\n\n// 如果此项目向 COM 公开，则下列 GUID 用于类型库的 ID\n[assembly: Guid(\"dc1d8b0a-9c8c-4911-aafe-d7d958ec4045\")]\n\n// 程序集的版本信息由下列四个值组成: \n//\n//      主版本\n//      次版本\n//      生成号\n//      修订号\n//\n//可以指定所有这些值，也可以使用“生成号”和“修订号”的默认值，\n// 方法是按如下所示使用“*”: :\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "SGFAppCommon/Proto/HeartBeatProto.cs",
    "content": "﻿using ProtoBuf;\nusing SGF.Network.General.Proto;\nusing SGFAppDemo.Common.Data;\n\nnamespace SGFAppDemo.Common.Proto\n{\n    /// <summary>\n    /// 可以利用心跳协议完成网络测速\n    /// </summary>\n    [ProtoContract]\n    public class HeartBeatReq\n    {\n        [ProtoMember(1)] public ushort ping;\n        [ProtoMember(2)] public uint timestamp;\n    }\n\n    [ProtoContract]\n    public class HeartBeatRsp\n    {\n        [ProtoMember(1)]public ReturnCode ret;\n        [ProtoMember(2)]public uint timestamp;\n    }\n}"
  },
  {
    "path": "SGFAppCommon/Proto/LoginProto.cs",
    "content": "﻿using ProtoBuf;\nusing SGF.Network.General.Proto;\nusing SGFAppDemo.Common.Data;\n\nnamespace SGFAppDemo.Common.Proto\n{\n    [ProtoContract]\n    public class LoginReq\n    {\n        [ProtoMember(1)]\n        public uint id;\n        [ProtoMember(2)]\n        public string name;\n    }\n\n    [ProtoContract]\n    public class LoginRsp\n    {\n        [ProtoMember(1)]\n        public ReturnCode ret;\n        [ProtoMember(2)]\n        public UserData userdata;\n    }\n}"
  },
  {
    "path": "SGFAppCommon/Proto/ProtoCmd.cs",
    "content": "﻿using ProtoBuf;\n\nnamespace SGFAppDemo.Common.Proto\n{\n    public class ProtoCmd\n    {\n        public static uint LoginReq = 1;\n        public static uint LoginRsp = 2;\n        public static uint HeartBeatReq = 3;\n        public static uint HeartBeatRsp = 4;\n    }\n}"
  },
  {
    "path": "SGFAppCommon/SGFAppCommon.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{A1BF1B00-7CDF-4A48-8D33-98645E5DF606}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>SGFAppDemo.Common</RootNamespace>\n    <AssemblyName>SGFAppCommon</AssemblyName>\n    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <TargetFrameworkProfile />\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>..\\Libs\\</OutputPath>\n    <DefineConstants>TRACE;DEBUG;ENABLE_LOG;ENABLE_LOG_LOOP</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>..\\Libs\\</OutputPath>\n    <DefineConstants>TRACE;ENABLE_LOG;ENABLE_LOG_LOOP</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"protobuf-net, Version=2.0.0.668, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\Common\\protobuf-net.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"Proto\\HeartBeatProto.cs\" />\n    <Compile Include=\"Proto\\LoginProto.cs\" />\n    <Compile Include=\"Data\\PlayerData.cs\" />\n    <Compile Include=\"Proto\\ProtoCmd.cs\" />\n    <Compile Include=\"Data\\RoomData.cs\" />\n    <Compile Include=\"Data\\UserData.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\SGFCore\\SGFCore.csproj\">\n      <Project>{eeb72dfc-0fa5-44de-b75a-586f69377aa6}</Project>\n      <Name>SGFCore</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <PropertyGroup>\n    <PostBuildEvent>$(ProjectDir)..\\Libs\\PublishLibrary.bat $(TargetName)\n</PostBuildEvent>\n  </PropertyGroup>\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "SGFAppDemo/App.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "SGFAppDemo/AppMain.cs",
    "content": "﻿\n\nusing System;\nusing SGF;\nusing SGF.Module;\nusing SGF.Unity.ILR;\nusing SGF.Unity.ILR.ModuleILR;\nusing SGFAppDemo.Framework;\nusing SGFAppDemo.Services;\n\nnamespace SGFAppDemo\n{\n    public class AppMain:SGFGameObject\n    {\n        public override void Active()\n        {\n            InitServices();\n            UpdateVersion();\n        }\n\n\n\n        private void InitServices()\n        {\n            Debuger.Log();\n\n            ILRManager.Instance.Init(RunMode.Native, false);\n            ILRManager.Instance.AddSearchDirectory(AppDomain.CurrentDomain.BaseDirectory);\n            ILRManager.Instance.LoadAssembly(ModuleDef.ScriptAssemblyName);\n\n            ModuleManager.Instance.Init();\n            ModuleManager.Instance.RegisterModuleActivator(new NativeModuleActivator(ModuleDef.Namespace, ModuleDef.NativeAssemblyName));\n            ModuleManager.Instance.RegisterModuleActivator(new ILRModuleActivator(ModuleDef.Namespace, ModuleDef.ScriptAssemblyName));\n\n            OnlineManager.Instance.Init();\n        }\n\n        private void UpdateVersion()\n        {\n            ModuleManager.Instance.CreateModule(ModuleDef.VersionModule);\n            ModuleManager.Instance.ShowModule(ModuleDef.VersionModule);\n            GlobalEvent.onVersionUpdateComplete.AddListener(OnVersionUpdateComplete);\n        }\n\n        private void OnVersionUpdateComplete()\n        {\n            GlobalEvent.onVersionUpdateComplete.RemoveAllListeners();\n\n            //由脚本来初始业务逻辑，便于热更\n            bool ret = (bool)ILRManager.Instance.Invoke(\"SGFAppDemo.ScriptMain\", \"Init\");\n            if (!ret)\n            {\n                Debuger.LogError(\"初始化业务逻辑失败！\");\n                Console.WriteLine(\"初始化业务逻辑失败！\");\n            }\n        }\n        \n    }\n}"
  },
  {
    "path": "SGFAppDemo/Framework/SGFGameDefine.cs",
    "content": "﻿namespace SGFAppDemo.Framework\n{\n    public static class SGFGameDefine\n    {\n        public static int FPS = 30;\n        public static int FRAME_TICK_INTERVAL{get { return (int)(FRAME_INTERVAL * 10000); } }\n        public static float FRAME_INTERVAL { get { return 1000 / FPS; } }\n\n    }\n}"
  },
  {
    "path": "SGFAppDemo/Framework/SGFGameMainLoop.cs",
    "content": "﻿using System;\nusing SGF;\nusing SGF.Utils;\n\nnamespace SGFAppDemo.Framework\n{\n    public class SGFGameMainLoop\n    {\n        private static bool m_run = false;\n\n        public static void Run()\n        {\n            float deltaTimeMS = 0;\n            long m_LogicLastTicks = DateTime.Now.Ticks;\n            long nowticks = DateTime.Now.Ticks;\n            long interval = 0;\n            long fixedFrameInterval = 0;\n\n            ConsoleInput.onInputKey.AddListener(OnInputKey);\n            \n            m_run = true;\n\n            while (m_run)\n            {\n                ConsoleInput.Tick();\n                \n\n                fixedFrameInterval = SGFGameDefine.FRAME_TICK_INTERVAL;\n                nowticks = DateTime.Now.Ticks;\n                interval = nowticks - m_LogicLastTicks;\n\n                if (interval >= fixedFrameInterval)\n                {\n                    deltaTimeMS = interval / 10000.0f;\n                    SGFGameObject[] list;\n                    int cnt = 0;\n\n                    while (interval >= fixedFrameInterval)\n                    {\n                        interval -= fixedFrameInterval;\n                        list = SGFGameObject.GetActivedGameObjects();\n                        cnt = list.Length;\n                        for (int i = 0; i < cnt; i++)\n                        {\n                            list[i].FixedUpdate();\n                        }\n\n                        GlobalEvent.onFixedUpdate.Invoke();\n                    }\n\n                    list = SGFGameObject.GetActivedGameObjects();\n                    cnt = list.Length;\n                    for (int i = 0; i < cnt; i++)\n                    {\n                        list[i].Update(deltaTimeMS);\n                    }\n\n                    GlobalEvent.onUpdate.Invoke(deltaTimeMS);\n\n                    m_LogicLastTicks = nowticks - interval;\n                }\n\n                \n            }\n        }\n\n        private static void OnInputKey(ConsoleKey key)\n        {\n            if (key == ConsoleKey.Escape)\n            {\n                m_run = false;\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFAppDemo/Framework/SGFGameObject.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\n\nnamespace SGFAppDemo.Framework\n{\n    public class SGFGameObject\n    {\n        private static List<SGFGameObject> m_listInstancedObject = new List<SGFGameObject>();\n        private static List<SGFGameObject> m_listActivedObject = new List<SGFGameObject>();\n        \n        public static SGFGameObject Instance(Type type)\n        {\n            \n            if (type.IsSubclassOf(typeof(SGFGameObject)))\n            {\n                SGFGameObject obj = Activator.CreateInstance(type) as SGFGameObject;\n                obj.InstanceInternal();\n                return obj;\n            }\n            return null;\n        }\n\n        public static void Destroy(SGFGameObject obj)\n        {\n            obj.DestroyInternal();\n        }\n\n        public static SGFGameObject[] GetActivedGameObjects()\n        {\n            return m_listActivedObject.ToArray();\n        }\n\n        public static SGFGameObject[] GetInstancedGameObjects()\n        {\n            return m_listInstancedObject.ToArray();\n        }\n\n        public static void DestroyAll()\n        {\n            SGFGameObject[] list = m_listInstancedObject.ToArray();\n            int cnt = list.Length;\n            for (int i = 0; i < cnt; i++)\n            {\n                list[i].DestroyInternal();\n            }\n            m_listInstancedObject.Clear();\n        }\n\n        \n\n        private bool m_instanced = false;\n        private bool m_actived = false;\n\n        \n        protected SGFGameObject()\n        {\n            InstanceInternal();\n        }\n\n        private void InstanceInternal()\n        {\n            if (!m_instanced)\n            {\n                m_instanced = true;\n                m_listInstancedObject.Add(this);\n                Instance();\n                SetActive(true);\n            }\n        }\n\n        private void DestroyInternal()\n        {\n            if (m_instanced)\n            {\n                if (m_actived)\n                {\n                    m_actived = false;\n                    m_listActivedObject.Remove(this);\n                    Deactive();\n                }\n\n                m_instanced = false;\n                m_listInstancedObject.Remove(this);\n                Destroy();\n            }\n        }\n\n        public virtual void Instance()\n        {\n            \n        }\n\n        public virtual void Destroy()\n        {\n            DestroyInternal();\n        }\n\n        public void SetActive(bool value)\n        {\n            if (m_actived != value)\n            {\n                m_actived = value;\n                if (m_actived)\n                {\n                    if (!m_listActivedObject.Contains(this))\n                    {\n                        m_listActivedObject.Add(this);\n                    }\n                    Active();\n                }\n                else\n                {\n                    m_listActivedObject.Remove(this);\n                    Deactive();\n                }\n            }\n        }\n\n        public virtual void Active()\n        {\n\n        }\n\n        public virtual void Deactive()\n        {\n\n        }\n\n        public virtual void Update(float deltaTime)\n        {\n            \n        }\n\n        public virtual void FixedUpdate()\n        {\n\n        }\n\n\n    }\n}"
  },
  {
    "path": "SGFAppDemo/GlobalEvent.cs",
    "content": "﻿using SGF.SEvent;\n\nnamespace SGFAppDemo\n{\n    /// <summary>\n    /// 全局事件\n    /// 有些事件不确定应该是由谁发出\n    /// 就可以通过全局事件来收和发\n    /// </summary>\n    public static class GlobalEvent\n    {\n        public static Signal onVersionUpdateComplete = new Signal();\n        public static Signal onFixedUpdate = new Signal();\n        public static Signal<float> onUpdate = new Signal<float>();\n    }\n}"
  },
  {
    "path": "SGFAppDemo/ModuleDef.cs",
    "content": "﻿namespace SGFAppDemo\n{\n    internal static class ModuleDef\n    {\n        public const string Namespace = \"SGFAppDemo.Modules\";\n        public const string NativeAssemblyName = \"SGFAppDemo\";\n        public const string ScriptAssemblyName = \"SGFAppILRScript\";\n\n        public const string VersionModule = \"VersionModule\";\n    }\n}"
  },
  {
    "path": "SGFAppDemo/Modules/Version/VersionModule.cs",
    "content": "﻿using System;\nusing SGF;\nusing SGF.Module;\nusing SGF.Time;\n\nnamespace SGFAppDemo.Modules\n{\n    public class VersionModule : GeneralModule\n    {\n        private float m_progress = 0;\n        protected override void Show(object arg)\n        {\n            base.Show(arg);\n\n            GlobalEvent.onUpdate.AddListener(OnUpdate);\n        }\n\n        private void OnUpdate(float deltaTime)\n        {\n            m_progress += 0.1f;\n            if (m_progress > 1)\n            {\n                m_progress = 1;\n            }\n\n            Console.Write(\"模拟版本更新:\" + (int)(m_progress * 100) + \"%\\r\");\n\n            if (m_progress >= 1)\n            {\n                Console.WriteLine();\n                GlobalEvent.onUpdate.RemoveListener(OnUpdate);\n                GlobalEvent.onVersionUpdateComplete.Invoke();\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFAppDemo/Program.cs",
    "content": "﻿\nusing System;\nusing SGF;\nusing SGF.Time;\nusing SGFAppDemo.Framework;\n\nnamespace SGFAppDemo\n{\n    class Program\n    {\n\n        static void Main(string[] args)\n        {\n            InitDebuger();\n\n\n\n            SGFTime.DateTimeAppStart = DateTime.Now;\n            SGFGameObject.Instance(typeof(AppMain));\n            SGFGameMainLoop.Run();\n            SGFGameObject.DestroyAll();\n\n            Console.WriteLine(\"GameOver\");\n            Console.ReadKey();\n        }\n\n        private static void InitDebuger()\n        {\n            Debuger.Init();\n            Debuger.EnableLog = true;\n            Debuger.EnableSave = true;\n            Debuger.Log();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFAppDemo/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// 有关程序集的一般信息由以下\n// 控制。更改这些特性值可修改\n// 与程序集关联的信息。\n[assembly: AssemblyTitle(\"SGFAppDemo\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"HP Inc.\")]\n[assembly: AssemblyProduct(\"SGFAppDemo\")]\n[assembly: AssemblyCopyright(\"Copyright © HP Inc. 2017\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// 将 ComVisible 设置为 false 会使此程序集中的类型\n//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型\n//请将此类型的 ComVisible 特性设置为 true。\n[assembly: ComVisible(false)]\n\n// 如果此项目向 COM 公开，则下列 GUID 用于类型库的 ID\n[assembly: Guid(\"3facc3dd-ffa2-4fe7-b9b6-063260594af1\")]\n\n// 程序集的版本信息由下列四个值组成: \n//\n//      主版本\n//      次版本\n//      生成号\n//      修订号\n//\n// 可以指定所有值，也可以使用以下所示的 \"*\" 预置版本号和修订号\n// 方法是按如下所示使用“*”: :\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "SGFAppDemo/SGFAppDemo.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{3FACC3DD-FFA2-4FE7-B9B6-063260594AF1}</ProjectGuid>\n    <OutputType>Exe</OutputType>\n    <RootNamespace>SGFAppDemo</RootNamespace>\n    <AssemblyName>SGFAppDemo</AssemblyName>\n    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>\n    <TargetFrameworkProfile />\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>..\\Apps\\</OutputPath>\n    <DefineConstants>TRACE;DEBUG;ENABLE_LOG</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>..\\Apps\\</OutputPath>\n    <DefineConstants>TRACE;ENABLE_LOG</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"ILRuntime, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\ILRuntime.dll</HintPath>\n    </Reference>\n    <Reference Include=\"SGFDebuger, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\SGFDebuger.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"AppMain.cs\" />\n    <Compile Include=\"GlobalEvent.cs\" />\n    <Compile Include=\"ModuleDef.cs\" />\n    <Compile Include=\"Modules\\Version\\VersionModule.cs\" />\n    <Compile Include=\"Program.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Framework\\SGFGameDefine.cs\" />\n    <Compile Include=\"Framework\\SGFGameMainLoop.cs\" />\n    <Compile Include=\"Framework\\SGFGameObject.cs\" />\n    <Compile Include=\"Services\\Online\\HeartBeatHandler.cs\" />\n    <Compile Include=\"Services\\Online\\OnlineManager.cs\" />\n    <Compile Include=\"Services\\Online\\ServerProfiler.cs\" />\n    <Compile Include=\"Services\\Online\\ServerTestBot.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"App.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\SGFAppCommon\\SGFAppCommon.csproj\">\n      <Project>{a1bf1b00-7cdf-4a48-8d33-98645e5df606}</Project>\n      <Name>SGFAppCommon</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\SGFCore\\SGFCore.csproj\">\n      <Project>{eeb72dfc-0fa5-44de-b75a-586f69377aa6}</Project>\n      <Name>SGFCore</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\SGFUnity\\SGFUnity.csproj\">\n      <Project>{64ecff78-ee1f-432b-a581-a70e8eb6de83}</Project>\n      <Name>SGFUnity</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "SGFAppDemo/SGFGameDefine.cs",
    "content": "﻿namespace SGFAppDemo\n{\n    public static class SGFGameDefine\n    {\n        public static int FPS = 30;\n        public static int FRAME_TICK_INTERVAL{get { return (int)(FRAME_INTERVAL * 10000); } }\n        public static float FRAME_INTERVAL { get { return 1000 / FPS; } }\n\n    }\n}"
  },
  {
    "path": "SGFAppDemo/SGFGameMainLoop.cs",
    "content": "﻿using System;\nusing SGF;\nusing SGF.Time;\n\nnamespace SGFAppDemo\n{\n    public class SGFGameMainLoop\n    {\n        public static void Run()\n        {\n            float deltaTimeMS = 0;\n            long m_LogicLastTicks = DateTime.Now.Ticks;\n            long nowticks = DateTime.Now.Ticks;\n            long interval = 0;\n            long fixedFrameInterval = 0;\n\n            while (true)\n            {\n\n                if (Console.KeyAvailable)\n                {\n                    ConsoleKeyInfo info = Console.ReadKey();\n                    if (info.Key == ConsoleKey.Escape)\n                    {\n                        break;\n                    }\n                }\n\n\n                fixedFrameInterval = SGFGameDefine.FRAME_TICK_INTERVAL;\n                nowticks = DateTime.Now.Ticks;\n                interval = nowticks - m_LogicLastTicks;\n\n                if (interval >= fixedFrameInterval)\n                {\n                    deltaTimeMS = interval / 10000.0f;\n                    SGFGameObject[] list;\n                    int cnt = 0;\n\n                    while (interval >= fixedFrameInterval)\n                    {\n                        interval -= fixedFrameInterval;\n                        list = SGFGameObject.GetActivedGameObjects();\n                        cnt = list.Length;\n                        for (int i = 0; i < cnt; i++)\n                        {\n                            list[i].FixedUpdate();\n                        }\n\n                        GlobalEvent.onFixedUpdate.Invoke();\n                    }\n\n                    list = SGFGameObject.GetActivedGameObjects();\n                    cnt = list.Length;\n                    for (int i = 0; i < cnt; i++)\n                    {\n                        list[i].Update(deltaTimeMS);\n                    }\n\n                    GlobalEvent.onUpdate.Invoke(deltaTimeMS);\n\n                    m_LogicLastTicks = nowticks - interval;\n                }\n\n                \n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFAppDemo/SGFGameObject.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\n\nnamespace SGFAppDemo\n{\n    public class SGFGameObject\n    {\n        private static List<SGFGameObject> m_listInstancedObject = new List<SGFGameObject>();\n        private static List<SGFGameObject> m_listActivedObject = new List<SGFGameObject>();\n        \n        public static SGFGameObject Instance(Type type)\n        {\n            \n            if (type.IsSubclassOf(typeof(SGFGameObject)))\n            {\n                SGFGameObject obj = Activator.CreateInstance(type) as SGFGameObject;\n                obj.InstanceInternal();\n                return obj;\n            }\n            return null;\n        }\n\n        public static void Destroy(SGFGameObject obj)\n        {\n            obj.DestroyInternal();\n        }\n\n        public static SGFGameObject[] GetActivedGameObjects()\n        {\n            return m_listActivedObject.ToArray();\n        }\n\n        public static SGFGameObject[] GetInstancedGameObjects()\n        {\n            return m_listInstancedObject.ToArray();\n        }\n\n        public static void DestroyAll()\n        {\n            SGFGameObject[] list = m_listInstancedObject.ToArray();\n            int cnt = list.Length;\n            for (int i = 0; i < cnt; i++)\n            {\n                list[i].DestroyInternal();\n            }\n            m_listInstancedObject.Clear();\n        }\n\n        \n\n        private bool m_instanced = false;\n        private bool m_actived = false;\n\n        \n        protected SGFGameObject()\n        {\n            InstanceInternal();\n        }\n\n        private void InstanceInternal()\n        {\n            if (!m_instanced)\n            {\n                m_instanced = true;\n                m_listInstancedObject.Add(this);\n                Instance();\n                SetActive(true);\n            }\n        }\n\n        private void DestroyInternal()\n        {\n            if (m_instanced)\n            {\n                if (m_actived)\n                {\n                    m_actived = false;\n                    m_listActivedObject.Remove(this);\n                    Deactive();\n                }\n\n                m_instanced = false;\n                m_listInstancedObject.Remove(this);\n                Destroy();\n            }\n        }\n\n        public virtual void Instance()\n        {\n            \n        }\n\n        public virtual void Destroy()\n        {\n            DestroyInternal();\n        }\n\n        public void SetActive(bool value)\n        {\n            if (m_actived != value)\n            {\n                m_actived = value;\n                if (m_actived)\n                {\n                    if (!m_listActivedObject.Contains(this))\n                    {\n                        m_listActivedObject.Add(this);\n                    }\n                    Active();\n                }\n                else\n                {\n                    m_listActivedObject.Remove(this);\n                    Deactive();\n                }\n            }\n        }\n\n        public virtual void Active()\n        {\n\n        }\n\n        public virtual void Deactive()\n        {\n\n        }\n\n        public virtual void Update(float deltaTime)\n        {\n            \n        }\n\n        public virtual void FixedUpdate()\n        {\n\n        }\n\n\n    }\n}"
  },
  {
    "path": "SGFAppDemo/Services/Online/HeartBeatHandler.cs",
    "content": "﻿using SGF;\nusing SGF.MathLite;\nusing SGF.Network.Core;\nusing SGF.Network.General.Client;\nusing SGF.SEvent;\nusing SGF.Time;\nusing SGF.Utils;\nusing SGFAppDemo.Common.Proto;\n\nnamespace SGFAppDemo.Services.Online\n{\n    public class HeartBeatHandler\n    {\n        private NetManager m_net;\n        public Signal onTimeout = new Signal();\n        private float m_lastHeartBeatTime = 0;\n        private uint m_ping = 0;\n\n        public void Init(NetManager net)\n        {\n            m_net = net;\n        }\n\n        public void Start()\n        {\n            m_lastHeartBeatTime = SGFTime.GetTimeSinceStartup() + SGFRandom.Default.Range(5.0f);\n            GlobalEvent.onUpdate.AddListener(OnUpdate);\n        }\n\n        public void Stop()\n        {\n            GlobalEvent.onUpdate.RemoveListener(OnUpdate);\n        }\n\n        private void OnUpdate(float dt)\n        {\n            float current = SGFTime.GetTimeSinceStartup();\n            if (current - m_lastHeartBeatTime > 5.0f)\n            {\n                m_lastHeartBeatTime = current;\n\n                HeartBeatReq req = new HeartBeatReq();\n                req.ping = (ushort)m_ping;\n                req.timestamp = (uint)TimeUtils.GetTotalMillisecondsSince1970();\n                //m_net.Send<HeartBeatReq, HeartBeatRsp>(ProtoCmd.HeartBeatReq, req, OnHeartBeatRsp,15, OnHeartBeatError);\n                m_net.Send<HeartBeatRsp>(ProtoCmd.HeartBeatReq, req, OnHeartBeatRsp, 15, OnHeartBeatError);\n\n            }\n        }\n\n        private void OnHeartBeatRsp(uint index, HeartBeatRsp rsp)\n        {\n            Debuger.Log();\n            if (rsp.ret.code == 0)\n            {\n                uint current = (uint)TimeUtils.GetTotalMillisecondsSince1970();\n                uint dt = current - rsp.timestamp;\n                m_ping = dt / 2;\n            }\n        }\n\n        private void OnHeartBeatError(NetErrorCode code)\n        {\n            if (code == NetErrorCode.Timeout)\n            {\n                Stop();\n                onTimeout.Invoke();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFAppDemo/Services/Online/OnlineManager.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing SGF;\nusing SGF.Extension;\nusing SGF.Module;\nusing SGF.Network.Core;\nusing SGF.Network.Core.RPCLite;\nusing SGF.Network.General;\nusing SGF.Network.General.Client;\nusing SGF.Time;\nusing SGF.Utils;\nusing SGFAppDemo.Common.Data;\nusing SGFAppDemo.Common.Proto;\nusing SGFAppDemo.Services.Online;\n\nnamespace SGFAppDemo.Services\n{\n    public enum ConnID\n    {\n        ZoneServer = 1,\n        GameServer = 2\n    }\n\n    public class OnlineManager:Singleton<OnlineManager>\n    {\n        private NetManager m_net;\n        private bool m_connected = false;\n        private UserData m_mainUserData = null;\n        private HeartBeatHandler m_heartbeat;\n\n        public void Init()\n        {\n            m_net = new NetManager();\n\n            //m_net.Init(typeof(KCPConnection), (int)ConnID.ZoneServer,0);\n            //m_net.RegisterRPCListener(this);\n            m_net.Init(ConnectionType.RUDP, 0);\n            m_net.Rpc.RegisterListener(this);\n\n            GlobalEvent.onUpdate.AddListener(OnUpdate);\n            ConsoleInput.onInputKey.AddListener(OnInputKey);\n\n            m_heartbeat = new HeartBeatHandler();\n            m_heartbeat.Init(m_net);\n            m_heartbeat.onTimeout.AddListener(OnHeartBeatTimeout);\n        }\n\n        private void OnInputKey(ConsoleKey key)\n        {\n            Debuger.Log(key);\n            if (key == ConsoleKey.F1)\n            {\n                m_net.Dump();\n                ServerProfiler.Init();\n            }\n            else if(key == ConsoleKey.F2)\n            {\n                ServerProfiler.Start();\n                Login(\"slicol\");\n            }\n            else if (key == ConsoleKey.F3)\n            {\n                ServerProfiler.Stop();\n                Logout();\n            }\n            \n        }\n\n        public NetManager Net { get { return m_net; }}\n        public UserData MainUserData\n        {\n            get { return m_mainUserData; }\n        }\n\n        private void OnUpdate(float dt)\n        {\n            m_net.Tick();\n        }\n\n        private void OnHeartBeatTimeout()\n        {\n            Debuger.LogWarning(\"\");\n            CloseConnect();\n            m_heartbeat.Stop();\n\n            //转个菊花\n            //执行断线重连策略\n\n            ReLogin();\n        }\n\n        public void Connect()\n        {\n            if (!m_connected)\n            {\n                m_net.Connect(\"111.230.116.185\", 4540);\n                //m_net.Connect(\"127.0.0.1\", 4540);\n                //m_connected = m_net.Connected;\n                m_connected = m_net.IsConnected;\n            }\n        }\n\n        private void CloseConnect()\n        {\n            m_net.Close();\n            m_connected = false;\n        }\n\n        public void Login(string username)\n        {\n            Connect();\n\n            LoginReq req = new LoginReq();\n            req.name = username;\n            req.id = 0;\n\n            //m_net.Send<LoginReq, LoginRsp>(ProtoCmd.LoginReq, req, OnLoginRsp);\n            m_net.Send<LoginRsp>(ProtoCmd.LoginReq, req, OnLoginRsp);\n        }\n\n        private void ReLogin()\n        {\n            Connect();\n\n            LoginReq req = new LoginReq();\n            req.name = m_mainUserData.name;\n            req.id = m_mainUserData.id;\n\n            //m_net.Send<LoginReq, LoginRsp>(ProtoCmd.LoginReq, req, OnLoginRsp);\n            m_net.Send<LoginRsp>(ProtoCmd.LoginReq, req, OnLoginRsp);\n        }\n\n        private void OnLoginRsp(uint index, LoginRsp rsp)\n        {\n            if (rsp.ret.code == 0)\n            {\n                Debuger.Log(\"UserData:{0}\", rsp.userdata);\n                m_mainUserData = rsp.userdata;\n\n                m_heartbeat.Start();\n            }\n            else\n            {\n                Debuger.LogWarning(rsp.ret.info);\n            }\n        }\n        \n\n\n\n        \n        public void Logout()\n        {\n            m_heartbeat.Stop();\n\n            if (m_mainUserData != null)\n            {\n                //m_net.Invoke(\"Logout\");\n                m_net.Rpc.Invoke(\"Logout\");\n            }\n            m_mainUserData = null;\n        }\n\n        [RPCResponse]\n        private void OnLogout()\n        {\n            m_connected = false;\n        }\n\n    }\n}"
  },
  {
    "path": "SGFAppDemo/Services/Online/ServerProfiler.cs",
    "content": "﻿using System.Collections.Generic;\n\nnamespace SGFAppDemo.Services.Online\n{\n    public class ServerProfiler\n    {\n        private static List<ServerTestBot> m_listBot = new List<ServerTestBot>();\n        private static bool m_start = false;\n        private static bool m_inited = false;\n        public static void Init()\n        {\n            if (m_inited)\n            {\n                return;\n            }\n\n            m_inited = true;\n\n            GlobalEvent.onUpdate.AddListener(OnUpdate);\n            if (m_listBot.Count == 0)\n            {\n                for (int i = 0; i < 1000; i++)\n                {\n                    var bot = new ServerTestBot();\n                    m_listBot.Add(bot);\n                    bot.Init();\n                }\n            }\n        }\n\n        public static void Start()\n        {\n            if (!m_inited)\n            {\n                return;\n            }\n\n            if (m_start)\n            {\n                return;\n            }\n\n            m_start = true;\n            for (int i = 0; i < m_listBot.Count; i++)\n            {\n                m_listBot[i].Login(\"TestName#\" + i);\n            }\n        }\n\n        public static void Stop()\n        {\n            if (!m_inited)\n            {\n                return;\n            }\n\n            if (!m_start)\n            {\n                return;\n            }\n\n            m_start = false;\n            for (int i = 0; i < m_listBot.Count; i++)\n            {\n                m_listBot[i].Logout();\n            }\n        }\n\n        private static void OnUpdate(float dt)\n        {\n            if (!m_inited)\n            {\n                return;\n            }\n\n            for (int i = 0; i < m_listBot.Count; i++)\n            {\n                m_listBot[i].Update();\n            }\n\n\n        }\n    }\n}"
  },
  {
    "path": "SGFAppDemo/Services/Online/ServerTestBot.cs",
    "content": "﻿using SGF;\nusing SGF.Extension;\nusing SGF.Network.General;\nusing SGF.Network.General.Client;\nusing SGFAppDemo.Common.Data;\nusing SGFAppDemo.Common.Proto;\n\nnamespace SGFAppDemo.Services.Online\n{\n    public class ServerTestBot\n    {\n        private NetManager m_net;\n        private bool m_connected = false;\n        private UserData m_mainUserData = null;\n        private HeartBeatHandler m_heartbeat;\n\n\n        public void Init()\n        {\n            m_net = new NetManager();\n            //m_net.Init(typeof(KcpConnection), (int)ConnID.ZoneServer,0);\n            //m_net.RegisterRPCListener(this);\n\n            m_net.Init(ConnectionType.RUDP, 0);\n            m_net.Rpc.RegisterListener(this);\n\n            m_heartbeat = new HeartBeatHandler();\n            m_heartbeat.Init(m_net);\n        }\n\n        public void Connect()\n        {\n            if (!m_connected)\n            {\n                m_net.Connect(\"111.230.116.185\", 4540);\n                //m_net.Connect(\"127.0.0.1\", 4540);\n                //m_connected = m_net.Connected;\n                m_connected = m_net.IsConnected;\n            }\n        }\n\n        public void Update()\n        {\n            m_net.Tick();\n        }\n\n        public void Login(string username)\n        {\n            Connect();\n\n            LoginReq req = new LoginReq();\n            req.name = username;\n\n            //m_net.Send<LoginReq, LoginRsp>(ProtoCmd.LoginReq, req, OnLoginRsp);\n            m_net.Send<LoginRsp>(ProtoCmd.LoginReq, req, OnLoginRsp);\n        }\n\n        public void Logout()\n        {\n            m_heartbeat.Stop();\n            if (m_mainUserData != null)\n            {\n                //m_net.Invoke(\"Logout\");\n                m_net.Rpc.Invoke(\"Logout\");\n            }\n            m_mainUserData = null;\n        }\n\n        private void OnLogout()\n        {\n            Debuger.Log();\n        }\n\n        private void OnLoginRsp(uint index, LoginRsp rsp)\n        {\n            if (rsp.ret.code == 0)\n            {\n                Debuger.Log(\"UserData:{0}\", rsp.userdata);\n                m_mainUserData = rsp.userdata;\n                m_heartbeat.Start();\n            }\n            else\n            {\n                Debuger.LogWarning(rsp.ret.info);\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFAppILRScript/App.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "SGFAppILRScript/ModuleDef.cs",
    "content": "﻿namespace SGFAppDemo\n{\n    internal static class ModuleDef\n    {\n        public const string LoginModule = \"LoginModule\";\n        public const string HomeModule = \"HomeModule\";\n        public const string RoomModule = \"RoomModule\";\n        public const string SettingModule = \"SettingModule\";\n        public const string ActivityModule = \"ActivityModule\";\n        public const string DailyCheckInModule = \"DailyCheckInModule\";\n        public const string ShopModule = \"ShopModule\";\n        public const string ShareModule = \"ShareModule\";\n        public const string PVEModule = \"PVEModule\";\n        public const string PVPModule = \"PVPModule\";\n    }\n}"
  },
  {
    "path": "SGFAppILRScript/Modules/Login/LoginModule.cs",
    "content": "﻿using System;\nusing SGF;\nusing SGF.Module;\nusing SGF.Unity.Common;\nusing SGF.Utils;\nusing SGFAppDemo.Services;\n\n\nnamespace SGFAppDemo.Modules\n{\n    public class LoginModule : GeneralModule\n    {\n        protected override void Show(object arg)\n        {\n            base.Show(arg);\n            Debuger.Log(\"显示登录界面!(模拟一下)\");\n            Console.WriteLine(\"输入命令进行操作\");\n            Console.WriteLine(\"命令格式：Login %username%\");\n            Console.WriteLine(\"命令格式：Logout\");\n            Console.WriteLine(\"命令格式：ShowRoom\");\n            ConsoleInput.onInputLine.AddListener(OnInputLine);\n        }\n        \n        private void OnInputLine(string line)\n        {\n            if (line.StartsWith(\"Login\"))\n            {\n                string[] args = line.Split(' ');\n                if (args.Length > 1)\n                {\n                    string username = args[1];\n                    OnlineManager.Instance.Login(username);\n                }\n                else\n                {\n                    Debuger.LogError(\"输入格式错误!\");\n                }\n            }\n            else if (line == \"Logout\")\n            {\n                OnlineManager.Instance.Logout();\n            }\n            else if (line == \"ShowRoom\")\n            {\n                ModuleManager.Instance.ShowModule(ModuleDef.RoomModule);\n            }\n\n        }\n        \n    }\n}"
  },
  {
    "path": "SGFAppILRScript/Modules/Room/RoomModule.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing SGF;\nusing SGF.Extension;\nusing SGF.Module;\nusing SGF.Network.Core;\nusing SGF.Network.Core.RPCLite;\nusing SGF.Network.FSPLite;\nusing SGF.Utils;\nusing SGFAppDemo.Common.Data;\nusing SGFAppDemo.Services;\n\nnamespace SGFAppDemo.Modules\n{\n    public class RoomModule : GeneralModule\n    {\n        private List<RoomData> m_listRoom = null;\n        private RoomData m_currRoom = new RoomData();\n\n        protected override void Show(object arg)\n        {\n            base.Show(arg);\n            Debuger.Log(\"显示房间界面!(模拟一下)\");\n            Debuger.Log(\"显示登录界面!(模拟一下)\");\n            Console.WriteLine(\"输入命令进行操作\");\n            Console.WriteLine(\"命令格式：ShowRoomList\");\n            Console.WriteLine(\"命令格式：CreateRoom %roomname%\");\n            Console.WriteLine(\"命令格式：JoinRoom %roomid%\");\n            Console.WriteLine(\"命令格式：ExitRoom\");\n            Console.WriteLine(\"命令格式：RoomReady %ready%\");\n            ConsoleInput.onInputLine.AddListener(OnInputLine);\n\n            OnlineManager.Instance.Net.Rpc.RegisterListener(this);\n        }\n\n\n        private void OnInputLine(string line)\n        {\n            if (line == \"ShowRoomList\")\n            {\n                OnlineManager.Instance.Net.Rpc.Invoke(\"GetRoomList\");\n            }\n            else if(line.StartsWith(\"CreateRoom\"))\n            {\n                string[] args = line.Split(' ');\n                if (args.Length > 1)\n                {\n                    UserData ud = OnlineManager.Instance.MainUserData;\n                    string name = args[1];\n                    OnlineManager.Instance.Net.Rpc.Invoke(\"CreateRoom\", ud.id, name);\n                }\n                else\n                {\n                    Debuger.LogError(\"输入格式错误!\");\n                }\n            }\n            else if (line.StartsWith(\"JoinRoom\"))\n            {\n                string[] args = line.Split(' ');\n                if (args.Length > 1)\n                {\n                    UserData ud = OnlineManager.Instance.MainUserData;\n                    uint id = uint.Parse(args[1]);\n                    \n                    OnlineManager.Instance.Net.Rpc.Invoke(\"JoinRoom\", ud.id, id);\n                    \n                }\n                else\n                {\n                    Debuger.LogError(\"输入格式错误!\");\n                }\n            }\n            else if (line == \"ExitRoom\")\n            {\n                UserData ud = OnlineManager.Instance.MainUserData;\n                OnlineManager.Instance.Net.Rpc.Invoke(\"ExitRoom\", ud.id, m_currRoom.id);\n            }\n            else if (line.StartsWith(\"RoomReady\"))\n            {\n                string[] args = line.Split(' ');\n                if (args.Length > 1)\n                {\n                    bool ready = args[1] == \"true\";\n                    UserData ud = OnlineManager.Instance.MainUserData;\n                    OnlineManager.Instance.Net.Rpc.Invoke(\"RoomReady\", ud.id, m_currRoom.id, ready);\n                }\n                else\n                {\n                    Debuger.LogError(\"输入格式错误!\");\n                }\n            }\n            else if (line == \"StartGame\")\n            {\n                UserData ud = OnlineManager.Instance.MainUserData;\n                OnlineManager.Instance.Net.Rpc.Invoke(\"StartGame\", ud.id, m_currRoom.id);\n            }\n\n        }\n\n\n        [RPCResponse]\n        private void OnGetRoomList(RoomListData data)\n        {\n            if (data != null)\n            {\n                m_listRoom = data.rooms;\n                for (int i = 0; i < m_listRoom.Count; i++)\n                {\n                    Debuger.LogWarning(m_listRoom[i].ToString());\n                }\n            }\n            else\n            {\n                Debuger.LogWarning(\"房间列表为空！\");\n            }\n        }\n\n\n        [RPCResponse]\n        private void OnCreateRoom(RoomData data)\n        {\n            Debuger.Log(data.ToString());\n            m_currRoom = data;\n        }\n\n        [RPCResponse]\n        private void OnJoinRoom(RoomData data)\n        {\n            Debuger.Log(data.ToString());\n            m_currRoom = data;\n        }\n\n        [RPCNotify]\n        private void NotifyRoomUpdate(RoomData data)\n        {\n            Debuger.Log(data.ToString());\n            m_currRoom = data;\n        }\n\n        [RPCNotify]\n        private void NotifyGameStart(FSPParam param)\n        {\n            Debuger.LogWarning(param.ToString());\n        }\n    }\n}"
  },
  {
    "path": "SGFAppILRScript/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// 有关程序集的一般信息由以下\n// 控制。更改这些特性值可修改\n// 与程序集关联的信息。\n[assembly: AssemblyTitle(\"SGFAppILRScript\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"HP Inc.\")]\n[assembly: AssemblyProduct(\"SGFAppILRScript\")]\n[assembly: AssemblyCopyright(\"Copyright © HP Inc. 2017\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// 将 ComVisible 设置为 false 会使此程序集中的类型\n//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型\n//请将此类型的 ComVisible 特性设置为 true。\n[assembly: ComVisible(false)]\n\n// 如果此项目向 COM 公开，则下列 GUID 用于类型库的 ID\n[assembly: Guid(\"eeb72dfc-0fa5-44de-b75a-586f69377aa8\")]\n\n// 程序集的版本信息由下列四个值组成: \n//\n//      主版本\n//      次版本\n//      生成号\n//      修订号\n//\n// 可以指定所有值，也可以使用以下所示的 \"*\" 预置版本号和修订号\n// 方法是按如下所示使用“*”: :\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "SGFAppILRScript/SGFAppILRScript.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{4704169C-4BAD-4CFB-842A-2F4E3FC60375}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>SGFAppDemo</RootNamespace>\n    <AssemblyName>SGFAppILRScript</AssemblyName>\n    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>\n    <TargetFrameworkProfile />\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>..\\Apps\\</OutputPath>\n    <DefineConstants>TRACE;DEBUG;ENABLE_LOG</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>0</WarningLevel>\n    <Prefer32Bit>false</Prefer32Bit>\n    <DocumentationFile>\n    </DocumentationFile>\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>..\\Apps\\</OutputPath>\n    <DefineConstants>TRACE;ENABLE_LOG</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>0</WarningLevel>\n    <Prefer32Bit>false</Prefer32Bit>\n    <DocumentationFile>\n    </DocumentationFile>\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n  </PropertyGroup>\n  <PropertyGroup>\n    <StartupObject />\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"ILRuntime, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\ILRuntime.dll</HintPath>\n    </Reference>\n    <Reference Include=\"protobuf-net, Version=2.0.0.668, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\protobuf-net.dll</HintPath>\n    </Reference>\n    <Reference Include=\"SGFCore, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\SGFCore.dll</HintPath>\n    </Reference>\n    <Reference Include=\"SGFDebuger, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\SGFDebuger.dll</HintPath>\n    </Reference>\n    <Reference Include=\"SGFUnity, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\SGFUnity.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"ModuleDef.cs\" />\n    <Compile Include=\"Modules\\Login\\LoginModule.cs\" />\n    <Compile Include=\"Modules\\Room\\RoomModule.cs\" />\n    <Compile Include=\"ScriptMain.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"App.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\SGFAppCommon\\SGFAppCommon.csproj\">\n      <Project>{a1bf1b00-7cdf-4a48-8d33-98645e5df606}</Project>\n      <Name>SGFAppCommon</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\SGFAppDemo\\SGFAppDemo.csproj\">\n      <Project>{3facc3dd-ffa2-4fe7-b9b6-063260594af1}</Project>\n      <Name>SGFAppDemo</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <PropertyGroup>\n    <PostBuildEvent>\n    </PostBuildEvent>\n  </PropertyGroup>\n</Project>"
  },
  {
    "path": "SGFAppILRScript/SGFAppILRScript.csproj.user",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <PropertyGroup>\n    <ProjectView>ProjectFiles</ProjectView>\n  </PropertyGroup>\n</Project>"
  },
  {
    "path": "SGFAppILRScript/ScriptMain.cs",
    "content": "﻿\nusing System;\nusing SGF;\nusing SGF.Module;\n\n\nnamespace SGFAppDemo\n{\n    public class ScriptMain\n    {\n\n        public static bool Init()\n        {\n            Debuger.Log();\n            ModuleManager.Instance.CreateModule(ModuleDef.LoginModule);\n            ModuleManager.Instance.CreateModule(ModuleDef.RoomModule);\n\n            ModuleManager.Instance.ShowModule(ModuleDef.LoginModule);\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFCore/App.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "SGFCore/Class1.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SGFCore\n{\n    public class Class1\n    {\n    }\n}\n"
  },
  {
    "path": "SGFCore/Codec/MiniJSON.cs",
    "content": "/*\n * Copyright (c) 2013 Calvin Rien\n *\n * Based on the JSON parser by Patrick van Bergen\n * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html\n *\n * Simplified it so that it doesn't throw exceptions\n * and can be used in Unity iPhone with maximum code stripping.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nnamespace MiniJSON.Safe\n{\n    // Example usage:\n    //\n    //  using UnityEngine;\n    //  using System.Collections;\n    //  using System.Collections.Generic;\n    //  using MiniJSON;\n    //\n    //  public class MiniJSONTest : MonoBehaviour {\n    //      void Start () {\n    //          var jsonString = \"{ \\\"array\\\": [1.44,2,3], \" +\n    //                          \"\\\"object\\\": {\\\"key1\\\":\\\"value1\\\", \\\"key2\\\":256}, \" +\n    //                          \"\\\"string\\\": \\\"The quick brown fox \\\\\\\"jumps\\\\\\\" over the lazy dog \\\", \" +\n    //                          \"\\\"unicode\\\": \\\"\\\\u3041 Men\\u00fa sesi\\u00f3n\\\", \" +\n    //                          \"\\\"int\\\": 65536, \" +\n    //                          \"\\\"float\\\": 3.1415926, \" +\n    //                          \"\\\"bool\\\": true, \" +\n    //                          \"\\\"null\\\": null }\";\n    //\n    //          var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;\n    //\n    //          Debug.Log(\"deserialized: \" + dict.GetType());\n    //          Debug.Log(\"dict['array'][0]: \" + ((List<object>) dict[\"array\"])[0]);\n    //          Debug.Log(\"dict['string']: \" + (string) dict[\"string\"]);\n    //          Debug.Log(\"dict['float']: \" + (double) dict[\"float\"]); // floats come out as doubles\n    //          Debug.Log(\"dict['int']: \" + (long) dict[\"int\"]); // ints come out as longs\n    //          Debug.Log(\"dict['unicode']: \" + (string) dict[\"unicode\"]);\n    //\n    //          var str = Json.Serialize(dict);\n    //\n    //          Debug.Log(\"serialized: \" + str);\n    //      }\n    //  }\n\n    /// <summary>\n    /// This class encodes and decodes JSON strings.\n    /// Spec. details, see http://www.json.org/\n    ///\n    /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.\n    /// All numbers are parsed to doubles.\n    /// </summary>\n    public static class Json\n    {\n        /// <summary>\n        /// Parses the string json into a value\n        /// </summary>\n        /// <param name=\"json\">A JSON string.</param>\n        /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns>\n        public static object Deserialize(string json)\n        {\n            // save the string for debug information\n            if (json == null)\n            {\n                return null;\n            }\n\n            return Parser.Parse(json);\n        }\n\n        sealed class Parser : IDisposable\n        {\n            const string WORD_BREAK = \"{}[],:\\\"\";\n\n            public static bool IsWordBreak(char c)\n            {\n                return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;\n            }\n\n            enum TOKEN\n            {\n                NONE,\n                CURLY_OPEN,\n                CURLY_CLOSE,\n                SQUARED_OPEN,\n                SQUARED_CLOSE,\n                COLON,\n                COMMA,\n                STRING,\n                NUMBER,\n                TRUE,\n                FALSE,\n                NULL\n            };\n\n            StringReader json;\n\n            Parser(string jsonString)\n            {\n                json = new StringReader(jsonString);\n            }\n\n            public static object Parse(string jsonString)\n            {\n                using (var instance = new Parser(jsonString))\n                {\n                    return instance.ParseValue();\n                }\n            }\n\n            public void Dispose()\n            {\n                json.Dispose();\n                json = null;\n            }\n\n            JsonObject ParseObject()\n            {\n                JsonObject table = new JsonObject();\n\n                // ditch opening brace\n                json.Read();\n\n                // {\n                while (true)\n                {\n                    switch (NextToken)\n                    {\n                        case TOKEN.NONE:\n                            return null;\n                        case TOKEN.COMMA:\n                            continue;\n                        case TOKEN.CURLY_CLOSE:\n                            return table;\n                        default:\n                            // name\n                            string name = ParseString();\n                            if (name == null)\n                            {\n                                return null;\n                            }\n\n                            // :\n                            if (NextToken != TOKEN.COLON)\n                            {\n                                return null;\n                            }\n                            // ditch the colon\n                            json.Read();\n\n                            // value\n                            table[name] = ParseValue();\n                            break;\n                    }\n                }\n            }\n\n            List<object> ParseArray()\n            {\n                List<object> array = new List<object>();\n\n                // ditch opening bracket\n                json.Read();\n\n                // [\n                var parsing = true;\n                while (parsing)\n                {\n                    TOKEN nextToken = NextToken;\n\n                    switch (nextToken)\n                    {\n                        case TOKEN.NONE:\n                            return null;\n                        case TOKEN.COMMA:\n                            continue;\n                        case TOKEN.SQUARED_CLOSE:\n                            parsing = false;\n                            break;\n                        default:\n                            object value = ParseByToken(nextToken);\n\n                            array.Add(value);\n                            break;\n                    }\n                }\n\n                return array;\n            }\n\n            object ParseValue()\n            {\n                TOKEN nextToken = NextToken;\n                return ParseByToken(nextToken);\n            }\n\n            object ParseByToken(TOKEN token)\n            {\n                switch (token)\n                {\n                    case TOKEN.STRING:\n                        return ParseString();\n                    case TOKEN.NUMBER:\n                        return ParseNumber();\n                    case TOKEN.CURLY_OPEN:\n                        return ParseObject();\n                    case TOKEN.SQUARED_OPEN:\n                        return ParseArray();\n                    case TOKEN.TRUE:\n                        return true;\n                    case TOKEN.FALSE:\n                        return false;\n                    case TOKEN.NULL:\n                        return null;\n                    default:\n                        return null;\n                }\n            }\n\n            string ParseString()\n            {\n                StringBuilder s = new StringBuilder();\n                char c;\n\n                // ditch opening quote\n                json.Read();\n\n                bool parsing = true;\n                while (parsing)\n                {\n\n                    if (json.Peek() == -1)\n                    {\n                        parsing = false;\n                        break;\n                    }\n\n                    c = NextChar;\n                    switch (c)\n                    {\n                        case '\"':\n                            parsing = false;\n                            break;\n                        case '\\\\':\n                            if (json.Peek() == -1)\n                            {\n                                parsing = false;\n                                break;\n                            }\n\n                            c = NextChar;\n                            switch (c)\n                            {\n                                case '\"':\n                                case '\\\\':\n                                case '/':\n                                    s.Append(c);\n                                    break;\n                                case 'b':\n                                    s.Append('\\b');\n                                    break;\n                                case 'f':\n                                    s.Append('\\f');\n                                    break;\n                                case 'n':\n                                    s.Append('\\n');\n                                    break;\n                                case 'r':\n                                    s.Append('\\r');\n                                    break;\n                                case 't':\n                                    s.Append('\\t');\n                                    break;\n                                case 'u':\n                                    var hex = new char[4];\n\n                                    for (int i = 0; i < 4; i++)\n                                    {\n                                        hex[i] = NextChar;\n                                    }\n\n                                    s.Append((char)Convert.ToInt32(new string(hex), 16));\n                                    break;\n                            }\n                            break;\n                        default:\n                            s.Append(c);\n                            break;\n                    }\n                }\n\n                return s.ToString();\n            }\n\n            object ParseNumber()\n            {\n                string number = NextWord;\n\n                if (number.IndexOf('.') == -1)\n                {\n                    int parsedInt;\n                    Int32.TryParse(number, out parsedInt);\n                    return parsedInt;\n                }\n\n                float parsedDouble;\n                float.TryParse(number, out parsedDouble);\n                return parsedDouble;\n            }\n\n            void EatWhitespace()\n            {\n                while (Char.IsWhiteSpace(PeekChar))\n                {\n                    json.Read();\n\n                    if (json.Peek() == -1)\n                    {\n                        break;\n                    }\n                }\n            }\n\n            char PeekChar\n            {\n                get\n                {\n                    return Convert.ToChar(json.Peek());\n                }\n            }\n\n            char NextChar\n            {\n                get\n                {\n                    return Convert.ToChar(json.Read());\n                }\n            }\n\n            string NextWord\n            {\n                get\n                {\n                    StringBuilder word = new StringBuilder();\n\n                    while (!IsWordBreak(PeekChar))\n                    {\n                        word.Append(NextChar);\n\n                        if (json.Peek() == -1)\n                        {\n                            break;\n                        }\n                    }\n\n                    return word.ToString();\n                }\n            }\n\n            TOKEN NextToken\n            {\n                get\n                {\n                    EatWhitespace();\n\n                    if (json.Peek() == -1)\n                    {\n                        return TOKEN.NONE;\n                    }\n\n                    switch (PeekChar)\n                    {\n                        case '{':\n                            return TOKEN.CURLY_OPEN;\n                        case '}':\n                            json.Read();\n                            return TOKEN.CURLY_CLOSE;\n                        case '[':\n                            return TOKEN.SQUARED_OPEN;\n                        case ']':\n                            json.Read();\n                            return TOKEN.SQUARED_CLOSE;\n                        case ',':\n                            json.Read();\n                            return TOKEN.COMMA;\n                        case '\"':\n                            return TOKEN.STRING;\n                        case ':':\n                            return TOKEN.COLON;\n                        case '0':\n                        case '1':\n                        case '2':\n                        case '3':\n                        case '4':\n                        case '5':\n                        case '6':\n                        case '7':\n                        case '8':\n                        case '9':\n                        case '-':\n                            return TOKEN.NUMBER;\n                    }\n\n                    switch (NextWord)\n                    {\n                        case \"false\":\n                            return TOKEN.FALSE;\n                        case \"true\":\n                            return TOKEN.TRUE;\n                        case \"null\":\n                            return TOKEN.NULL;\n                    }\n\n                    return TOKEN.NONE;\n                }\n            }\n        }\n\n        /// <summary>\n        /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string\n        /// </summary>\n        /// <param name=\"json\">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param>\n        /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>\n        public static string Serialize(object obj)\n        {\n            return Serializer.Serialize(obj);\n        }\n\n        sealed class Serializer\n        {\n            StringBuilder builder;\n\n            Serializer()\n            {\n                builder = new StringBuilder();\n            }\n\n            public static string Serialize(object obj)\n            {\n                var instance = new Serializer();\n\n                instance.SerializeValue(obj);\n\n                return instance.builder.ToString();\n            }\n\n            void SerializeValue(object value)\n            {\n                IList asList;\n                IDictionary asDict;\n                string asStr;\n\n                if (value == null)\n                {\n                    builder.Append(\"null\");\n                }\n                else if ((asStr = value as string) != null)\n                {\n                    SerializeString(asStr);\n                }\n                else if (value is bool)\n                {\n                    builder.Append((bool)value ? \"true\" : \"false\");\n                }\n                else if ((asList = value as IList) != null)\n                {\n                    SerializeArray(asList);\n                }\n                else if ((asDict = value as IDictionary) != null)\n                {\n                    SerializeObject(asDict);\n                }\n                else if (value is char)\n                {\n                    SerializeString(new string((char)value, 1));\n                }\n                else\n                {\n                    SerializeOther(value);\n                }\n            }\n\n            void SerializeObject(IDictionary obj)\n            {\n                bool first = true;\n\n                builder.Append('{');\n\n                foreach (object e in obj.Keys)\n                {\n                    if (!first)\n                    {\n                        builder.Append(',');\n                    }\n\n                    SerializeString(e.ToString());\n                    builder.Append(':');\n\n                    SerializeValue(obj[e]);\n\n                    first = false;\n                }\n\n                builder.Append('}');\n            }\n\n            void SerializeArray(IList anArray)\n            {\n                builder.Append('[');\n\n                bool first = true;\n\n                foreach (object obj in anArray)\n                {\n                    if (!first)\n                    {\n                        builder.Append(',');\n                    }\n\n                    SerializeValue(obj);\n\n                    first = false;\n                }\n\n                builder.Append(']');\n            }\n\n            void SerializeString(string str)\n            {\n                builder.Append('\\\"');\n\n                char[] charArray = str.ToCharArray();\n                foreach (var c in charArray)\n                {\n                    switch (c)\n                    {\n                        case '\"':\n                            builder.Append(\"\\\\\\\"\");\n                            break;\n                        case '\\\\':\n                            builder.Append(\"\\\\\\\\\");\n                            break;\n                        case '\\b':\n                            builder.Append(\"\\\\b\");\n                            break;\n                        case '\\f':\n                            builder.Append(\"\\\\f\");\n                            break;\n                        case '\\n':\n                            builder.Append(\"\\\\n\");\n                            break;\n                        case '\\r':\n                            builder.Append(\"\\\\r\");\n                            break;\n                        case '\\t':\n                            builder.Append(\"\\\\t\");\n                            break;\n                        default:\n                            int codepoint = Convert.ToInt32(c);\n                            if ((codepoint >= 32) && (codepoint <= 126))\n                            {\n                                builder.Append(c);\n                            }\n                            else\n                            {\n                                builder.Append(\"\\\\u\");\n                                builder.Append(codepoint.ToString(\"x4\"));\n                            }\n                            break;\n                    }\n                }\n\n                builder.Append('\\\"');\n            }\n\n            void SerializeOther(object value)\n            {\n                // NOTE: decimals lose precision during serialization.\n                // They always have, I'm just letting you know.\n                // Previously floats and doubles lost precision too.\n                if (value is float)\n                {\n                    builder.Append(((float)value).ToString(\"R\"));\n                }\n                else if (value is int\n                  || value is uint\n                  || value is long\n                  || value is sbyte\n                  || value is byte\n                  || value is short\n                  || value is ushort\n                  || value is ulong)\n                {\n                    builder.Append(value);\n                }\n                else if (value is double\n                  || value is decimal)\n                {\n                    builder.Append(Convert.ToDouble(value).ToString(\"R\"));\n                }\n                else\n                {\n                    SerializeString(value.ToString());\n                }\n            }\n        }\n    }\n\n\n    public class JsonObject : Dictionary<string, object>\n    {\n        public new object this[string indexKey]\n        {\n            set { base[indexKey] = value; }\n            get\n            {\n                object tmp = default(object);\n                base.TryGetValue(indexKey, out tmp);\n                return tmp;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFCore/Codec/PBSerializer.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 封装Protobuf(https://github.com/google/protobuf)以提供简捷的使用方式\n * Package Protobuf (https://github.com/google/protobuf) to provide a simple way to use\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing ProtoBuf;\nusing ProtoBuf.Meta;\nusing System.IO;\n\nnamespace SGF.Codec\n{\n    /// <summary>\n    /// 序列化帮助类\n    /// </summary>\n    public class PBSerializer\n    {\n\n        public static T Clone<T>(T data)\n        {\n            byte[] buffer = NSerialize<T>(data);\n            return NDeserialize<T>(buffer);\n        }\n\n\n        /// <summary>\n        /// 序列化pb数据\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"t\"></param>\n        /// <returns></returns>\n        public static byte[] NSerialize<T>(T t)\n        {\n            byte[] buffer = null;\n\n            using (MemoryStream m = new MemoryStream())\n            {\n                Serializer.Serialize<T>(m, t);\n\n                m.Position = 0;\n                int length = (int)m.Length;\n                buffer = new byte[length];\n                m.Read(buffer, 0, length);\n            }\n\n            return buffer;\n        }\n\n        public static byte[] NSerialize(object t)\n        {\n            byte[] buffer = null;\n\n            using (MemoryStream m = new MemoryStream())\n            {\n                if (t != null)\n                {\n                    RuntimeTypeModel.Default.Serialize(m, t);\n                }\n\n                m.Position = 0;\n                int length = (int)m.Length;\n                buffer = new byte[length];\n                m.Read(buffer, 0, length);\n            }\n\n            return buffer;\n        }\n\n\n        public static int NSerialize(object t, byte[] buffer)\n        {\n            using (MemoryStream m = new MemoryStream())\n            {\n                if (t != null)\n                {\n                    RuntimeTypeModel.Default.Serialize(m, t);\n                }\n\n                m.Position = 0;\n                int length = (int)m.Length;\n                m.Read(buffer, 0, length);\n                return length;\n            }\n            return 0;\n        }\n\n\n\n        /// <summary>\n        /// 反序列化pb数据\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"buffer\"></param>\n        /// <returns></returns>\n        public static T NDeserialize<T>(byte[] buffer)\n        {\n            T t = default(T);\n            using (MemoryStream m = new MemoryStream(buffer))\n            {\n                t = Serializer.Deserialize<T>(m);\n            }\n            return t;\n        }\n\n        public static object NDeserialize(byte[] buffer, System.Type type)\n        {\n            object t = null;\n            using (MemoryStream m = new MemoryStream(buffer))\n            {\n                t = RuntimeTypeModel.Default.Deserialize(m, null, type);\n            }\n            return t;\n        }\n\n        public static object NDeserialize(MemoryStream buffer, System.Type type)\n        {\n            object t = null;\n            t = RuntimeTypeModel.Default.Deserialize(buffer, null, type);\n            return t;\n        }\n\n\n        public static object NDeserialize(byte[] buffer, int len, System.Type type)\n        {\n            object t = null;\n            using (MemoryStream m = new MemoryStream(buffer))\n            {\n                t = RuntimeTypeModel.Default.Deserialize(m, null, type, len);\n            }\n            return t;\n        }\n\n\n        public static T NDeserialize<T>(Stream stream)\n        {\n            T t = default(T);\n            t = Serializer.Deserialize<T>(stream);\n            return t;\n        }\n    }\n\n}"
  },
  {
    "path": "SGFCore/Codec/SGFEncoding.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 实现一些常用而【简单】的编解码算法,\n * 对于一些复杂的算法将采用单独的类来实现\n * Implement some common and simple codec algorithms,\n * For some complex algorithms will use a separate class to achieve.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\n\n\n\nnamespace SGF.Codec\n{\n    public class SGFEncoding\n    {\n        public static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n        public static String BytesToHex(byte[] bytes, int size = 0)\n        {\n            \n            if (bytes == null || bytes.Length == 0)\n            {\n                return null;\n            }\n\n            if (size <= 0 || size > bytes.Length)\n            {\n                size = bytes.Length;\n            }\n\n            char[] buf = new char[2 * size];\n            for (int i = 0; i < size; i++)\n            {\n                byte b = bytes[i];\n                buf[2 * i + 1] = digits[b & 0xF];\n                b = (byte)(b >> 4);\n                buf[2 * i + 0] = digits[b & 0xF];\n            }\n            return new String(buf);\n        }\n\n        public static byte[] HexToBytes(String s)\n        {\n\n            int len = s.Length;\n            byte[] data = new byte[len / 2];\n            for (int i = 0; i < len; i += 2)\n            {\n\n                data[i / 2] = (byte)((CharToValue(s[i]) << 4) + (CharToValue(s[i + 1])));\n            }\n            return data;\n        }\n\n        public static string Number2BinString(long value, int bitCnt)\n        {\n            return Number2BinString((ulong) value, bitCnt);\n        }\n\n        public static string Number2BinString(ulong value, int bitCnt)\n        {\n            string str = \"\";\n            for (int i = 0; i < bitCnt; i++)\n            {\n                if ((value & (ulong) (1 << i)) != 0)\n                {\n                    str = \"1\" + str;\n                }\n                else\n                {\n                    str = \"0\" + str;\n                }\n            }\n            return str;\n        }\n\n        private static byte CharToValue(char ch)\n        {\n            if (ch >= '0' && ch <= '9')\n            {\n                return (byte)(ch - '0');\n            }\n            else if (ch >= 'a' && ch <= 'f')\n            {\n                return (byte)(ch - 'a' + 10);\n            }\n            else if (ch >= 'A' && ch <= 'F')\n            {\n                return (byte)(ch - 'A' + 10);\n            }\n\n            return 0;\n        }\n\n\n        public static int XORCodec(byte[] buffer, int begin, int len,  byte[] key)\n        {\n            if (buffer == null || key == null || key.Length == 0)\n            {\n                return -1;\n            }\n\n            if (begin + len >= buffer.Length)\n            {\n                return -1;\n            }\n\n            int blockSize = key.Length;\n            int j = 0;\n            for (j = begin; j < begin + len; j++)\n            {\n                buffer[j] = (byte)(buffer[j] ^ key[(j - begin) % blockSize]);\n            }\n\n            return j;\n        }\n\n        public static int XORCodec(byte[] inBytes, byte[] outBytes, byte[] keyBytes)\n        {\n            if (inBytes == null || outBytes == null || keyBytes == null || keyBytes.Length == 0)\n            {\n                return -1;\n            }\n\n            if (outBytes.Length < inBytes.Length)\n            {\n                return -1;\n            }\n\n            int blockSize = keyBytes.Length;\n            int j = 0;\n            for (j = 0; j < inBytes.Length; j++)\n            {\n                outBytes[j] = (byte)(inBytes[j] ^ keyBytes[j % blockSize]);\n            }\n\n            return j;\n        }\n\n\n\n        public static ushort CheckSum(byte[] buffer, int size)\n        {\n            ulong sum = 0;\n            int i = 0;\n            while (size > 1)\n            {\n                sum = sum + BitConverter.ToUInt16(buffer, i);\n                size -= 2;\n                i += 2;\n            }\n            if (size > 0)\n            {\n                sum += buffer[i];\n            }\n\n            while ((sum >> 16) != 0)\n            {\n                sum = (sum >> 16) + (sum & 0xffff);\n            }\n\n            return (ushort)(~sum);\n        }\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/Event/Signal.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang (slicol@qq.com). All rights reserved.\n * \n * 一个高性能的事件(信号)系统\n * A high performance event (signal) system\n * \n * 它的思路与系统自带的Action类似，\n * 但是在性能与逻辑上比原生的Action更加可控，\n * 并且能够以日志的方式进行追踪和调试。\n * 这在实际应用中非常有用。\n * 并且非常高性能和低GC\n * Its idea is similar to the Action, \n * but it is more controllable than the original Action in terms of performance and logic, \n * and can be tracked and debugged in log mode.\n * This is very useful in practical applications.\n *\n *\n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\n\nusing System;\nusing SGF;\n\nnamespace SGF.SEvent\n{\n    public class SignalBase\n    {\n        protected int _methodCount;\n        protected Delegate[] _methods;\n        protected bool _needClean = false;\n\n        public SignalBase(int capacity)\n        {\n            _methods = new Delegate[capacity];\n            _methodCount = 0;\n        }\n\n        public SignalBase()\n        {\n            _methods = new Delegate[10];\n            _methodCount = 0;\n        }\n\n        protected void AddListener(Delegate del, bool bInsertAtFirst)\n        {\n            if (bInsertAtFirst)\n            {\n                if (_methods[0] == del)\n                {\n                    return;\n                }\n\n                Delegate[] listTemp;\n                if (_methodCount + 1 > _methods.Length)\n                {\n                    listTemp = new Delegate[_methods.Length * 2];\n                }\n                else\n                {\n                    listTemp = new Delegate[_methods.Length];\n                }\n\n                bool hasExist = false;\n                int j = 0;\n                listTemp[j++] = del;\n                for (int i = 0; i < _methodCount; i++)\n                {\n                    if (_methods[i] == del)\n                    {\n                        hasExist = true;\n                        continue;\n                    }\n                    listTemp[j++] = _methods[i];\n                }\n\n                if (!hasExist)\n                {\n                    _methodCount++;\n                }\n\n                _methods = listTemp;\n            }\n            else\n            {\n                for (int i = 0; i < _methodCount; i++)\n                {\n                    if (_methods[i] == del)\n                    {\n                        return;\n                    }\n                }\n\n                if (_methodCount + 1 > _methods.Length)\n                {\n                    Delegate[] listTemp;\n                    listTemp = new Delegate[_methods.Length * 2];\n                    Array.Copy(_methods, 0, listTemp, 0, _methodCount);\n                    _methods = listTemp;\n                }\n                _methods[_methodCount] = del;\n                _methodCount++;\n            }\n\n        }\n\n        protected void RemoveListener(Delegate del)\n        {\n            int j = 0;\n            int c = _methodCount;\n            for (int i = 0; i < c; i++)\n            {\n                if (_methods[i] == del)\n                {\n                    _needClean = true;\n                    _methods[i] = null;\n                    break;\n                }\n            }\n        }\n\n        public void RemoveAllListeners()\n        {\n            for (int i = 0; i < _methodCount; i++)\n            {\n                _methods[i] = null;\n            }\n            _methodCount = 0;\n        }\n\n\n        protected void TryClean()\n        {\n            if (_needClean)\n            {\n                _needClean = false;\n                int i = _methodCount;\n                while (i > 0)\n                {\n                    i--;\n                    if (_methods[i] == null)\n                    {\n                        _methodCount--;\n                        for (int j = i; j < _methodCount; j++)\n                        {\n                            _methods[i] = _methods[i + 1];\n                        }\n                    }\n                }\n\n            }\n        }\n\n\n        public int GetListenerCount()\n        {\n            return _methodCount;\n        }\n    }\n\n\n    /// <summary>\n    /// 尽管Signal的实现已经具备很高性能\n    /// 但是肯定比不上直接的函数调用，所以，如果需要最高性能，请用Delegate\n    /// 但是，Signal在内存上比Delegate有较大优势\n    /// 请综合考虑\n    /// </summary>\n    public class Signal : SignalBase\n    {\n\n        public static Signal operator +(Signal p1, Action p2)\n        {\n            p1.AddListener(p2, false);\n            return p1;\n        }\n\n        public static Signal operator -(Signal p1, Action p2)\n        {\n            p1.RemoveListener(p2);\n            return p1;\n        }\n\n        public void AddListener(Action a, bool bInsertAtFirst = false)\n        {\n            base.AddListener(a, bInsertAtFirst);\n        }\n\n        public void RemoveListener(Action a)\n        {\n            base.RemoveListener(a);\n        }\n\n        public void Invoke()\n        {\n\n            int c = _methodCount;\n            var methods = _methods;\n            for (int i = 0; i < c; i++)\n            {\n                var item = methods[i];\n                if (item == null)\n                    continue;\n                var action = item as Action;\n                action();\n            }\n\n            TryClean();\n        }\n\n        public void InvokeSafe()\n        {\n            try\n            {\n                int c = _methodCount;\n                var methods = _methods;\n                for (int i = 0; i < c; i++)\n                {\n                    var item = methods[i];\n                    if (item == null)\n                        continue;\n                    var action = item as Action;\n                    action();\n                }\n\n                TryClean();\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(e);\n            }\n        }\n\n        public Signal(int capacity) : base(capacity)\n        {\n        }\n\n        public Signal()\n        {\n        }\n    }\n\n\n    public class Signal<T> : SignalBase\n    {\n        public static Signal<T> operator +(Signal<T> p1, Action<T> p2)\n        {\n            p1.AddListener(p2, false);\n            return p1;\n        }\n\n        public static Signal<T> operator -(Signal<T> p1, Action<T> p2)\n        {\n            p1.RemoveListener(p2);\n            return p1;\n        }\n\n        public void AddListener(Action<T> a, bool bInsertAtFirst = false)\n        {\n            base.AddListener(a, bInsertAtFirst);\n        }\n\n        public void RemoveListener(Action<T> a)\n        {\n            base.RemoveListener(a);\n        }\n\n        public void Invoke(T t1)\n        {\n\n            int c = _methodCount;\n            var methods = _methods;\n            for (int i = 0; i < c; i++)\n            {\n                var item = methods[i];\n                if (item == null)\n                    continue;\n                var action = item as Action<T>;\n                action(t1);\n            }\n\n            TryClean();\n        }\n\n        public void InvokeSafe(T t)\n        {\n            try\n            {\n\n                int c = _methodCount;\n                var methods = _methods;\n                for (int i = 0; i < c; i++)\n                {\n                    var item = methods[i];\n                    if (item == null)\n                        continue;\n                    var action = item as Action<T>;\n                    action(t);\n                }\n\n                TryClean();\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(e);\n            }\n        }\n\n        public Signal(int capacity) : base(capacity)\n        {\n        }\n\n        public Signal()\n        {\n        }\n    }\n\n    public class Signal<T1, T2> : SignalBase\n    {\n        public static Signal<T1, T2> operator +(Signal<T1, T2> p1, Action<T1, T2> p2)\n        {\n            p1.AddListener(p2, false);\n            return p1;\n        }\n\n        public static Signal<T1, T2> operator -(Signal<T1, T2> p1, Action<T1, T2> p2)\n        {\n            p1.RemoveListener(p2);\n            return p1;\n        }\n\n        public void AddListener(Action<T1, T2> a, bool bInsertAtFirst = false)\n        {\n            base.AddListener(a, bInsertAtFirst);\n        }\n\n        public void RemoveListener(Action<T1, T2> a)\n        {\n            base.RemoveListener(a);\n        }\n\n        public void Invoke(T1 t1, T2 t2)\n        {\n\n            int c = _methodCount;\n            var methods = _methods;\n            for (int i = 0; i < c; i++)\n            {\n                var item = methods[i];\n                if (item == null)\n                    continue;\n                var action = item as Action<T1, T2>;\n                action(t1, t2);\n            }\n\n            TryClean();\n        }\n\n        public void InvokeSafe(T1 t1, T2 t2)\n        {\n            try\n            {\n                int c = _methodCount;\n                var methods = _methods;\n                for (int i = 0; i < c; i++)\n                {\n                    var item = methods[i];\n                    if (item == null)\n                        continue;\n                    var action = item as Action<T1, T2>;\n                    action(t1, t2);\n                }\n\n                TryClean();\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(e);\n            }\n        }\n\n        public Signal(int capacity) : base(capacity)\n        {\n        }\n\n        public Signal()\n        {\n        }\n    }\n\n    public class Signal<T1, T2, T3> : SignalBase\n    {\n        public static Signal<T1, T2, T3> operator +(Signal<T1, T2, T3> p1, Action<T1, T2, T3> p2)\n        {\n            p1.AddListener(p2, false);\n            return p1;\n        }\n\n        public static Signal<T1, T2, T3> operator -(Signal<T1, T2, T3> p1, Action<T1, T2, T3> p2)\n        {\n            p1.RemoveListener(p2);\n            return p1;\n        }\n\n        public void AddListener(Action<T1, T2, T3> a, bool bInsertAtFirst = false)\n        {\n            base.AddListener(a, bInsertAtFirst);\n        }\n\n        public void RemoveListener(Action<T1, T2, T3> a)\n        {\n            base.RemoveListener(a);\n        }\n\n        public void Invoke(T1 t1, T2 t2, T3 t3)\n        {\n\n            int c = _methodCount;\n            var methods = _methods;\n            for (int i = 0; i < c; i++)\n            {\n                var item = methods[i];\n                if (item == null)\n                    continue;\n                var action = item as Action<T1, T2, T3>;\n                action(t1, t2, t3);\n            }\n\n            TryClean();\n\n        }\n\n        public void InvokeSafe(T1 t1, T2 t2, T3 t3)\n        {\n            try\n            {\n                int c = _methodCount;\n                var methods = _methods;\n                for (int i = 0; i < c; i++)\n                {\n                    var item = methods[i];\n                    if (item == null)\n                        continue;\n                    var action = item as Action<T1, T2, T3>;\n                    action(t1, t2, t3);\n                }\n\n                TryClean();\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(e);\n            }\n\n        }\n\n        public Signal(int capacity) : base(capacity)\n        {\n        }\n\n        public Signal()\n        {\n        }\n    }\n\n    public class Signal<T1, T2, T3, T4> : SignalBase\n    {\n        public static Signal<T1, T2, T3, T4> operator +(Signal<T1, T2, T3, T4> p1, Action<T1, T2, T3, T4> p2)\n        {\n            p1.AddListener(p2, false);\n            return p1;\n        }\n\n        public static Signal<T1, T2, T3, T4> operator -(Signal<T1, T2, T3, T4> p1, Action<T1, T2, T3, T4> p2)\n        {\n            p1.RemoveListener(p2);\n            return p1;\n        }\n\n        public void AddListener(Action<T1, T2, T3, T4> a, bool bInsertAtFirst = false)\n        {\n            base.AddListener(a, bInsertAtFirst);\n        }\n\n        public void RemoveListener(Action<T1, T2, T3, T4> a)\n        {\n            base.RemoveListener(a);\n        }\n\n        public void Invoke(T1 t1, T2 t2, T3 t3, T4 t4)\n        {\n\n            int c = _methodCount;\n            var methods = _methods;\n            for (int i = 0; i < c; i++)\n            {\n                var item = methods[i];\n                if (item == null)\n                    continue;\n                var action = item as Action<T1, T2, T3, T4>;\n                action(t1, t2, t3, t4);\n            }\n\n            TryClean();\n        }\n        public void InvokeSafe(T1 t1, T2 t2, T3 t3, T4 t4)\n        {\n            try\n            {\n                int c = _methodCount;\n                var methods = _methods;\n                for (int i = 0; i < c; i++)\n                {\n                    var item = methods[i];\n                    if (item == null)\n                        continue;\n                    var action = item as Action<T1, T2, T3, T4>;\n                    action(t1, t2, t3, t4);\n                }\n\n                TryClean();\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(e);\n            }\n        }\n\n        public Signal(int capacity) : base(capacity)\n        {\n        }\n\n        public Signal()\n        {\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Extension/CollectionExtensions.cs",
    "content": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace SGF.Extension\n{\n    public static class CollectionExtensions\n    {\n        private static Random m_Random = new Random();\n\n        /**\n            Returns all elements of the source which are of FilterType.\n        */\n        public static IEnumerable<TFilter> FilterByType<T, TFilter>(this IEnumerable<T> source)\n            where T : class\n            where TFilter : class, T\n        {\n            return source.Where(item => item as TFilter != null).Cast<TFilter>();\n        }\n\n\n        /// <summary>\n        /// ƳԪ\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"source\"></param>\n        /// <param name=\"match\"></param>\n        public static void RemoveAllBut<T>(this List<T> source, Predicate<T> match)\n        {\n            Predicate<T> nomatch = item => !match(item);\n\n            source.RemoveAll(nomatch);\n        }\n\n\n        /// <summary>\n        /// ǷΪ\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"collection\"></param>\n        /// <returns></returns>\n        public static bool IsEmpty<T>(this ICollection<T> collection)\n        {\n            return collection.Count == 0;\n        }\n\n\n        /// <summary>\n        /// ׷Ԫ\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"collection\"></param>\n        /// <param name=\"other\"></param>\n        public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> other)\n        {\n            if (other == null) //nothing to add\n            {\n                return;\n            }\n\n            foreach (var obj in other)\n            {\n                collection.Add(obj);\n            }\n        }\n\n\n\n\n        /// <summary>\n        /// лַ\n        /// ʽ{a, b, c}\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"source\"></param>\n        /// <returns></returns>\n        public static string ToListString<T>(this IEnumerable<T> source)\n        {\n            if (source == null)\n            {\n                return \"null\";\n            }\n\n            if (source.Count() == 0)\n            {\n                return \"[]\";\n            }\n\n            if (source.Count() == 1)\n            {\n                return \"[\" + source.First() + \"]\";\n            }\n\n            var s = \"\";\n\n            s += source.ButFirst().Aggregate(s, (res, x) => res + \", \" + x.ToListString());\n            s = \"[\" + source.First().ToListString() + s + \"]\";\n\n            return s;\n        }\n\n\n        /// <summary>\n        /// лַ\n        /// </summary>\n        /// <param name=\"obj\"></param>\n        /// <returns></returns>\n        private static string ToListString(this object obj)\n        {\n            if (obj == null)\n            {\n                return \"\";\n            }\n\n            if (obj is string)\n            {\n                return obj.ToString();\n            }\n\n            var objAsList = obj as IEnumerable;\n\n            return objAsList == null ? obj.ToString() : objAsList.Cast<object>().ToListString();\n        }\n\n        /**\n            Returns an enumerable of all elements of the given list\tbut the first,\n            keeping them in order.\n        */\n        public static IEnumerable<T> ButFirst<T>(this IEnumerable<T> source)\n        {\n            return source.Skip(1);\n        }\n\n        /**\n            Returns an enumarable of all elements in the given \n            list but the last, keeping them in order.\n        */\n        public static IEnumerable<T> ButLast<T>(this IEnumerable<T> source)\n        {\n            var lastX = default(T);\n            var first = true;\n\n            foreach (var x in source)\n            {\n                if (first)\n                {\n                    first = false;\n                }\n                else\n                {\n                    yield return lastX;\n                }\n\n                lastX = x;\n            }\n        }\n\n\n        /// <summary>\n        /// ݸķԪ\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"source\"></param>\n        /// <param name=\"score\"></param>\n        /// <returns></returns>\n        public static T MaxBy<T>(this IEnumerable<T> source, Func<T, IComparable> score)\n        {\n            return source.Aggregate((x, y) => score(x).CompareTo(score(y)) > 0 ? x : y);\n        }\n\n        /**\n            Finds the maximum element in the source as scored by the given function.\n        */\n        //public static s2 MinBy<s2>(this IEnumerable<s2> source, Func<s2, IComparable> score)\n        //{\n        //\treturn source.Aggregate((x, y) => score(x).CompareTo(score(y)) < 0 ? x : y);\n        //}\n\n        public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source,\n            Func<TSource, TKey> selector)\n        {\n            return source.MinBy(selector, Comparer<TKey>.Default);\n        }\n\n        public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source,\n            Func<TSource, TKey> selector, IComparer<TKey> comparer)\n        {\n            source.ThrowIfNull(\"source\");\n            selector.ThrowIfNull(\"selector\");\n            comparer.ThrowIfNull(\"comparer\");\n\n            using (IEnumerator<TSource> sourceIterator = source.GetEnumerator())\n            {\n                if (!sourceIterator.MoveNext())\n                {\n                    throw new InvalidOperationException(\"Sequence was empty\");\n                }\n\n                TSource min = sourceIterator.Current;\n                TKey minKey = selector(min);\n\n                while (sourceIterator.MoveNext())\n                {\n                    TSource candidate = sourceIterator.Current;\n                    TKey candidateProjected = selector(candidate);\n                    if (comparer.Compare(candidateProjected, minKey) < 0)\n                    {\n                        min = candidate;\n                        minKey = candidateProjected;\n                    }\n                }\n                return min;\n            }\n        }\n\n        public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source,\n            Func<TSource, TKey> selector)\n        {\n            return source.MaxBy(selector, Comparer<TKey>.Default);\n        }\n\n        public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source,\n            Func<TSource, TKey> selector, IComparer<TKey> comparer)\n        {\n            source.ThrowIfNull(\"source\");\n            selector.ThrowIfNull(\"selector\");\n            comparer.ThrowIfNull(\"comparer\");\n\n            using (IEnumerator<TSource> sourceIterator = source.GetEnumerator())\n            {\n                if (!sourceIterator.MoveNext())\n                {\n                    throw new InvalidOperationException(\"Sequence was empty\");\n                }\n\n                TSource max = sourceIterator.Current;\n                TKey maxKey = selector(max);\n\n                while (sourceIterator.MoveNext())\n                {\n                    TSource candidate = sourceIterator.Current;\n                    TKey candidateProjected = selector(candidate);\n\n                    if (comparer.Compare(candidateProjected, maxKey) > 0)\n                    {\n                        max = candidate;\n                        maxKey = candidateProjected;\n                    }\n                }\n\n                return max;\n            }\n        }\n\n\n        /**\n            Returns a enumerable with elements in order, but the first element is moved to the end.\n        */\n        //TODO consider changing left to something more universal\n        public static IEnumerable<T> RotateLeft<T>(this IEnumerable<T> source)\n        {\n            var enumeratedList = source as IList<T> ?? source.ToList();\n            return enumeratedList.ButFirst().Concat(enumeratedList.Take(1));\n        }\n\n        /**\n            Returns a enumerable with elements in order, but the last element is moved to the front.\n        */\n        public static IEnumerable<T> RotateRight<T>(this IEnumerable<T> source)\n        {\n            var enumeratedList = source as IList<T> ?? source.ToList();\n            yield return enumeratedList.Last();\n\n            foreach (var item in enumeratedList.ButLast())\n            {\n                yield return item;\n            }\n        }\n\n        /**\n            Returns a random element from the list.\n        */\n        public static T RandomItem<T>(this IEnumerable<T> source)\n        {\n            return source.SampleRandom(1).First();\n        }\n\n        /**\n            Returns a random sample from the list.\n        */\n        public static IEnumerable<T> SampleRandom<T>(this IEnumerable<T> source, int sampleCount)\n        {\n            if (source == null)\n            {\n                throw new ArgumentNullException(\"source\");\n            }\n\n            if (sampleCount < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"sampleCount\");\n            }\n\n            /* Reservoir sampling. */\n            var samples = new List<T>();\n\n            //Must be 1, otherwise we have to use Range(0, i + 1)\n            var i = 1;\n\n            foreach (var item in source)\n            {\n                if (i <= sampleCount)\n                {\n                    samples.Add(item);\n                }\n                else\n                {\n                    // Randomly replace elements in the reservoir with a decreasing probability.\n                    var r = m_Random.Next(0, i);\n\n                    if (r < sampleCount)\n                    {\n                        samples[r] = item;\n                    }\n                }\n\n                i++;\n            }\n\n            return samples;\n        }\n\n\n        /// <summary>\n        /// \n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"source\"></param>\n        public static void Shuffle<T>(this IList<T> source)\n        {\n            var n = source.Count;\n\n            while (n > 1)\n            {\n                n--;\n\n                var k = m_Random.Next(0, n + 1);\n                var value = source[k];\n                source[k] = source[n];\n                source[n] = value;\n            }\n        }\n\n\n        public static IEnumerable<T> TakeHalf<T>(this IEnumerable<T> source)\n        {\n            int count = source.Count();\n\n            return source.Take(count / 2);\n        }\n\n        /**\n            Find an element in a collection by binary searching. \n            This requires the collection to be sorted on the values returned by getSubElement\n            This will compare some derived property of the elements in the collection, rather than the elements\n            themselves.\n         */\n        public static int BinarySearch<TCollection, TElement>(this ICollection<TCollection> source, TElement value,\n            Func<TCollection, TElement> getSubElement)\n        {\n            return BinarySearch(source, value, getSubElement, 0, source.Count, null);\n        }\n\n        /**\n            Find an element in a collection by binary searching. \n            This requires the collection to be sorted on the values returned by getSubElement\n            This will compare some derived property of the elements in the collection, rather than the elements\n            themselves.\n         */\n        public static int BinarySearch<TCollection, TElement>(this ICollection<TCollection> source, TElement value,\n            Func<TCollection, TElement> getSubElement, IComparer<TElement> comparer)\n        {\n            return BinarySearch(source, value, getSubElement, 0, source.Count, comparer);\n        }\n\n        /**\n            Find an element in a collection by binary searching. \n            This requires the collection to be sorted on the values returned by getSubElement\n            This will compare some derived property of the elements in the collection, rather than the elements\n            themselves.\n         */\n        public static int BinarySearch<TCollection, TElement>(this ICollection<TCollection> source, TElement value,\n            Func<TCollection, TElement> getSubElement, int index, int length)\n        {\n            return BinarySearch(source, value, getSubElement, index, length, null);\n        }\n\n        /**\n            Find an element in a collection by binary searching. \n            This requires the collection to be sorted on the values returned by getSubElement\n            This will compare some derived property of the elements in the collection, rather than the elements\n            themselves.\n         */\n        public static int BinarySearch<TCollection, TElement>(this ICollection<TCollection> source, TElement value,\n            Func<TCollection, TElement> getSubElement, int index, int length, IComparer<TElement> comparer)\n        {\n            if (index < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"index\",\n                    \"index is less than the lower bound of array.\");\n            }\n\n            if (length < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"length\",\n                    \"Value has to be >= 0.\");\n            }\n\n            // re-ordered to avoid possible integer overflow\n            if (index > source.Count - length)\n            {\n                throw new ArgumentException(\n                    \"index and length do not specify a valid range in array.\");\n            }\n            if (comparer == null)\n            {\n                comparer = Comparer<TElement>.Default;\n            }\n\n            int min = index;\n            int max = index + length - 1;\n            int cmp;\n            int mid;\n\n            while (min <= max)\n            {\n                mid = (min + ((max - min) >> 1));\n\n                cmp = comparer.Compare(\n                    getSubElement(source.ElementAt(mid)), value);\n\n                if (cmp == 0) return mid;\n\n                if (cmp > 0)\n                {\n                    max = mid - 1;\n                }\n                else\n                {\n                    min = mid + 1;\n                }\n            }\n\n            return ~min;\n        }\n\n        public static bool AreSequencesEqual<T>(IEnumerable<T> s1, IEnumerable<T> s2)\n            where T : IComparable\n        {\n            ObjectExtensions.ThrowIfNull(s1, \"s1\");\n            ObjectExtensions.ThrowIfNull(s2, \"s2\");\n\n            var list1 = s1.ToList();\n            var list2 = s2.ToList();\n\n            if (list1.Count != list2.Count) return false;\n\n            for (int i = 0; i < list1.Count; i++)\n            {\n                if (list1[i].CompareTo(list2[i]) != 0) return false;\n            }\n\n            return true;\n        }\n\n        public static string SequenceToString(this IEnumerable<string> sequence)\n        {\n            if (sequence == null) return \"null\";\n            if (!sequence.Any()) return \"\";\n\n            return sequence.Aggregate((x, y) => x + y);\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Extension/ObjectExtensions.cs",
    "content": "﻿using System;\nusing System.Collections;\nusing System.Text;\n\nnamespace SGF.Extension\n{\n    public static class ObjectExtensions\n    {\n        /// <summary>\n        /// 对象如果为Null，抛出异常\n        /// </summary>\n        /// <param name=\"o\"></param>\n        /// <param name=\"message\">异常消息</param>\n        public static void ThrowIfNull(this object o, string message)\n        {\n            if (o == null) throw new NullReferenceException(message);\n        }\n\n\n\n    }\n\n}"
  },
  {
    "path": "SGFCore/Extension/StreamExtension.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System.IO;\n\nnamespace SGF.Extension\n{\n    public static class StreamExtension\n    {\n        public static long CopyTo(this Stream source, Stream destination)\n        {\n            byte[] buffer = new byte[2048];\n            int bytesRead;\n            long totalBytes = 0;\n            while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)\n            {\n                destination.Write(buffer, 0, bytesRead);\n                totalBytes += bytesRead;\n            }\n            return totalBytes;\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Extension/StringExtensions.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 提供String的扩展方法\n * Provide String extension method\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\n\nnamespace SGF.Extension\n{\n    public static class StringExtensions\n    {\n        public static int ToInt(this string target, int defaultValue = 0)\n        {\n            int.TryParse(target, out defaultValue);\n            return defaultValue;\n        }\n\n        public static uint ToUInt(this string target, uint defaultValue = 0)\n        {\n            uint.TryParse(target, out defaultValue);\n            return defaultValue;\n        }\n\n        public static long ToLong(this string target, long defaultValue = 0)\n        {\n            long.TryParse(target, out defaultValue);\n            return defaultValue;\n        }\n\n        public static ulong ToULong(this string target, ulong defaultValue = 0)\n        {\n            ulong.TryParse(target, out defaultValue);\n            return defaultValue;\n        }\n\n        public static double ToDouble(this string target, double defaultValue = 0)\n        {\n            double.TryParse(target, out defaultValue);\n            return defaultValue;\n        }\n\n        public static float ToFloat(this string target, float defaultValue = 0)\n        {\n            float.TryParse(target, out defaultValue);\n            return defaultValue;\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/G3Lite/IndexTypes.cs",
    "content": "﻿using System;\n\nnamespace SGF.G3Lite\n{\n\n    public struct Index3 : IComparable<Index3>, IEquatable<Index3>\n    {\n        public int a;\n        public int b;\n        public int c;\n\n        public Index3(int z) { a = b = c = z; }\n        public Index3(int ii, int jj, int kk) { a = ii; b = jj; c = kk; }\n        public Index3(int[] i2) { a = i2[0]; b = i2[1]; c = i2[2]; }\n        public Index3(Index3 copy) { a = copy.a; b = copy.b; c = copy.b; }\n\n        // reverse last two indices if cycle is true (useful for cw/ccw codes)\n        public Index3(int ii, int jj, int kk, bool cycle)\n        {\n            a = ii;\n            if (cycle) { b = kk; c = jj; }\n            else { b = jj; c = kk; }\n        }\n\n        static public readonly Index3 Zero = new Index3(0, 0, 0);\n        static public readonly Index3 One = new Index3(1, 1, 1);\n        static public readonly Index3 Max = new Index3(int.MaxValue, int.MaxValue, int.MaxValue);\n        static public readonly Index3 Min = new Index3(int.MinValue, int.MinValue, int.MinValue);\n\n\n        public int this[int key]\n        {\n            get { return (key == 0) ? a : (key == 1) ? b : c; }\n            set { if (key == 0) a = value; else if (key == 1) b = value; else c = value; }\n        }\n\n        public int[] array\n        {\n            get { return new int[] { a, b, c }; }\n        }\n\n\n        public int LengthSquared\n        {\n            get { return a * a + b * b + c * c; }\n        }\n        public int Length\n        {\n            get { return (int)Math.Sqrt(LengthSquared); }\n        }\n\n\n        public void Set(Index3 o)\n        {\n            a = o[0]; b = o[1]; c = o[2];\n        }\n        public void Set(int ii, int jj, int kk)\n        {\n            a = ii; b = jj; c = kk;\n        }\n\n\n        public static Index3 operator -(Index3 v)\n        {\n            return new Index3(-v.a, -v.b, -v.c);\n        }\n\n        public static Index3 operator *(int f, Index3 v)\n        {\n            return new Index3(f * v.a, f * v.b, f * v.c);\n        }\n        public static Index3 operator *(Index3 v, int f)\n        {\n            return new Index3(f * v.a, f * v.b, f * v.c);\n        }\n        public static Index3 operator /(Index3 v, int f)\n        {\n            return new Index3(v.a / f, v.b / f, v.c / f);\n        }\n\n\n        public static Index3 operator *(Index3 a, Index3 b)\n        {\n            return new Index3(a.a * b.a, a.b * b.b, a.c * b.c);\n        }\n        public static Index3 operator /(Index3 a, Index3 b)\n        {\n            return new Index3(a.a / b.a, a.b / b.b, a.c / b.c);\n        }\n\n\n        public static Index3 operator +(Index3 v0, Index3 v1)\n        {\n            return new Index3(v0.a + v1.a, v0.b + v1.b, v0.c + v1.c);\n        }\n        public static Index3 operator +(Index3 v0, int f)\n        {\n            return new Index3(v0.a + f, v0.b + f, v0.c + f);\n        }\n\n        public static Index3 operator -(Index3 v0, Index3 v1)\n        {\n            return new Index3(v0.a - v1.a, v0.b - v1.b, v0.c - v1.c);\n        }\n        public static Index3 operator -(Index3 v0, int f)\n        {\n            return new Index3(v0.a - f, v0.b - f, v0.c - f);\n        }\n\n\n        public static bool operator ==(Index3 a, Index3 b)\n        {\n            return (a.a == b.a && a.b == b.b && a.c == b.c);\n        }\n        public static bool operator !=(Index3 a, Index3 b)\n        {\n            return (a.a != b.a || a.b != b.b || a.c != b.c);\n        }\n        public override bool Equals(object obj)\n        {\n            return this == (Index3)obj;\n        }\n        public override int GetHashCode()\n        {\n            unchecked // Overflow is fine, just wrap\n            {\n                int hash = (int)2166136261;\n                // Suitable nullity checks etc, of course :)\n                hash = (hash * 16777619) ^ a.GetHashCode();\n                hash = (hash * 16777619) ^ b.GetHashCode();\n                hash = (hash * 16777619) ^ c.GetHashCode();\n                return hash;\n            }\n        }\n        public int CompareTo(Index3 other)\n        {\n            if (a != other.a)\n                return a < other.a ? -1 : 1;\n            else if (b != other.b)\n                return b < other.b ? -1 : 1;\n            else if (c != other.c)\n                return c < other.c ? -1 : 1;\n            return 0;\n        }\n        public bool Equals(Index3 other)\n        {\n            return (a == other.a && b == other.b && c == other.c);\n        }\n\n\n        public override string ToString()\n        {\n            return string.Format(\"[{0},{1},{2}]\", a, b, c);\n        }\n\n    }\n\n\n\n\n\n\n\n\n\n\n\n\n    public struct Index2 : IComparable<Index2>, IEquatable<Index2>\n    {\n        public int a;\n        public int b;\n\n        public Index2(int z) { a = b = z; }\n        public Index2(int ii, int jj) { a = ii; b = jj; }\n        public Index2(int[] i2) { a = i2[0]; b = i2[1]; }\n        public Index2(Index2 copy) { a = copy.a; b = copy.b; }\n\n        static public readonly Index2 Zero = new Index2(0, 0);\n        static public readonly Index2 One = new Index2(1, 1);\n        static public readonly Index2 Max = new Index2(int.MaxValue, int.MaxValue);\n        static public readonly Index2 Min = new Index2(int.MinValue, int.MinValue);\n\n\n        public int this[int key]\n        {\n            get { return (key == 0) ? a : b; }\n            set { if (key == 0) a = value; else b = value; }\n        }\n\n        public int[] array\n        {\n            get { return new int[] { a, b }; }\n        }\n\n\n        public int LengthSquared\n        {\n            get { return a * a + b * b; }\n        }\n        public int Length\n        {\n            get { return (int)Math.Sqrt(LengthSquared); }\n        }\n\n\n        public void Set(Index2 o)\n        {\n            a = o[0]; b = o[1];\n        }\n        public void Set(int ii, int jj)\n        {\n            a = ii; b = jj;\n        }\n\n\n        public static Index2 operator -(Index2 v)\n        {\n            return new Index2(-v.a, -v.b);\n        }\n\n        public static Index2 operator *(int f, Index2 v)\n        {\n            return new Index2(f * v.a, f * v.b);\n        }\n        public static Index2 operator *(Index2 v, int f)\n        {\n            return new Index2(f * v.a, f * v.b);\n        }\n        public static Index2 operator /(Index2 v, int f)\n        {\n            return new Index2(v.a / f, v.b / f);\n        }\n\n\n        public static Index2 operator *(Index2 a, Index2 b)\n        {\n            return new Index2(a.a * b.a, a.b * b.b);\n        }\n        public static Index2 operator /(Index2 a, Index2 b)\n        {\n            return new Index2(a.a / b.a, a.b / b.b);\n        }\n\n\n        public static Index2 operator +(Index2 v0, Index2 v1)\n        {\n            return new Index2(v0.a + v1.a, v0.b + v1.b);\n        }\n        public static Index2 operator +(Index2 v0, int f)\n        {\n            return new Index2(v0.a + f, v0.b + f);\n        }\n\n        public static Index2 operator -(Index2 v0, Index2 v1)\n        {\n            return new Index2(v0.a - v1.a, v0.b - v1.b);\n        }\n        public static Index2 operator -(Index2 v0, int f)\n        {\n            return new Index2(v0.a - f, v0.b - f);\n        }\n\n\n        public static bool operator ==(Index2 a, Index2 b)\n        {\n            return (a.a == b.a && a.b == b.b);\n        }\n        public static bool operator !=(Index2 a, Index2 b)\n        {\n            return (a.a != b.a || a.b != b.b);\n        }\n        public override bool Equals(object obj)\n        {\n            return this == (Index2)obj;\n        }\n        public override int GetHashCode()\n        {\n            unchecked // Overflow is fine, just wrap\n            {\n                int hash = (int)2166136261;\n                // Suitable nullity checks etc, of course :)\n                hash = (hash * 16777619) ^ a.GetHashCode();\n                hash = (hash * 16777619) ^ b.GetHashCode();\n                return hash;\n            }\n        }\n        public int CompareTo(Index2 other)\n        {\n            if (a != other.a)\n                return a < other.a ? -1 : 1;\n            else if (b != other.b)\n                return b < other.b ? -1 : 1;\n            return 0;\n        }\n        public bool Equals(Index2 other)\n        {\n            return (a == other.a && b == other.b);\n        }\n\n\n        public override string ToString()\n        {\n            return string.Format(\"[{0},{1}]\", a, b);\n        }\n\n    }\n\n\n\n\n\n\n\n\n\n    public struct Index4\n    {\n        public int a;\n        public int b;\n        public int c;\n        public int d;\n\n        public Index4(int z) { a = b = c = d = z; }\n        public Index4(int aa, int bb, int cc, int dd) { a = aa; b = bb; c = cc; d = dd; }\n        public Index4(int[] i2) { a = i2[0]; b = i2[1]; c = i2[2]; d = i2[3]; }\n        public Index4(Index4 copy) { a = copy.a; b = copy.b; c = copy.b; d = copy.d; }\n\n        static public readonly Index4 Zero = new Index4(0, 0, 0, 0);\n        static public readonly Index4 One = new Index4(1, 1, 1, 1);\n        static public readonly Index4 Max = new Index4(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue);\n\n\n        public int this[int key]\n        {\n            get { return (key == 0) ? a : (key == 1) ? b : (key == 2) ? c : d; }\n            set { if (key == 0) a = value; else if (key == 1) b = value; else if (key == 2) c = value; else d = value; }\n        }\n\n        public int[] array\n        {\n            get { return new int[4] { a, b, c, d }; }\n        }\n\n\n        public int LengthSquared\n        {\n            get { return a * a + b * b + c * c + d * d; }\n        }\n        public int Length\n        {\n            get { return (int)Math.Sqrt(LengthSquared); }\n        }\n\n\n        public void Set(Index4 o)\n        {\n            a = o[0]; b = o[1]; c = o[2]; d = o[3];\n        }\n        public void Set(int aa, int bb, int cc, int dd)\n        {\n            a = aa; b = bb; c = cc; d = dd;\n        }\n\n\n        public bool Contains(int val)\n        {\n            return a == val || b == val || c == val || d == val;\n        }\n\n        public void Sort()\n        {\n            int tmp;   // if we use 2 temp ints, we can swap in a different order where some test pairs\n                       // could be done simultaneously, but no idea if compiler would optimize that anyway...\n            if (d < c) { tmp = d; d = c; c = tmp; }\n            if (c < b) { tmp = c; c = b; b = tmp; }\n            if (b < a) { tmp = b; b = a; a = tmp; }   // now a is smallest value\n            if (b > c) { tmp = c; c = b; b = tmp; }\n            if (c > d) { tmp = d; d = c; c = tmp; }   // now d is largest value\n            if (b > c) { tmp = c; c = b; b = tmp; }   // bow b,c are sorted\n        }\n\n\n        public static Index4 operator -(Index4 v)\n        {\n            return new Index4(-v.a, -v.b, -v.c, -v.d);\n        }\n\n        public static Index4 operator *(int f, Index4 v)\n        {\n            return new Index4(f * v.a, f * v.b, f * v.c, f * v.d);\n        }\n        public static Index4 operator *(Index4 v, int f)\n        {\n            return new Index4(f * v.a, f * v.b, f * v.c, f * v.d);\n        }\n        public static Index4 operator /(Index4 v, int f)\n        {\n            return new Index4(v.a / f, v.b / f, v.c / f, v.d / f);\n        }\n\n\n        public static Index4 operator *(Index4 a, Index4 b)\n        {\n            return new Index4(a.a * b.a, a.b * b.b, a.c * b.c, a.d * b.d);\n        }\n        public static Index4 operator /(Index4 a, Index4 b)\n        {\n            return new Index4(a.a / b.a, a.b / b.b, a.c / b.c, a.d / b.d);\n        }\n\n\n        public static Index4 operator +(Index4 v0, Index4 v1)\n        {\n            return new Index4(v0.a + v1.a, v0.b + v1.b, v0.c + v1.c, v0.d + v1.d);\n        }\n        public static Index4 operator +(Index4 v0, int f)\n        {\n            return new Index4(v0.a + f, v0.b + f, v0.c + f, v0.d + f);\n        }\n\n        public static Index4 operator -(Index4 v0, Index4 v1)\n        {\n            return new Index4(v0.a - v1.a, v0.b - v1.b, v0.c - v1.c, v0.d - v1.d);\n        }\n        public static Index4 operator -(Index4 v0, int f)\n        {\n            return new Index4(v0.a - f, v0.b - f, v0.c - f, v0.d - f);\n        }\n\n\n        public static bool operator ==(Index4 a, Index4 b)\n        {\n            return (a.a == b.a && a.b == b.b && a.c == b.c && a.d == b.d);\n        }\n        public static bool operator !=(Index4 a, Index4 b)\n        {\n            return (a.a != b.a || a.b != b.b || a.c != b.c || a.d != b.d);\n        }\n        public override bool Equals(object obj)\n        {\n            return this == (Index4)obj;\n        }\n        public override int GetHashCode()\n        {\n            unchecked // Overflow is fine, just wrap\n            {\n                int hash = (int)2166136261;\n                // Suitable nullity checks etc, of course :)\n                hash = (hash * 16777619) ^ a.GetHashCode();\n                hash = (hash * 16777619) ^ b.GetHashCode();\n                hash = (hash * 16777619) ^ c.GetHashCode();\n                hash = (hash * 16777619) ^ d.GetHashCode();\n                return hash;\n            }\n        }\n        public int CompareTo(Index4 other)\n        {\n            if (a != other.a)\n                return a < other.a ? -1 : 1;\n            else if (b != other.b)\n                return b < other.b ? -1 : 1;\n            else if (c != other.c)\n                return c < other.c ? -1 : 1;\n            else if (d != other.d)\n                return d < other.d ? -1 : 1;\n            return 0;\n        }\n        public bool Equals(Index4 other)\n        {\n            return (a == other.a && b == other.b && c == other.c && d == other.d);\n        }\n\n\n\n        public override string ToString()\n        {\n            return string.Format(\"[{0},{1},{2},{3}]\", a, b, c, d);\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/G3Lite/MathUtil.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\n\n\nnamespace SGF.G3Lite\n{\n    public static class MathUtil\n    {\n        public const double Deg2Rad = (Math.PI / 180.0);\n        public const double Rad2Deg = (180.0 / Math.PI);\n        public const double TwoPI = 2.0 * Math.PI;\n        public const double FourPI = 4.0 * Math.PI;\n        public const double HalfPI = 0.5 * Math.PI;\n        public const double ZeroTolerance = 1e-08;\n        public const double Epsilon = 2.2204460492503131e-016;\n        public const double SqrtTwo = 1.41421356237309504880168872420969807;\n        public const double SqrtTwoInv = 1.0 / SqrtTwo;\n        public const double SqrtThree = 1.73205080756887729352744634150587236;\n\n        public const float Deg2Radf = (float)(Math.PI / 180.0);\n        public const float Rad2Degf = (float)(180.0 / Math.PI);\n        public const float PIf = (float)(Math.PI);\n        public const float TwoPIf = 2.0f * PIf;\n        public const float HalfPIf = 0.5f * PIf;\n        public const float SqrtTwof = 1.41421356237f;\n\n        public const float ZeroTolerancef = 1e-06f;\n        public const float Epsilonf = 1.192092896e-07F;\n\n\n        public static bool IsFinite(double d)\n        {\n            return double.IsInfinity(d) == false && double.IsNaN(d) == false;\n        }\n        public static bool IsFinite(float d)\n        {\n            return float.IsInfinity(d) == false && float.IsNaN(d) == false;\n        }\n\n\n        public static bool EpsilonEqual(double a, double b, double epsilon = MathUtil.Epsilon)\n        {\n            return Math.Abs(a - b) <= epsilon;\n        }\n        public static bool EpsilonEqual(float a, float b, float epsilon = MathUtil.Epsilonf)\n        {\n            return (float)Math.Abs(a - b) <= epsilon;\n        }\n\n        // ugh C# generics so limiting...\n        public static T Clamp<T>(T f, T low, T high) where T : IComparable\n        {\n            if (f.CompareTo(low) < 0) return low;\n            else if (f.CompareTo(high) > 0) return high;\n            else return f;\n        }\n        public static float Clamp(float f, float low, float high)\n        {\n            return (f < low) ? low : (f > high) ? high : f;\n        }\n        public static double Clamp(double f, double low, double high)\n        {\n            return (f < low) ? low : (f > high) ? high : f;\n        }\n        public static int Clamp(int f, int low, int high)\n        {\n            return (f < low) ? low : (f > high) ? high : f;\n        }\n\n        public static int ModuloClamp(int f, int N)\n        {\n            while (f < 0)\n                f += N;\n            return f % N;\n        }\n\n        // fMinMaxValue may be signed\n        public static float RangeClamp(float fValue, float fMinMaxValue)\n        {\n            return Clamp(fValue, -Math.Abs(fMinMaxValue), Math.Abs(fMinMaxValue));\n        }\n        public static double RangeClamp(double fValue, double fMinMaxValue)\n        {\n            return Clamp(fValue, -Math.Abs(fMinMaxValue), Math.Abs(fMinMaxValue));\n        }\n\n\n        public static float SignedClamp(float f, float fMax)\n        {\n            return Clamp(Math.Abs(f), 0, fMax) * Math.Sign(f);\n        }\n        public static double SignedClamp(double f, double fMax)\n        {\n            return Clamp(Math.Abs(f), 0, fMax) * Math.Sign(f);\n        }\n\n        public static float SignedClamp(float f, float fMin, float fMax)\n        {\n            return Clamp(Math.Abs(f), fMin, fMax) * Math.Sign(f);\n        }\n        public static double SignedClamp(double f, double fMin, double fMax)\n        {\n            return Clamp(Math.Abs(f), fMin, fMax) * Math.Sign(f);\n        }\n\n\n        public static bool InRange(float f, float low, float high)\n        {\n            return f >= low && f <= high;\n        }\n        public static bool InRange(double f, double low, double high)\n        {\n            return f >= low && f <= high;\n        }\n        public static bool InRange(int f, int low, int high)\n        {\n            return f >= low && f <= high;\n        }\n\n\n        // clamps theta to angle interval [min,max]. should work for any theta,\n        // regardless of cycles, however min & max values should be in range\n        // [-360,360] and min < max\n        public static double ClampAngleDeg(double theta, double min, double max)\n        {\n            // convert interval to center/extent - [c-e,c+e]\n            double c = (min + max) * 0.5;\n            double e = max - c;\n\n            // get rid of extra rotations\n            theta = theta % 360;\n\n            // shift to origin, then convert theta to +- 180\n            theta -= c;\n            if (theta < -180)\n                theta += 360;\n            else if (theta > 180)\n                theta -= 360;\n\n            // clamp to extent\n            if (theta < -e)\n                theta = -e;\n            else if (theta > e)\n                theta = e;\n\n            // shift back\n            return theta + c;\n        }\n\n\n\n        // clamps theta to angle interval [min,max]. should work for any theta,\n        // regardless of cycles, however min & max values should be in range\n        // [-2_PI,2_PI] and min < max\n        public static double ClampAngleRad(double theta, double min, double max)\n        {\n            // convert interval to center/extent - [c-e,c+e]\n            double c = (min + max) * 0.5;\n            double e = max - c;\n\n            // get rid of extra rotations\n            theta = theta % TwoPI;\n\n            // shift to origin, then convert theta to +- 180\n            theta -= c;\n            if (theta < -Math.PI)\n                theta += TwoPI;\n            else if (theta > Math.PI)\n                theta -= TwoPI;\n\n            // clamp to extent\n            if (theta < -e)\n                theta = -e;\n            else if (theta > e)\n                theta = e;\n\n            // shift back\n            return theta + c;\n        }\n\n\n\n        // for ((i++) % N)-type loops, but where we might be using (i--)\n        public static int WrapSignedIndex(int val, int mod)\n        {\n            while (val < 0)\n                val += mod;\n            return val % mod;\n        }\n\n\n        // compute min and max of a,b,c with max 3 comparisons (sometimes 2)\n        public static void MinMax(double a, double b, double c, out double min, out double max)\n        {\n            if (a < b)\n            {\n                if (a < c)\n                {\n                    min = a; max = Math.Max(b, c);\n                }\n                else\n                {\n                    min = c; max = b;\n                }\n            }\n            else\n            {\n                if (a > c)\n                {\n                    max = a; min = Math.Min(b, c);\n                }\n                else\n                {\n                    min = b; max = c;\n                }\n            }\n        }\n\n\n        public static double Min(double a, double b, double c)\n        {\n            return Math.Min(a, Math.Min(b, c));\n        }\n        public static float Min(float a, float b, float c)\n        {\n            return Math.Min(a, Math.Min(b, c));\n        }\n        public static int Min(int a, int b, int c)\n        {\n            return Math.Min(a, Math.Min(b, c));\n        }\n        public static double Max(double a, double b, double c)\n        {\n            return Math.Max(a, Math.Max(b, c));\n        }\n        public static float Max(float a, float b, float c)\n        {\n            return Math.Max(a, Math.Max(b, c));\n        }\n        public static int Max(int a, int b, int c)\n        {\n            return Math.Max(a, Math.Max(b, c));\n        }\n\n\n\n        // there are fast approximations to this...\n        public static double InvSqrt(double f)\n        {\n            return f / Math.Sqrt(f);\n        }\n\n\n        // normal Atan2 returns in range [-pi,pi], this shifts to [0,2pi]\n        public static double Atan2Positive(double y, double x)\n        {\n            double theta = Math.Atan2(y, x);\n            if (theta < 0)\n                theta = (2 * Math.PI) + theta;\n            return theta;\n        }\n\n\n        public static float PlaneAngleD(Vector3 a, Vector3 b, int nPlaneNormalIdx = 1)\n        {\n            a[nPlaneNormalIdx] = b[nPlaneNormalIdx] = 0.0f;\n            a.Normalize();\n            b.Normalize();\n            return Vector3.AngleD(a, b);\n        }\n\n\n\n        public static float PlaneAngleSignedD(Vector3 vFrom, Vector3 vTo, int nPlaneNormalIdx = 1)\n        {\n            vFrom[nPlaneNormalIdx] = vTo[nPlaneNormalIdx] = 0.0f;\n            vFrom.Normalize();\n            vTo.Normalize();\n            Vector3 c = vFrom.Cross(vTo);\n            if (c.sqrMagnitude < MathUtil.ZeroTolerancef)\n            {        // vectors are parallel\n                return vFrom.Dot(vTo) < 0 ? 180.0f : 0;\n            }\n            float fSign = Math.Sign(c[nPlaneNormalIdx]);\n            float fAngle = fSign * Vector3.AngleD(vFrom, vTo);\n            return fAngle;\n        }\n\n\n        public static float PlaneAngleSignedD(Vector3 vFrom, Vector3 vTo, Vector3 planeN)\n        {\n            vFrom = vFrom - Vector3.Dot(vFrom, planeN) * planeN;\n            vTo = vTo - Vector3.Dot(vTo, planeN) * planeN;\n            vFrom.Normalize();\n            vTo.Normalize();\n            Vector3 c = Vector3.Cross(vFrom, vTo);\n            if (c.sqrMagnitude < MathUtil.ZeroTolerancef)\n            {        // vectors are parallel\n                return vFrom.Dot(vTo) < 0 ? 180.0f : 0;\n            }\n            float fSign = Math.Sign(Vector3.Dot(c, planeN));\n            float fAngle = fSign * Vector3.AngleD(vFrom, vTo);\n            return fAngle;\n        }\n\n\n\n        public static float PlaneAngleSignedD(Vector2 vFrom, Vector2 vTo)\n        {\n            vFrom.Normalize();\n            vTo.Normalize();\n            float fSign = Math.Sign(vFrom.Cross(vTo));\n            float fAngle = fSign * Vector2.AngleD(vFrom, vTo);\n            return fAngle;\n        }\n\n\n\n\n\n        public static float Lerp(float a, float b, float t)\n        {\n            return (1.0f - t) * a + (t) * b;\n        }\n        public static double Lerp(double a, double b, double t)\n        {\n            return (1.0 - t) * a + (t) * b;\n        }\n\n        public static float SmoothStep(float a, float b, float t)\n        {\n            t = t * t * (3.0f - 2.0f * t);\n            return (1.0f - t) * a + (t) * b;\n        }\n        public static double SmoothStep(double a, double b, double t)\n        {\n            t = t * t * (3.0 - 2.0 * t);\n            return (1.0 - t) * a + (t) * b;\n        }\n\n\n        public static float SmoothInterp(float a, float b, float t)\n        {\n            float tt = WyvillRise01(t);\n            return (1.0f - tt) * a + (tt) * b;\n        }\n        public static double SmoothInterp(double a, double b, double t)\n        {\n            double tt = WyvillRise01(t);\n            return (1.0 - tt) * a + (tt) * b;\n        }\n\n        //! if yshift is 0, function approaches y=1 at xZero from y=0. \n        //! speed (> 0) controls how fast it gets there\n        //! yshift pushes the whole graph upwards (so that it actually crosses y=1 at some point)\n        public static float SmoothRise0To1(float fX, float yshift, float xZero, float speed)\n        {\n            double denom = Math.Pow((fX - (xZero - 1)), speed);\n            float fY = (float)((1 + yshift) + (1 / -denom));\n            return Clamp(fY, 0, 1);\n        }\n\n        public static float WyvillRise01(float fX)\n        {\n            float d = MathUtil.Clamp(1.0f - fX * fX, 0.0f, 1.0f);\n            return 1 - (d * d * d);\n        }\n        public static double WyvillRise01(double fX)\n        {\n            double d = MathUtil.Clamp(1.0 - fX * fX, 0.0, 1.0);\n            return 1 - (d * d * d);\n        }\n\n        public static float WyvillFalloff01(float fX)\n        {\n            float d = 1 - fX * fX;\n            return (d >= 0) ? (d * d * d) : 0;\n        }\n        public static double WyvillFalloff01(double fX)\n        {\n            double d = 1 - fX * fX;\n            return (d >= 0) ? (d * d * d) : 0;\n        }\n\n\n        public static float WyvillFalloff(float fD, float fInnerRad, float fOuterRad)\n        {\n            if (fD > fOuterRad)\n            {\n                return 0;\n            }\n            else if (fD > fInnerRad)\n            {\n                fD -= fInnerRad;\n                fD /= (fOuterRad - fInnerRad);\n                fD = Math.Max(0, Math.Min(1, fD));\n                float fVal = (1.0f - fD * fD);\n                return fVal * fVal * fVal;\n            }\n            else\n                return 1.0f;\n        }\n        public static double WyvillFalloff(double fD, double fInnerRad, double fOuterRad)\n        {\n            if (fD > fOuterRad)\n            {\n                return 0;\n            }\n            else if (fD > fInnerRad)\n            {\n                fD -= fInnerRad;\n                fD /= (fOuterRad - fInnerRad);\n                fD = Math.Max(0, Math.Min(1, fD));\n                double fVal = (1.0f - fD * fD);\n                return fVal * fVal * fVal;\n            }\n            else\n                return 1.0;\n        }\n\n\n\n        // lerps from [0,1] for x in range [deadzone,R]\n        public static float LinearRampT(float R, float deadzoneR, float x)\n        {\n            float sign = Math.Sign(x);\n            x = Math.Abs(x);\n            if (x < deadzoneR)\n                return 0.0f;\n            else if (x > R)\n                return sign * 1.0f;\n            else\n            {\n                x = Math.Min(x, R);\n                float d = (x - deadzoneR) / (R - deadzoneR);\n                return sign * d;\n            }\n        }\n\n\n        public static bool SolveQuadratic(double a, double b, double c, out double minT, out double maxT)\n        {\n            minT = maxT = 0;\n            if (a == 0 && b == 0)   // function is constant...\n                return true;\n\n            double discrim = b * b - 4.0 * a * c;\n            if (discrim < 0)\n                return false;    // no solution\n\n            // a bit odd but numerically better (says NRIC)\n            double t = -0.5 * (b + Math.Sign(b) * Math.Sqrt(discrim));\n            minT = t / a;\n            maxT = c / t;\n            if (minT > maxT)\n            {\n                a = minT; minT = maxT; maxT = a;   // swap\n            }\n\n            return true;\n        }\n\n\n\n\n        static readonly int[] powers_of_10 = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };\n        public static int PowerOf10(int n)\n        {\n            return powers_of_10[n];\n        }\n\n\n        /// <summary>\n        /// Iterate from 0 to (nMax-1) using prime-modulo, so we see every index once, but not in-order\n        /// </summary>\n        public static IEnumerable<int> ModuloIteration(int nMaxExclusive, int nPrime = 31337)\n        {\n            int i = 0;\n            bool done = false;\n            while (done == false)\n            {\n                yield return i;\n                i = (i + nPrime) % nMaxExclusive;\n                done = (i == 0);\n            }\n        }\n\n\n\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/G3Lite/Matrix3.cs",
    "content": "﻿using System;\n\nnamespace SGF.G3Lite\n{\n    public struct Matrix3\n    {\n        public Vector3 Row0;\n        public Vector3 Row1;\n        public Vector3 Row2;\n\n        public Matrix3(bool bIdentity)\n        {\n            if (bIdentity)\n            {\n                Row0 = Vector3.AxisX; Row1 = Vector3.AxisY; Row2 = Vector3.AxisZ;\n            }\n            else\n            {\n                Row0 = Row1 = Row2 = Vector3.zero;\n            }\n        }\n\n        // assumes input is row-major...\n        public Matrix3(float[,] mat)\n        {\n            Row0 = new Vector3(mat[0, 0], mat[0, 1], mat[0, 2]);\n            Row1 = new Vector3(mat[1, 0], mat[1, 1], mat[1, 2]);\n            Row2 = new Vector3(mat[2, 0], mat[2, 1], mat[2, 2]);\n        }\n        public Matrix3(float[] mat)\n        {\n            Row0 = new Vector3(mat[0], mat[1], mat[2]);\n            Row1 = new Vector3(mat[3], mat[4], mat[5]);\n            Row2 = new Vector3(mat[6], mat[7], mat[8]);\n        }\n        public Matrix3(double[,] mat)\n        {\n            Row0 = new Vector3(mat[0, 0], mat[0, 1], mat[0, 2]);\n            Row1 = new Vector3(mat[1, 0], mat[1, 1], mat[1, 2]);\n            Row2 = new Vector3(mat[2, 0], mat[2, 1], mat[2, 2]);\n        }\n        public Matrix3(double[] mat)\n        {\n            Row0 = new Vector3(mat[0], mat[1], mat[2]);\n            Row1 = new Vector3(mat[3], mat[4], mat[5]);\n            Row2 = new Vector3(mat[6], mat[7], mat[8]);\n        }\n        public Matrix3(Func<int, float> matBufferF)\n        {\n            Row0 = new Vector3(matBufferF(0), matBufferF(1), matBufferF(2));\n            Row1 = new Vector3(matBufferF(3), matBufferF(4), matBufferF(5));\n            Row2 = new Vector3(matBufferF(6), matBufferF(7), matBufferF(8));\n        }\n        public Matrix3(Func<int, int, float> matF)\n        {\n            Row0 = new Vector3(matF(0, 0), matF(0, 1), matF(0, 2));\n            Row1 = new Vector3(matF(1, 0), matF(1, 1), matF(1, 2));\n            Row2 = new Vector3(matF(2, 0), matF(1, 2), matF(2, 2));\n        }\n        public Matrix3(float m00, float m11, float m22)\n        {\n            Row0 = new Vector3(m00, 0, 0);\n            Row1 = new Vector3(0, m11, 0);\n            Row2 = new Vector3(0, 0, m22);\n        }\n        public Matrix3(Vector3 v1, Vector3 v2, Vector3 v3, bool bRows)\n        {\n            if (bRows)\n            {\n                Row0 = v1; Row1 = v2; Row2 = v3;\n            }\n            else\n            {\n                Row0 = new Vector3(v1.x, v2.x, v3.x);\n                Row1 = new Vector3(v1.y, v2.y, v3.y);\n                Row2 = new Vector3(v1.z, v2.z, v3.z);\n            }\n        }\n        public Matrix3(float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22)\n        {\n            Row0 = new Vector3(m00, m01, m02);\n            Row1 = new Vector3(m10, m11, m12);\n            Row2 = new Vector3(m20, m21, m22);\n        }\n\n\n        public static readonly Matrix3 Identity = new Matrix3(true);\n        public static readonly Matrix3 Zero = new Matrix3(false);\n\n\n\n        public float this[int r, int c]\n        {\n            get\n            {\n                return (r == 0) ? Row0[c] : ((r == 1) ? Row1[c] : Row2[c]);\n            }\n            set\n            {\n                if (r == 0) Row0[c] = value;\n                else if (r == 1) Row1[c] = value;\n                else Row2[c] = value;\n            }\n        }\n\n\n        public float this[int i]\n        {\n            get\n            {\n                return (i > 5) ? Row2[i % 3] : ((i > 2) ? Row1[i % 3] : Row0[i % 3]);\n            }\n            set\n            {\n                if (i > 5) Row2[i % 3] = value;\n                else if (i > 2) Row1[i % 3] = value;\n                else Row0[i % 3] = value;\n            }\n        }\n\n\n\n        public Vector3 Row(int i)\n        {\n            return (i == 0) ? Row0 : (i == 1) ? Row1 : Row2;\n        }\n        public Vector3 Column(int i)\n        {\n            if (i == 0) return new Vector3(Row0.x, Row1.x, Row2.x);\n            else if (i == 1) return new Vector3(Row0.y, Row1.y, Row2.y);\n            else return new Vector3(Row0.z, Row1.z, Row2.z);\n        }\n\n\n        public float[] ToBuffer()\n        {\n            return new float[9] {\n                Row0.x, Row0.y, Row0.z,\n                Row1.x, Row1.y, Row1.z,\n                Row2.x, Row2.y, Row2.z };\n        }\n        public void ToBuffer(float[] buf)\n        {\n            buf[0] = Row0.x; buf[1] = Row0.y; buf[2] = Row0.z;\n            buf[3] = Row1.x; buf[4] = Row1.y; buf[5] = Row1.z;\n            buf[6] = Row2.x; buf[7] = Row2.y; buf[8] = Row2.z;\n        }\n\n\n\n\n        public static Matrix3 operator *(Matrix3 mat, float f)\n        {\n            return new Matrix3(\n                mat.Row0.x * f, mat.Row0.y * f, mat.Row0.z * f,\n                mat.Row1.x * f, mat.Row1.y * f, mat.Row1.z * f,\n                mat.Row2.x * f, mat.Row2.y * f, mat.Row2.z * f);\n        }\n        public static Matrix3 operator *(float f, Matrix3 mat)\n        {\n            return new Matrix3(\n                mat.Row0.x * f, mat.Row0.y * f, mat.Row0.z * f,\n                mat.Row1.x * f, mat.Row1.y * f, mat.Row1.z * f,\n                mat.Row2.x * f, mat.Row2.y * f, mat.Row2.z * f);\n        }\n\n\n        public static Vector3 operator *(Matrix3 mat, Vector3 v)\n        {\n            return new Vector3(\n                mat.Row0.x * v.x + mat.Row0.y * v.y + mat.Row0.z * v.z,\n                mat.Row1.x * v.x + mat.Row1.y * v.y + mat.Row1.z * v.z,\n                mat.Row2.x * v.x + mat.Row2.y * v.y + mat.Row2.z * v.z);\n        }\n\n        public Vector3 Multiply(ref Vector3 v)\n        {\n            return new Vector3(\n                Row0.x * v.x + Row0.y * v.y + Row0.z * v.z,\n                Row1.x * v.x + Row1.y * v.y + Row1.z * v.z,\n                Row2.x * v.x + Row2.y * v.y + Row2.z * v.z);\n        }\n\n        public void Multiply(ref Vector3 v, ref Vector3 vOut)\n        {\n            vOut.x = Row0.x * v.x + Row0.y * v.y + Row0.z * v.z;\n            vOut.y = Row1.x * v.x + Row1.y * v.y + Row1.z * v.z;\n            vOut.z = Row2.x * v.x + Row2.y * v.y + Row2.z * v.z;\n        }\n\n        public static Matrix3 operator *(Matrix3 mat1, Matrix3 mat2)\n        {\n            float m00 = mat1.Row0.x * mat2.Row0.x + mat1.Row0.y * mat2.Row1.x + mat1.Row0.z * mat2.Row2.x;\n            float m01 = mat1.Row0.x * mat2.Row0.y + mat1.Row0.y * mat2.Row1.y + mat1.Row0.z * mat2.Row2.y;\n            float m02 = mat1.Row0.x * mat2.Row0.z + mat1.Row0.y * mat2.Row1.z + mat1.Row0.z * mat2.Row2.z;\n\n            float m10 = mat1.Row1.x * mat2.Row0.x + mat1.Row1.y * mat2.Row1.x + mat1.Row1.z * mat2.Row2.x;\n            float m11 = mat1.Row1.x * mat2.Row0.y + mat1.Row1.y * mat2.Row1.y + mat1.Row1.z * mat2.Row2.y;\n            float m12 = mat1.Row1.x * mat2.Row0.z + mat1.Row1.y * mat2.Row1.z + mat1.Row1.z * mat2.Row2.z;\n\n            float m20 = mat1.Row2.x * mat2.Row0.x + mat1.Row2.y * mat2.Row1.x + mat1.Row2.z * mat2.Row2.x;\n            float m21 = mat1.Row2.x * mat2.Row0.y + mat1.Row2.y * mat2.Row1.y + mat1.Row2.z * mat2.Row2.y;\n            float m22 = mat1.Row2.x * mat2.Row0.z + mat1.Row2.y * mat2.Row1.z + mat1.Row2.z * mat2.Row2.z;\n\n            return new Matrix3(m00, m01, m02, m10, m11, m12, m20, m21, m22);\n        }\n\n\n\n        public static Matrix3 operator +(Matrix3 mat1, Matrix3 mat2)\n        {\n            return new Matrix3(mat1.Row0 + mat2.Row0, mat1.Row1 + mat2.Row1, mat1.Row2 + mat2.Row2, true);\n        }\n        public static Matrix3 operator -(Matrix3 mat1, Matrix3 mat2)\n        {\n            return new Matrix3(mat1.Row0 - mat2.Row0, mat1.Row1 - mat2.Row1, mat1.Row2 - mat2.Row2, true);\n        }\n\n\n        public float Determinant\n        {\n            get\n            {\n                float a11 = Row0.x, a12 = Row0.y, a13 = Row0.z, a21 = Row1.x, a22 = Row1.y, a23 = Row1.z, a31 = Row2.x, a32 = Row2.y, a33 = Row2.z;\n                float i00 = a33 * a22 - a32 * a23;\n                float i01 = -(a33 * a12 - a32 * a13);\n                float i02 = a23 * a12 - a22 * a13;\n                return a11 * i00 + a21 * i01 + a31 * i02;\n            }\n        }\n\n\n        public Matrix3 Inverse()\n        {\n            float a11 = Row0.x, a12 = Row0.y, a13 = Row0.z, a21 = Row1.x, a22 = Row1.y, a23 = Row1.z, a31 = Row2.x, a32 = Row2.y, a33 = Row2.z;\n            float i00 = a33 * a22 - a32 * a23;\n            float i01 = -(a33 * a12 - a32 * a13);\n            float i02 = a23 * a12 - a22 * a13;\n\n            float i10 = -(a33 * a21 - a31 * a23);\n            float i11 = a33 * a11 - a31 * a13;\n            float i12 = -(a23 * a11 - a21 * a13);\n\n            float i20 = a32 * a21 - a31 * a22;\n            float i21 = -(a32 * a11 - a31 * a12);\n            float i22 = a22 * a11 - a21 * a12;\n\n            float det = a11 * i00 + a21 * i01 + a31 * i02;\n            if (Math.Abs(det) < float.Epsilon)\n                throw new Exception(\"Matrix3.Inverse: matrix is not invertible\");\n            det = 1.0f / det;\n            return new Matrix3(i00 * det, i01 * det, i02 * det, i10 * det, i11 * det, i12 * det, i20 * det, i21 * det, i22 * det);\n        }\n\n        public Matrix3 Transpose()\n        {\n            return new Matrix3(\n                Row0.x, Row1.x, Row2.x,\n                Row0.y, Row1.y, Row2.y,\n                Row0.z, Row1.z, Row2.z);\n        }\n\n        public Quaternion ToQuaternion()\n        {\n            return new Quaternion(this);\n        }\n\n\n\n\n\n        public bool EpsilonEqual(Matrix3 m2, float epsilon)\n        {\n            return Row0.EpsilonEqual(m2.Row0, epsilon) &&\n                Row1.EpsilonEqual(m2.Row1, epsilon) &&\n                Row2.EpsilonEqual(m2.Row2, epsilon);\n        }\n\n\n\n\n        public static Matrix3 AxisAngleD(Vector3 axis, float angleDeg)\n        {\n            double angle = angleDeg * MathUtil.Deg2Rad;\n            float cs = (float)Math.Cos(angle);\n            float sn = (float)Math.Sin(angle);\n            float oneMinusCos = 1.0f - cs;\n            float x2 = axis[0] * axis[0];\n            float y2 = axis[1] * axis[1];\n            float z2 = axis[2] * axis[2];\n            float xym = axis[0] * axis[1] * oneMinusCos;\n            float xzm = axis[0] * axis[2] * oneMinusCos;\n            float yzm = axis[1] * axis[2] * oneMinusCos;\n            float xSin = axis[0] * sn;\n            float ySin = axis[1] * sn;\n            float zSin = axis[2] * sn;\n            return new Matrix3(\n                x2 * oneMinusCos + cs, xym - zSin, xzm + ySin,\n                xym + zSin, y2 * oneMinusCos + cs, yzm - xSin,\n                xzm - ySin, yzm + xSin, z2 * oneMinusCos + cs);\n        }\n\n\n\n\n        public override string ToString()\n        {\n            return string.Format(\"[{0}] [{1}] [{2}]\", Row0, Row1, Row2);\n        }\n        public string ToString(string fmt)\n        {\n            return string.Format(\"[{0}] [{1}] [{2}]\", Row0.ToString(fmt), Row1.ToString(fmt), Row2.ToString(fmt));\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/G3Lite/Quaternion.cs",
    "content": "﻿using System;\n\nnamespace SGF.G3Lite\n{\n    // mostly ported from WildMagic5 Wm5Quaternion, from geometrictools.com\n    public struct Quaternion : IComparable<Quaternion>, IEquatable<Quaternion>\n    {\n        // note: in Wm5 version, this is a 4-element array stored in order (w,x,y,z).\n        public float x, y, z, w;\n\n        public Quaternion(float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; }\n        public Quaternion(float[] v2) { x = v2[0]; y = v2[1]; z = v2[2]; w = v2[3]; }\n        public Quaternion(Quaternion q2) { x = q2.x; y = q2.y; z = q2.z; w = q2.w; }\n\n        public Quaternion(Vector3 axis, float AngleDeg)\n        {\n            x = y = z = 0; w = 1;\n            SetAxisAngleD(axis, AngleDeg);\n        }\n        public Quaternion(Vector3 vFrom, Vector3 vTo)\n        {\n            x = y = z = 0; w = 1;\n            SetFromTo(vFrom, vTo);\n        }\n        public Quaternion(Quaternion p, Quaternion q, float t)\n        {\n            x = y = z = 0; w = 1;\n            SetToSlerp(p, q, t);\n        }\n        public Quaternion(Matrix3 mat)\n        {\n            x = y = z = 0; w = 1;\n            SetFromRotationMatrix(mat);\n        }\n\n        static public readonly Quaternion Zero = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f);\n        static public readonly Quaternion Identity = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);\n\n        public float this[int key]\n        {\n            get { if (key == 0) return x; else if (key == 1) return y; else if (key == 2) return z; else return w; }\n            set { if (key == 0) x = value; else if (key == 1) y = value; else if (key == 2) z = value; else w = value; }\n\n        }\n\n\n        public float LengthSquared\n        {\n            get { return x * x + y * y + z * z + w * w; }\n        }\n        public float Length\n        {\n            get { return (float)Math.Sqrt(x * x + y * y + z * z + w * w); }\n        }\n\n        public float Normalize(float epsilon = 0)\n        {\n            float length = Length;\n            if (length > epsilon)\n            {\n                float invLength = 1.0f / length;\n                x *= invLength;\n                y *= invLength;\n                z *= invLength;\n                w *= invLength;\n            }\n            else\n            {\n                length = 0;\n                x = y = z = w = 0;\n            }\n            return length;\n        }\n        public Quaternion Normalized\n        {\n            get { Quaternion q = new Quaternion(this); q.Normalize(); return q; }\n        }\n\n        public float Dot(Quaternion q2)\n        {\n            return x * q2.x + y * q2.y + z * q2.z + w * q2.w;\n        }\n\n\n\n\n        public static Quaternion operator *(Quaternion a, Quaternion b)\n        {\n            float w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n            float x = a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y;\n            float y = a.w * b.y + a.y * b.w + a.z * b.x - a.x * b.z;\n            float z = a.w * b.z + a.z * b.w + a.x * b.y - a.y * b.x;\n            return new Quaternion(x, y, z, w);\n        }\n\n\n\n        public static Quaternion operator -(Quaternion q1, Quaternion q2)\n        {\n            return new Quaternion(q1.x - q2.x, q1.y - q2.y, q1.z - q2.z, q1.w - q2.w);\n        }\n\n        public static Vector3 operator *(Quaternion q, Vector3 v)\n        {\n            //return q.ToRotationMatrix() * v;\n            // inline-expansion of above:\n            float twoX = 2 * q.x; float twoY = 2 * q.y; float twoZ = 2 * q.z;\n            float twoWX = twoX * q.w; float twoWY = twoY * q.w; float twoWZ = twoZ * q.w;\n            float twoXX = twoX * q.x; float twoXY = twoY * q.x; float twoXZ = twoZ * q.x;\n            float twoYY = twoY * q.y; float twoYZ = twoZ * q.y; float twoZZ = twoZ * q.z;\n            return new Vector3(\n                v.x * (1 - (twoYY + twoZZ)) + v.y * (twoXY - twoWZ) + v.z * (twoXZ + twoWY),\n                v.x * (twoXY + twoWZ) + v.y * (1 - (twoXX + twoZZ)) + v.z * (twoYZ - twoWX),\n                v.x * (twoXZ - twoWY) + v.y * (twoYZ + twoWX) + v.z * (1 - (twoXX + twoYY))); ;\n        }\n\n\n\n\n\n        /// <summary> Inverse() * v </summary>\n        public Vector3 InverseMultiply(ref Vector3 v)\n        {\n            float norm = LengthSquared;\n            if (norm > 0)\n            {\n                float invNorm = 1.0f / norm;\n                float qx = -x * invNorm, qy = -y * invNorm, qz = -z * invNorm, qw = w * invNorm;\n                float twoX = 2 * qx; float twoY = 2 * qy; float twoZ = 2 * qz;\n                float twoWX = twoX * qw; float twoWY = twoY * qw; float twoWZ = twoZ * qw;\n                float twoXX = twoX * qx; float twoXY = twoY * qx; float twoXZ = twoZ * qx;\n                float twoYY = twoY * qy; float twoYZ = twoZ * qy; float twoZZ = twoZ * qz;\n                return new Vector3(\n                    v.x * (1 - (twoYY + twoZZ)) + v.y * (twoXY - twoWZ) + v.z * (twoXZ + twoWY),\n                    v.x * (twoXY + twoWZ) + v.y * (1 - (twoXX + twoZZ)) + v.z * (twoYZ - twoWX),\n                    v.x * (twoXZ - twoWY) + v.y * (twoYZ + twoWX) + v.z * (1 - (twoXX + twoYY)));\n            }\n            else\n                return Vector3.zero;\n        }\n\n\n\n\n\n        // these multiply quaternion by (1,0,0), (0,1,0), (0,0,1), respectively.\n        // faster than full multiply, because of all the zeros\n        public Vector3 AxisX\n        {\n            get\n            {\n                float twoY = 2 * y; float twoZ = 2 * z;\n                float twoWY = twoY * w; float twoWZ = twoZ * w;\n                float twoXY = twoY * x; float twoXZ = twoZ * x;\n                float twoYY = twoY * y; float twoZZ = twoZ * z;\n                return new Vector3(1 - (twoYY + twoZZ), twoXY + twoWZ, twoXZ - twoWY);\n            }\n        }\n        public Vector3 AxisY\n        {\n            get\n            {\n                float twoX = 2 * x; float twoY = 2 * y; float twoZ = 2 * z;\n                float twoWX = twoX * w; float twoWZ = twoZ * w; float twoXX = twoX * x;\n                float twoXY = twoY * x; float twoYZ = twoZ * y; float twoZZ = twoZ * z;\n                return new Vector3(twoXY - twoWZ, 1 - (twoXX + twoZZ), twoYZ + twoWX);\n            }\n        }\n        public Vector3 AxisZ\n        {\n            get\n            {\n                float twoX = 2 * x; float twoY = 2 * y; float twoZ = 2 * z;\n                float twoWX = twoX * w; float twoWY = twoY * w; float twoXX = twoX * x;\n                float twoXZ = twoZ * x; float twoYY = twoY * y; float twoYZ = twoZ * y;\n                return new Vector3(twoXZ + twoWY, twoYZ - twoWX, 1 - (twoXX + twoYY));\n            }\n        }\n\n\n\n        public Quaternion Inverse()\n        {\n            float norm = LengthSquared;\n            if (norm > 0)\n            {\n                float invNorm = 1.0f / norm;\n                return new Quaternion(\n                    -x * invNorm, -y * invNorm, -z * invNorm, w * invNorm);\n            }\n            else\n                return Quaternion.Zero;\n        }\n        public static Quaternion Inverse(Quaternion q)\n        {\n            return q.Inverse();\n        }\n\n\n\n        public Matrix3 ToRotationMatrix()\n        {\n            float twoX = 2 * x; float twoY = 2 * y; float twoZ = 2 * z;\n            float twoWX = twoX * w; float twoWY = twoY * w; float twoWZ = twoZ * w;\n            float twoXX = twoX * x; float twoXY = twoY * x; float twoXZ = twoZ * x;\n            float twoYY = twoY * y; float twoYZ = twoZ * y; float twoZZ = twoZ * z;\n            Matrix3 m = Matrix3.Zero;\n            m[0, 0] = 1 - (twoYY + twoZZ); m[0, 1] = twoXY - twoWZ; m[0, 2] = twoXZ + twoWY;\n            m[1, 0] = twoXY + twoWZ; m[1, 1] = 1 - (twoXX + twoZZ); m[1, 2] = twoYZ - twoWX;\n            m[2, 0] = twoXZ - twoWY; m[2, 1] = twoYZ + twoWX; m[2, 2] = 1 - (twoXX + twoYY);\n            return m;\n        }\n\n\n\n        public void SetAxisAngleD(Vector3 axis, float AngleDeg)\n        {\n            double angle_rad = MathUtil.Deg2Rad * AngleDeg;\n            double halfAngle = 0.5 * angle_rad;\n            double sn = Math.Sin(halfAngle);\n            w = (float)Math.Cos(halfAngle);\n            x = (float)(sn * axis.x);\n            y = (float)(sn * axis.y);\n            z = (float)(sn * axis.z);\n        }\n\n        public static Quaternion AngleAxis(float angleDeg, Vector3 axis)\n        {\n            return new Quaternion(axis, angleDeg);\n        }\n\n        public static Quaternion AngleAxisRad(float angleRad, Vector3 axis)\n        {\n            return new Quaternion(axis, angleRad * MathUtil.Rad2Degf);\n        }\n\n        // this function can take non-normalized vectors vFrom and vTo (normalizes internally)\n        public void SetFromTo(Vector3 vFrom, Vector3 vTo)\n        {\n            // [TODO] this page seems to have optimized version:\n            //    http://lolengine.net/blog/2013/09/18/beautiful-maths-quaternion-from-vectors\n\n            // [RMS] not ideal to explicitly normalize here, but if we don't,\n            //   output quaternion is not normalized and this causes problems,\n            //   eg like drift if we do repeated SetFromTo()\n            Vector3 from = vFrom.normalized, to = vTo.normalized;\n            Vector3 bisector = (from + to).normalized;\n            w = from.Dot(bisector);\n            if (w != 0)\n            {\n                Vector3 cross = from.Cross(bisector);\n                x = cross.x;\n                y = cross.y;\n                z = cross.z;\n            }\n            else\n            {\n                float invLength;\n                if (Math.Abs(from.x) >= Math.Abs(from.y))\n                {\n                    // V1.x or V1.z is the largest magnitude component.\n                    invLength = (float)(1.0 / Math.Sqrt(from.x * from.x + from.z * from.z));\n                    x = -from.z * invLength;\n                    y = 0;\n                    z = +from.x * invLength;\n                }\n                else\n                {\n                    // V1.y or V1.z is the largest magnitude component.\n                    invLength = (float)(1.0 / Math.Sqrt(from.y * from.y + from.z * from.z));\n                    x = 0;\n                    y = +from.z * invLength;\n                    z = -from.y * invLength;\n                }\n            }\n            Normalize();   // aaahhh just to be safe...\n        }\n        public static Quaternion FromTo(Vector3 vFrom, Vector3 vTo)\n        {\n            return new Quaternion(vFrom, vTo);\n        }\n        public static Quaternion FromToConstrained(Vector3 vFrom, Vector3 vTo, Vector3 vAround)\n        {\n            float fAngle = MathUtil.PlaneAngleSignedD(vFrom, vTo, vAround);\n            return Quaternion.AngleAxis(fAngle, vAround);\n        }\n\n\n        public void SetToSlerp(Quaternion p, Quaternion q, float t)\n        {\n            float cs = p.Dot(q);\n            float angle = (float)Math.Acos(cs);\n            if (Math.Abs(angle) >= MathUtil.ZeroTolerance)\n            {\n                float sn = (float)Math.Sin(angle);\n                float invSn = 1 / sn;\n                float tAngle = t * angle;\n                float coeff0 = (float)Math.Sin(angle - tAngle) * invSn;\n                float coeff1 = (float)Math.Sin(tAngle) * invSn;\n                x = coeff0 * p.x + coeff1 * q.x;\n                y = coeff0 * p.y + coeff1 * q.y;\n                z = coeff0 * p.z + coeff1 * q.z;\n                w = coeff0 * p.w + coeff1 * q.w;\n            }\n            else\n            {\n                x = p.x;\n                y = p.y;\n                z = p.z;\n                w = p.w;\n            }\n        }\n        public static Quaternion Slerp(Quaternion p, Quaternion q, float t)\n        {\n            return new Quaternion(p, q, t);\n        }\n\n\n\n        public void SetFromRotationMatrix(Matrix3 rot)\n        {\n            // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\n            // article \"Quaternion Calculus and Fast Animation\".\n            Index3 next = new Index3(1, 2, 0);\n\n            float trace = rot[0, 0] + rot[1, 1] + rot[2, 2];\n            float root;\n\n            if (trace > 0)\n            {\n                // |w| > 1/2, may as well choose w > 1/2\n                root = (float)Math.Sqrt(trace + (float)1);  // 2w\n                w = ((float)0.5) * root;\n                root = ((float)0.5) / root;  // 1/(4w)\n                x = (rot[2, 1] - rot[1, 2]) * root;\n                y = (rot[0, 2] - rot[2, 0]) * root;\n                z = (rot[1, 0] - rot[0, 1]) * root;\n            }\n            else\n            {\n                // |w| <= 1/2\n                int i = 0;\n                if (rot[1, 1] > rot[0, 0])\n                {\n                    i = 1;\n                }\n                if (rot[2, 2] > rot[i, i])\n                {\n                    i = 2;\n                }\n                int j = next[i];\n                int k = next[j];\n\n                root = (float)Math.Sqrt(rot[i, i] - rot[j, j] - rot[k, k] + (float)1);\n\n                Vector3 quat = new Vector3(x, y, z);\n                quat[i] = ((float)0.5) * root;\n                root = ((float)0.5) / root;\n                w = (rot[k, j] - rot[j, k]) * root;\n                quat[j] = (rot[j, i] + rot[i, j]) * root;\n                quat[k] = (rot[k, i] + rot[i, k]) * root;\n                x = quat.x; y = quat.y; z = quat.z;\n            }\n\n            Normalize();   // we prefer normalized quaternions...\n        }\n\n\n        public static Quaternion Euler(Vector3 euler)\n        {\n            float pitch = euler.x;\n            float roll = euler.y;\n            float yaw = euler.z;\n\n            Quaternion q;\n            // Abbreviations for the various angular functions\n            double cy = Math.Cos(yaw * 0.5);\n            double sy = Math.Sin(yaw * 0.5);\n            double cr = Math.Cos(roll * 0.5);\n            double sr = Math.Sin(roll * 0.5);\n            double cp = Math.Cos(pitch * 0.5);\n            double sp = Math.Sin(pitch * 0.5);\n\n            q.w = (float)(cy * cr * cp + sy * sr * sp);\n            q.x = (float)(cy * sr * cp - sy * cr * sp);\n            q.y = (float)(cy * cr * sp + sy * sr * cp);\n            q.z = (float)(sy * cr * cp - cy * sr * sp);\n            return q;\n        }\n\n\n\n        public static bool operator ==(Quaternion a, Quaternion b)\n        {\n            return (a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w);\n        }\n        public static bool operator !=(Quaternion a, Quaternion b)\n        {\n            return (a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w);\n        }\n        public override bool Equals(object obj)\n        {\n            return this == (Quaternion)obj;\n        }\n        public override int GetHashCode()\n        {\n            unchecked // Overflow is fine, just wrap\n            {\n                int hash = (int)2166136261;\n                // Suitable nullity checks etc, of course :)\n                hash = (hash * 16777619) ^ x.GetHashCode();\n                hash = (hash * 16777619) ^ y.GetHashCode();\n                hash = (hash * 16777619) ^ z.GetHashCode();\n                hash = (hash * 16777619) ^ w.GetHashCode();\n                return hash;\n            }\n        }\n        public int CompareTo(Quaternion other)\n        {\n            if (x != other.x)\n                return x < other.x ? -1 : 1;\n            else if (y != other.y)\n                return y < other.y ? -1 : 1;\n            else if (z != other.z)\n                return z < other.z ? -1 : 1;\n            else if (w != other.w)\n                return w < other.w ? -1 : 1;\n            return 0;\n        }\n        public bool Equals(Quaternion other)\n        {\n            return (x == other.x && y == other.y && z == other.z && w == other.w);\n        }\n\n\n\n\n\n        public bool EpsilonEqual(Quaternion q2, float epsilon)\n        {\n            return (float)Math.Abs(x - q2.x) <= epsilon &&\n                   (float)Math.Abs(y - q2.y) <= epsilon &&\n                   (float)Math.Abs(z - q2.z) <= epsilon &&\n                   (float)Math.Abs(w - q2.w) <= epsilon;\n        }\n\n\n        public override string ToString()\n        {\n            return string.Format(\"{0:F8} {1:F8} {2:F8} {3:F8}\", x, y, z, w);\n        }\n        public string ToString(string fmt)\n        {\n            return string.Format(\"{0} {1} {2} {3}\", x.ToString(fmt), y.ToString(fmt), z.ToString(fmt), w.ToString(fmt));\n        }\n\n\n#if G3_USING_UNITY\n        public static implicit operator Quaternion(Quaternion q)\n        {\n            return new Quaternion(q.x, q.y, q.z, q.w);\n        }\n        public static implicit operator Quaternion(Quaternion q)\n        {\n            return new Quaternion(q.x, q.y, q.z, q.w);\n        }\n#endif\n\n    }\n}\n\n"
  },
  {
    "path": "SGFCore/G3Lite/Vector2.cs",
    "content": "﻿using System;\n\nnamespace SGF.G3Lite\n{\n    public struct Vector2 : IComparable<Vector2>, IEquatable<Vector2>\n    {\n        public float x;\n        public float y;\n\n        public Vector2(float f) { x = y = f; }\n        public Vector2(float x, float y) { this.x = x; this.y = y; }\n        public Vector2(float[] v2) { x = v2[0]; y = v2[1]; }\n        public Vector2(double f) { x = y = (float)f; }\n        public Vector2(double x, double y) { this.x = (float)x; this.y = (float)y; }\n        public Vector2(double[] v2) { x = (float)v2[0]; y = (float)v2[1]; }\n        public Vector2(Vector2 copy) { x = copy[0]; y = copy[1]; }\n \n\n        static public readonly Vector2 Zero = new Vector2(0.0f, 0.0f);\n        static public readonly Vector2 One = new Vector2(1.0f, 1.0f);\n        static public readonly Vector2 AxisX = new Vector2(1.0f, 0.0f);\n        static public readonly Vector2 AxisY = new Vector2(0.0f, 1.0f);\n        static public readonly Vector2 MaxValue = new Vector2(float.MaxValue, float.MaxValue);\n        static public readonly Vector2 MinValue = new Vector2(float.MinValue, float.MinValue);\n\n        public float this[int key]\n        {\n            get { return (key == 0) ? x : y; }\n            set { if (key == 0) x = value; else y = value; }\n        }\n\n\n        public float LengthSquared\n        {\n            get { return x * x + y * y; }\n        }\n        public float Length\n        {\n            get { return (float)Math.Sqrt(LengthSquared); }\n        }\n\n        public float Normalize(float epsilon = MathUtil.Epsilonf)\n        {\n            float length = Length;\n            if (length > epsilon)\n            {\n                float invLength = 1.0f / length;\n                x *= invLength;\n                y *= invLength;\n            }\n            else\n            {\n                length = 0;\n                x = y = 0;\n            }\n            return length;\n        }\n        public Vector2 Normalized\n        {\n            get\n            {\n                float length = Length;\n                if (length > MathUtil.Epsilonf)\n                {\n                    float invLength = 1 / length;\n                    return new Vector2(x * invLength, y * invLength);\n                }\n                else\n                    return Vector2.Zero;\n            }\n        }\n\n        public bool IsNormalized\n        {\n            get { return Math.Abs((x * x + y * y) - 1) < MathUtil.ZeroTolerancef; }\n        }\n\n        public bool IsFinite\n        {\n            get { float f = x + y; return float.IsNaN(f) == false && float.IsInfinity(f) == false; }\n        }\n\n        public void Round(int nDecimals)\n        {\n            x = (float)Math.Round(x, nDecimals);\n            y = (float)Math.Round(y, nDecimals);\n        }\n\n        public float Dot(Vector2 v2)\n        {\n            return x * v2.x + y * v2.y;\n        }\n\n\n        public float Cross(Vector2 v2)\n        {\n            return x * v2.y - y * v2.x;\n        }\n\n\n        public Vector2 Perp\n        {\n            get { return new Vector2(y, -x); }\n        }\n        public Vector2 UnitPerp\n        {\n            get { return new Vector2(y, -x).Normalized; }\n        }\n        public float DotPerp(Vector2 v2)\n        {\n            return x * v2.y - y * v2.x;\n        }\n\n\n        public float AngleD(Vector2 v2)\n        {\n            float fDot = MathUtil.Clamp(Dot(v2), -1, 1);\n            return (float)(Math.Acos(fDot) * MathUtil.Rad2Deg);\n        }\n        public static float AngleD(Vector2 v1, Vector2 v2)\n        {\n            return v1.AngleD(v2);\n        }\n        public float AngleR(Vector2 v2)\n        {\n            float fDot = MathUtil.Clamp(Dot(v2), -1, 1);\n            return (float)(Math.Acos(fDot));\n        }\n        public static float AngleR(Vector2 v1, Vector2 v2)\n        {\n            return v1.AngleR(v2);\n        }\n\n\n\n        public float DistanceSquared(Vector2 v2)\n        {\n            float dx = v2.x - x, dy = v2.y - y;\n            return dx * dx + dy * dy;\n        }\n        public float Distance(Vector2 v2)\n        {\n            float dx = v2.x - x, dy = v2.y - y;\n            return (float)Math.Sqrt(dx * dx + dy * dy);\n        }\n\n\n        public void Set(Vector2 o)\n        {\n            x = o.x; y = o.y;\n        }\n        public void Set(float fX, float fY)\n        {\n            x = fX; y = fY;\n        }\n        public void Add(Vector2 o)\n        {\n            x += o.x; y += o.y;\n        }\n        public void Subtract(Vector2 o)\n        {\n            x -= o.x; y -= o.y;\n        }\n\n\n        public static Vector2 operator -(Vector2 v)\n        {\n            return new Vector2(-v.x, -v.y);\n        }\n\n        public static Vector2 operator +(Vector2 a, Vector2 o)\n        {\n            return new Vector2(a.x + o.x, a.y + o.y);\n        }\n        public static Vector2 operator +(Vector2 a, float f)\n        {\n            return new Vector2(a.x + f, a.y + f);\n        }\n\n        public static Vector2 operator -(Vector2 a, Vector2 o)\n        {\n            return new Vector2(a.x - o.x, a.y - o.y);\n        }\n        public static Vector2 operator -(Vector2 a, float f)\n        {\n            return new Vector2(a.x - f, a.y - f);\n        }\n\n        public static Vector2 operator *(Vector2 a, float f)\n        {\n            return new Vector2(a.x * f, a.y * f);\n        }\n        public static Vector2 operator *(float f, Vector2 a)\n        {\n            return new Vector2(a.x * f, a.y * f);\n        }\n        public static Vector2 operator /(Vector2 v, float f)\n        {\n            return new Vector2(v.x / f, v.y / f);\n        }\n        public static Vector2 operator /(float f, Vector2 v)\n        {\n            return new Vector2(f / v.x, f / v.y);\n        }\n\n        public static Vector2 operator *(Vector2 a, Vector2 b)\n        {\n            return new Vector2(a.x * b.x, a.y * b.y);\n        }\n        public static Vector2 operator /(Vector2 a, Vector2 b)\n        {\n            return new Vector2(a.x / b.x, a.y / b.y);\n        }\n\n\n        public static bool operator ==(Vector2 a, Vector2 b)\n        {\n            return (a.x == b.x && a.y == b.y);\n        }\n        public static bool operator !=(Vector2 a, Vector2 b)\n        {\n            return (a.x != b.x || a.y != b.y);\n        }\n        public override bool Equals(object obj)\n        {\n            return this == (Vector2)obj;\n        }\n        public override int GetHashCode()\n        {\n            unchecked // Overflow is fine, just wrap\n            {\n                int hash = (int)2166136261;\n                // Suitable nullity checks etc, of course :)\n                hash = (hash * 16777619) ^ x.GetHashCode();\n                hash = (hash * 16777619) ^ y.GetHashCode();\n                return hash;\n            }\n        }\n        public int CompareTo(Vector2 other)\n        {\n            if (x != other.x)\n                return x < other.x ? -1 : 1;\n            else if (y != other.y)\n                return y < other.y ? -1 : 1;\n            return 0;\n        }\n        public bool Equals(Vector2 other)\n        {\n            return (x == other.x && y == other.y);\n        }\n\n\n        public bool EpsilonEqual(Vector2 v2, float epsilon)\n        {\n            return (float)Math.Abs(x - v2.x) <= epsilon &&\n                   (float)Math.Abs(y - v2.y) <= epsilon;\n        }\n\n\n        public static Vector2 Lerp(Vector2 a, Vector2 b, float t)\n        {\n            float s = 1 - t;\n            return new Vector2(s * a.x + t * b.x, s * a.y + t * b.y);\n        }\n        public static Vector2 Lerp(ref Vector2 a, ref Vector2 b, float t)\n        {\n            float s = 1 - t;\n            return new Vector2(s * a.x + t * b.x, s * a.y + t * b.y);\n        }\n\n\n        public override string ToString()\n        {\n            return string.Format(\"{0:F8} {1:F8}\", x, y);\n        }\n\n\n        public static implicit operator Vector2(Vector3 v)\n        {\n            return new Vector2(v.x, v.y);\n        }\n\n#if G3_USING_UNITY\n        public static implicit operator Vector2(UnityEngine.Vector2 v)\n        {\n            return new Vector2(v.x, v.y);\n        }\n        public static implicit operator Vector2(Vector2 v)\n        {\n            return new Vector2(v.x, v.y);\n        }\n#endif\n\n    }\n}"
  },
  {
    "path": "SGFCore/G3Lite/Vector3.cs",
    "content": "﻿using System;\n\nnamespace SGF.G3Lite\n{\n    public struct Vector3 : IComparable<Vector3>, IEquatable<Vector3>\n    {\n        public float x;\n        public float y;\n        public float z;\n\n        public Vector3(float f) { x = y = z = f; }\n        public Vector3(float x, float y, float z) { this.x = x; this.y = y; this.z = z; }\n        public Vector3(float[] v2) { x = v2[0]; y = v2[1]; z = v2[2]; }\n        public Vector3(Vector3 copy) { x = copy.x; y = copy.y; z = copy.z; }\n\n        public Vector3(double f) { x = y = z = (float)f; }\n        public Vector3(double x, double y, double z) { this.x = (float)x; this.y = (float)y; this.z = (float)z; }\n        public Vector3(double[] v2) { x = (float)v2[0]; y = (float)v2[1]; z = (float)v2[2]; }\n\n        static public readonly Vector3 zero = new Vector3(0.0f, 0.0f, 0.0f);\n        static public readonly Vector3 one = new Vector3(1.0f, 1.0f, 1.0f);\n        static public readonly Vector3 forward = new Vector3(0.0f, 0.0f, 1.0f);\n        static public readonly Vector3 back = new Vector3(0.0f, 0.0f, -1.0f);\n        static public readonly Vector3 up = new Vector3(0.0f, 1.0f, 0.0f);\n        static public readonly Vector3 down = new Vector3(0.0f, -1.0f, 0.0f);\n        static public readonly Vector3 left = new Vector3(-1.0f, 0.0f, 0.0f);\n        static public readonly Vector3 right = new Vector3(1.0f, 0.0f, 0.0f);\n\n        static public readonly Vector3 OneNormalized = new Vector3(1.0f, 1.0f, 1.0f).normalized;\n        static public readonly Vector3 Invalid = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);\n        static public readonly Vector3 AxisX = new Vector3(1.0f, 0.0f, 0.0f);\n        static public readonly Vector3 AxisY = new Vector3(0.0f, 1.0f, 0.0f);\n        static public readonly Vector3 AxisZ = new Vector3(0.0f, 0.0f, 1.0f);\n        static public readonly Vector3 MaxValue = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);\n        static public readonly Vector3 MinValue = new Vector3(float.MinValue, float.MinValue, float.MinValue);\n\n\n\n        public float this[int key]\n        {\n            get { return (key == 0) ? x : (key == 1) ? y : z; }\n            set { if (key == 0) x = value; else if (key == 1) y = value; else z = value; }\n        }\n\n        public Vector2 xy\n        {\n            get { return new Vector2(x, y); }\n            set { x = value.x; y = value.y; }\n        }\n        public Vector2 xz\n        {\n            get { return new Vector2(x, z); }\n            set { x = value.x; z = value.y; }\n        }\n        public Vector2 yz\n        {\n            get { return new Vector2(y, z); }\n            set { y = value.x; z = value.y; }\n        }\n\n        public float sqrMagnitude\n        {\n            get { return x * x + y * y + z * z; }\n        }\n        public float magnitude\n        {\n            get { return (float)Math.Sqrt(sqrMagnitude); }\n        }\n\n        public float LengthL1\n        {\n            get { return Math.Abs(x) + Math.Abs(y) + Math.Abs(z); }\n        }\n\n        public float Max\n        {\n            get { return Math.Max(x, Math.Max(y, z)); }\n        }\n        public float Min\n        {\n            get { return Math.Min(x, Math.Min(y, z)); }\n        }\n        public float MaxAbs\n        {\n            get { return Math.Max(Math.Abs(x), Math.Max(Math.Abs(y), Math.Abs(z))); }\n        }\n        public float MinAbs\n        {\n            get { return Math.Min(Math.Abs(x), Math.Min(Math.Abs(y), Math.Abs(z))); }\n        }\n\n\n        public float Normalize(float epsilon = MathUtil.Epsilonf)\n        {\n            float length = magnitude;\n            if (length > epsilon)\n            {\n                float invLength = 1.0f / length;\n                x *= invLength;\n                y *= invLength;\n                z *= invLength;\n            }\n            else\n            {\n                length = 0;\n                x = y = z = 0;\n            }\n            return length;\n        }\n        public Vector3 normalized\n        {\n            get\n            {\n                float length = magnitude;\n                if (length > MathUtil.Epsilonf)\n                {\n                    float invLength = 1 / length;\n                    return new Vector3(x * invLength, y * invLength, z * invLength);\n                }\n                else\n                    return Vector3.zero;\n            }\n        }\n\n        public bool IsNormalized\n        {\n            get { return Math.Abs((x * x + y * y + z * z) - 1) < MathUtil.ZeroTolerancef; }\n        }\n\n        public bool IsFinite\n        {\n            get { float f = x + y + z; return float.IsNaN(f) == false && float.IsInfinity(f) == false; }\n        }\n\n\n        public void Round(int nDecimals)\n        {\n            x = (float)Math.Round(x, nDecimals);\n            y = (float)Math.Round(y, nDecimals);\n            z = (float)Math.Round(z, nDecimals);\n        }\n\n\n        public float Dot(Vector3 v2)\n        {\n            return x * v2[0] + y * v2[1] + z * v2[2];\n        }\n        public static float Dot(Vector3 v1, Vector3 v2)\n        {\n            return v1.Dot(v2);\n        }\n\n\n        public Vector3 Cross(Vector3 v2)\n        {\n            return new Vector3(\n                y * v2.z - z * v2.y,\n                z * v2.x - x * v2.z,\n                x * v2.y - y * v2.x);\n        }\n        public static Vector3 Cross(Vector3 v1, Vector3 v2)\n        {\n            return v1.Cross(v2);\n        }\n\n        public Vector3 UnitCross(Vector3 v2)\n        {\n            Vector3 n = new Vector3(\n                y * v2.z - z * v2.y,\n                z * v2.x - x * v2.z,\n                x * v2.y - y * v2.x);\n            n.Normalize();\n            return n;\n        }\n\n        public float AngleD(Vector3 v2)\n        {\n            float fDot = MathUtil.Clamp(Dot(v2), -1, 1);\n            return (float)(Math.Acos(fDot) * MathUtil.Rad2Deg);\n        }\n        public static float AngleD(Vector3 v1, Vector3 v2)\n        {\n            return v1.AngleD(v2);\n        }\n        public float AngleR(Vector3 v2)\n        {\n            float fDot = MathUtil.Clamp(Dot(v2), -1, 1);\n            return (float)(Math.Acos(fDot));\n        }\n        public static float AngleR(Vector3 v1, Vector3 v2)\n        {\n            return v1.AngleR(v2);\n        }\n\n\n        public float DistanceSquared(Vector3 v2)\n        {\n            float dx = v2.x - x, dy = v2.y - y, dz = v2.z - z;\n            return dx * dx + dy * dy + dz * dz;\n        }\n        public float Distance(Vector3 v2)\n        {\n            float dx = v2.x - x, dy = v2.y - y, dz = v2.z - z;\n            return (float)Math.Sqrt(dx * dx + dy * dy + dz * dz);\n        }\n\n\n\n        public void Set(Vector3 o)\n        {\n            x = o[0]; y = o[1]; z = o[2];\n        }\n        public void Set(float fX, float fY, float fZ)\n        {\n            x = fX; y = fY; z = fZ;\n        }\n        public void Add(Vector3 o)\n        {\n            x += o[0]; y += o[1]; z += o[2];\n        }\n        public void Subtract(Vector3 o)\n        {\n            x -= o[0]; y -= o[1]; z -= o[2];\n        }\n\n\n\n        public static Vector3 operator -(Vector3 v)\n        {\n            return new Vector3(-v.x, -v.y, -v.z);\n        }\n\n        public static Vector3 operator *(float f, Vector3 v)\n        {\n            return new Vector3(f * v.x, f * v.y, f * v.z);\n        }\n        public static Vector3 operator *(Vector3 v, float f)\n        {\n            return new Vector3(f * v.x, f * v.y, f * v.z);\n        }\n        public static Vector3 operator /(Vector3 v, float f)\n        {\n            return new Vector3(v.x / f, v.y / f, v.z / f);\n        }\n        public static Vector3 operator /(float f, Vector3 v)\n        {\n            return new Vector3(f / v.x, f / v.y, f / v.z);\n        }\n\n        public static Vector3 operator *(Vector3 a, Vector3 b)\n        {\n            return new Vector3(a.x * b.x, a.y * b.y, a.z * b.z);\n        }\n        public static Vector3 operator /(Vector3 a, Vector3 b)\n        {\n            return new Vector3(a.x / b.x, a.y / b.y, a.z / b.z);\n        }\n\n\n        public static Vector3 operator +(Vector3 v0, Vector3 v1)\n        {\n            return new Vector3(v0.x + v1.x, v0.y + v1.y, v0.z + v1.z);\n        }\n        public static Vector3 operator +(Vector3 v0, float f)\n        {\n            return new Vector3(v0.x + f, v0.y + f, v0.z + f);\n        }\n\n        public static Vector3 operator -(Vector3 v0, Vector3 v1)\n        {\n            return new Vector3(v0.x - v1.x, v0.y - v1.y, v0.z - v1.z);\n        }\n        public static Vector3 operator -(Vector3 v0, float f)\n        {\n            return new Vector3(v0.x - f, v0.y - f, v0.z - f);\n        }\n\n\n        public static bool operator ==(Vector3 a, Vector3 b)\n        {\n            return (a.x == b.x && a.y == b.y && a.z == b.z);\n        }\n        public static bool operator !=(Vector3 a, Vector3 b)\n        {\n            return (a.x != b.x || a.y != b.y || a.z != b.z);\n        }\n        public override bool Equals(object obj)\n        {\n            return this == (Vector3)obj;\n        }\n        public override int GetHashCode()\n        {\n            unchecked // Overflow is fine, just wrap\n            {\n                int hash = (int)2166136261;\n                // Suitable nullity checks etc, of course :)\n                hash = (hash * 16777619) ^ x.GetHashCode();\n                hash = (hash * 16777619) ^ y.GetHashCode();\n                hash = (hash * 16777619) ^ z.GetHashCode();\n                return hash;\n            }\n        }\n        public int CompareTo(Vector3 other)\n        {\n            if (x != other.x)\n                return x < other.x ? -1 : 1;\n            else if (y != other.y)\n                return y < other.y ? -1 : 1;\n            else if (z != other.z)\n                return z < other.z ? -1 : 1;\n            return 0;\n        }\n        public bool Equals(Vector3 other)\n        {\n            return (x == other.x && y == other.y && z == other.z);\n        }\n\n\n        public bool EpsilonEqual(Vector3 v2, float epsilon)\n        {\n            return (float)Math.Abs(x - v2.x) <= epsilon &&\n                   (float)Math.Abs(y - v2.y) <= epsilon &&\n                   (float)Math.Abs(z - v2.z) <= epsilon;\n        }\n\n\n        public static Vector3 Lerp(Vector3 a, Vector3 b, float t)\n        {\n            float s = 1 - t;\n            return new Vector3(s * a.x + t * b.x, s * a.y + t * b.y, s * a.z + t * b.z);\n        }\n\n\n\n        public override string ToString()\n        {\n            return string.Format(\"{0:F8} {1:F8} {2:F8}\", x, y, z);\n        }\n        public string ToString(string fmt)\n        {\n            return string.Format(\"{0} {1} {2}\", x.ToString(fmt), y.ToString(fmt), z.ToString(fmt));\n        }\n\n\n        public static implicit operator Vector3(Vector2 v)\n        {\n            return new Vector3(v.x, v.y, 0);\n        }\n\n\n#if G3_USING_UNITY\n        public static implicit operator Vector3(UnityEngine.Vector3 v)\n        {\n            return new Vector3(v.x, v.y, v.z);\n        }\n        public static implicit operator Vector3(Vector3 v)\n        {\n            return new Vector3(v.x, v.y, v.z);\n        }\n        public static implicit operator Color(Vector3 v)\n        {\n            return new Color(v.x, v.y, v.z, 1.0f);\n        }\n        public static implicit operator Vector3(Color c)\n        {\n            return new Vector3(c.r, c.g, c.b);\n        }\n#endif\n\n    }\n}"
  },
  {
    "path": "SGFCore/G3Lite/Vector4.cs",
    "content": "﻿using System;\n\nnamespace SGF.G3Lite\n{\n    public struct Vector4 : IComparable<Vector4>, IEquatable<Vector4>\n    {\n        public float x;\n        public float y;\n        public float z;\n        public float w;\n\n        public Vector4(float f) { x = y = z = w = f; }\n        public Vector4(float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; }\n        public Vector4(float[] v2) { x = v2[0]; y = v2[1]; z = v2[2]; w = v2[3]; }\n        public Vector4(Vector4 copy) { x = copy.x; y = copy.y; z = copy.z; w = copy.w; }\n\n        static public readonly Vector4 zero = new Vector4(0.0f, 0.0f, 0.0f, 0.0f);\n        static public readonly Vector4 one = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);\n\n        public float this[int key]\n        {\n            get { return (key < 2) ? ((key == 0) ? x : y) : ((key == 2) ? z : w); }\n            set\n            {\n                if (key < 2) { if (key == 0) x = value; else y = value; }\n                else { if (key == 2) z = value; else w = value; }\n            }\n        }\n\n        public float LengthSquared\n        {\n            get { return x * x + y * y + z * z + w * w; }\n        }\n        public float Length\n        {\n            get { return (float)Math.Sqrt(LengthSquared); }\n        }\n\n        public float LengthL1\n        {\n            get { return Math.Abs(x) + Math.Abs(y) + Math.Abs(z) + Math.Abs(w); }\n        }\n\n\n        public float Normalize(float epsilon = MathUtil.Epsilonf)\n        {\n            float length = Length;\n            if (length > epsilon)\n            {\n                float invLength = 1.0f / length;\n                x *= invLength;\n                y *= invLength;\n                z *= invLength;\n                w *= invLength;\n            }\n            else\n            {\n                length = 0;\n                x = y = z = w = 0;\n            }\n            return length;\n        }\n        public Vector4 Normalized\n        {\n            get\n            {\n                float length = Length;\n                if (length > MathUtil.Epsilon)\n                {\n                    float invLength = 1.0f / length;\n                    return new Vector4(x * invLength, y * invLength, z * invLength, w * invLength);\n                }\n                else\n                    return Vector4.zero;\n            }\n        }\n\n        public bool IsNormalized\n        {\n            get { return Math.Abs((x * x + y * y + z * z + w * w) - 1) < MathUtil.ZeroTolerance; }\n        }\n\n\n        public bool IsFinite\n        {\n            get { float f = x + y + z + w; return float.IsNaN(f) == false && float.IsInfinity(f) == false; }\n        }\n\n        public void Round(int nDecimals)\n        {\n            x = (float)Math.Round(x, nDecimals);\n            y = (float)Math.Round(y, nDecimals);\n            z = (float)Math.Round(z, nDecimals);\n            w = (float)Math.Round(w, nDecimals);\n        }\n\n\n        public float Dot(Vector4 v2)\n        {\n            return x * v2.x + y * v2.y + z * v2.z + w * v2.w;\n        }\n        public float Dot(ref Vector4 v2)\n        {\n            return x * v2.x + y * v2.y + z * v2.z + w * v2.w;\n        }\n\n        public static float Dot(Vector4 v1, Vector4 v2)\n        {\n            return v1.Dot(v2);\n        }\n\n\n        public float AngleD(Vector4 v2)\n        {\n            float fDot = MathUtil.Clamp(Dot(v2), -1, 1);\n            return (float)Math.Acos(fDot) * MathUtil.Rad2Degf;\n        }\n        public static float AngleD(Vector4 v1, Vector4 v2)\n        {\n            return v1.AngleD(v2);\n        }\n        public float AngleR(Vector4 v2)\n        {\n            float fDot = MathUtil.Clamp(Dot(v2), -1, 1);\n            return (float)Math.Acos(fDot);\n        }\n        public static float AngleR(Vector4 v1, Vector4 v2)\n        {\n            return v1.AngleR(v2);\n        }\n\n        public float DistanceSquared(Vector4 v2)\n        {\n            float dx = v2.x - x, dy = v2.y - y, dz = v2.z - z, dw = v2.w - w;\n            return dx * dx + dy * dy + dz * dz + dw * dw;\n        }\n        public float DistanceSquared(ref Vector4 v2)\n        {\n            float dx = v2.x - x, dy = v2.y - y, dz = v2.z - z, dw = v2.w - w;\n            return dx * dx + dy * dy + dz * dz + dw * dw;\n        }\n\n        public float Distance(Vector4 v2)\n        {\n            float dx = v2.x - x, dy = v2.y - y, dz = v2.z - z, dw = v2.w - w;\n            return (float)Math.Sqrt(dx * dx + dy * dy + dz * dz + dw * dw);\n        }\n        public float Distance(ref Vector4 v2)\n        {\n            float dx = v2.x - x, dy = v2.y - y, dz = v2.z - z, dw = v2.w - w;\n            return (float)Math.Sqrt(dx * dx + dy * dy + dz * dz + dw * dw);\n        }\n\n\n        public static Vector4 operator -(Vector4 v)\n        {\n            return new Vector4(-v.x, -v.y, -v.z, -v.w);\n        }\n\n        public static Vector4 operator *(float f, Vector4 v)\n        {\n            return new Vector4(f * v.x, f * v.y, f * v.z, f * v.w);\n        }\n        public static Vector4 operator *(Vector4 v, float f)\n        {\n            return new Vector4(f * v.x, f * v.y, f * v.z, f * v.w);\n        }\n        public static Vector4 operator /(Vector4 v, float f)\n        {\n            return new Vector4(v.x / f, v.y / f, v.z / f, v.w / f);\n        }\n        public static Vector4 operator /(float f, Vector4 v)\n        {\n            return new Vector4(f / v.x, f / v.y, f / v.z, f / v.w);\n        }\n\n        public static Vector4 operator *(Vector4 a, Vector4 b)\n        {\n            return new Vector4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w);\n        }\n        public static Vector4 operator /(Vector4 a, Vector4 b)\n        {\n            return new Vector4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w);\n        }\n\n\n        public static Vector4 operator +(Vector4 v0, Vector4 v1)\n        {\n            return new Vector4(v0.x + v1.x, v0.y + v1.y, v0.z + v1.z, v0.w + v1.w);\n        }\n        public static Vector4 operator +(Vector4 v0, float f)\n        {\n            return new Vector4(v0.x + f, v0.y + f, v0.z + f, v0.w + f);\n        }\n\n        public static Vector4 operator -(Vector4 v0, Vector4 v1)\n        {\n            return new Vector4(v0.x - v1.x, v0.y - v1.y, v0.z - v1.z, v0.w - v1.w);\n        }\n        public static Vector4 operator -(Vector4 v0, float f)\n        {\n            return new Vector4(v0.x - f, v0.y - f, v0.z - f, v0.w - f);\n        }\n\n\n\n        public static bool operator ==(Vector4 a, Vector4 b)\n        {\n            return (a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w);\n        }\n        public static bool operator !=(Vector4 a, Vector4 b)\n        {\n            return (a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w);\n        }\n        public override bool Equals(object obj)\n        {\n            return this == (Vector4)obj;\n        }\n        public override int GetHashCode()\n        {\n            unchecked // Overflow is fine, just wrap\n            {\n                int hash = (int)2166136261;\n                // Suitable nullity checks etc, of course :)\n                hash = (hash * 16777619) ^ x.GetHashCode();\n                hash = (hash * 16777619) ^ y.GetHashCode();\n                hash = (hash * 16777619) ^ z.GetHashCode();\n                hash = (hash * 16777619) ^ w.GetHashCode();\n                return hash;\n            }\n        }\n        public int CompareTo(Vector4 other)\n        {\n            if (x != other.x)\n                return x < other.x ? -1 : 1;\n            else if (y != other.y)\n                return y < other.y ? -1 : 1;\n            else if (z != other.z)\n                return z < other.z ? -1 : 1;\n            else if (w != other.w)\n                return w < other.w ? -1 : 1;\n            return 0;\n        }\n        public bool Equals(Vector4 other)\n        {\n            return (x == other.x && y == other.y && z == other.z && w == other.w);\n        }\n\n\n        public bool EpsilonEqual(Vector4 v2, float epsilon)\n        {\n            return Math.Abs(x - v2.x) <= epsilon &&\n                   Math.Abs(y - v2.y) <= epsilon &&\n                   Math.Abs(z - v2.z) <= epsilon &&\n                   Math.Abs(w - v2.w) <= epsilon;\n        }\n\n        public static implicit operator Vector4(Vector3 v)\n        {\n            return new Vector4(v.x, v.y, v.z, 0.0f);\n        }\n\n        public static implicit operator Vector3(Vector4 v)\n        {\n            return new Vector3(v.x, v.y, v.z);\n        }\n\n        public static implicit operator Vector4(Vector2 v)\n        {\n            return new Vector4(v.x, v.y, 0.0f, 0.0f);\n        }\n\n        public static implicit operator Vector2(Vector4 v)\n        {\n            return new Vector2(v.x, v.y);\n        }\n\n        public override string ToString()\n        {\n            return string.Format(\"{0:F8} {1:F8} {2:F8} {3:F8}\", x, y, z, w);\n        }\n        public string ToString(string fmt)\n        {\n            return string.Format(\"{0} {1} {2} {3}\", x.ToString(fmt), y.ToString(fmt), z.ToString(fmt), w.ToString(fmt));\n        }\n\n\n\n\n#if G3_USING_UNITY\n        public static implicit operator Vector4(Vector4 v)\n        {\n            return new Vector4(v.x, v.y, v.z, v.w);\n        }\n        public static implicit operator Vector4(Vector4 v)\n        {\n            return new Vector4(v.x, v.y, v.z, v.w);\n        }\n        public static implicit operator Color(Vector4 v)\n        {\n            return new Color(v.x, v.y, v.z, v.w);\n        }\n        public static implicit operator Vector4(Color c)\n        {\n            return new Vector4(c.r, c.g, c.b, c.a);\n        }\n#endif\n\n    }\n}"
  },
  {
    "path": "SGFCore/IPCWork/IPCConfig.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 进程通讯模块。\n * Inter-process communication module.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System.Collections.Generic;\n\nusing SGF.Utils;\n\nnamespace SGF.IPCWork\n{\n\n    public class IPCInfo\n    {\n        public int id;\n        public int port;\n    }\n\n    public class IPCConfig\n    {\n        private readonly static string Path = \"./IPCConfig.json\";\n        private readonly static MapList<int, IPCInfo> MapIPCInfo = new MapList<int, IPCInfo>();\n\n\n        public static IPCInfo GetIPCInfo(int id)\n        {\n            if (MapIPCInfo.Count == 0)\n            {\n                ReadConfig();\n            }\n\n            return MapIPCInfo[id];\n        }\n\n        private static void ReadConfig()\n        {\n            Debuger.Log();\n            string jsonStr = FileUtils.ReadString(Path);\n            var obj = MiniJSON.Safe.Json.Deserialize(jsonStr) as List<object>;\n            for (int i = 0; i < obj.Count; i++)\n            {\n                var infoJson = obj[i] as Dictionary<string, object>;\n                IPCInfo info = new IPCInfo();\n                info.id = (int)(long)infoJson[\"id\"];\n                info.port = (int)(long)infoJson[\"port\"];\n                MapIPCInfo.Add(info.id, info);\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/IPCWork/IPCManager.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 进程通讯模块。\n * 它基于UdpSocket实现，以RPC的方式进行调用。\n * 由于是基于Udp的简单实现，所以对单次通讯的数据大小有要求，不能超过当前系统的MTU。\n * 如果需要在进程间进行大数据通讯，可以使用Network模块，建立可靠UDP连接，或者TCP连接。\n * 当然也可以采用共享内存和管道方案，期待后续有人来完善。\n * Inter-process communication module.\n * It is based on UdpSocket implementation and is called in RPC mode.\n * Since it is based on a simple implementation of Udp, there is a requirement for the data size of a single communication and cannot exceed the MTU of the current system.\n * If you need to perform big data communication between processes, you can use the Network module to establish a reliable UDP connection or a TCP connection.\n * Of course you can also use shared memory and pipeline solutions and look forward to follow-up improvements.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Reflection;\nusing System.Threading;\nusing SGF.Codec;\nusing SGF.Network;\nusing SGF.Network.Core.RPCLite;\nusing SGF.Extension;\n\nnamespace SGF.IPCWork\n{\n    public class IPCManager\n    {\n        private int m_id;\n        private int m_port;\n\n        private Socket m_SystemSocket;\n        private Thread m_ThreadRecv;\n        private byte[] m_RecvBufferTemp = new byte[4096];\n        private Queue<byte[]> m_RecvBufferQueue = new Queue<byte[]>();\n\n        private bool m_IsRunning = false;\n        \n        //RPC\n        private RPCManagerBase m_rpc;\n\n\n        public void Init(int id)\n        {\n            m_id = id;\n            m_port = IPCConfig.GetIPCInfo(id).port;\n\n            m_rpc = new RPCManagerBase();\n            m_rpc.Init();\n\n        }\n\n\n        public void Clean()\n        {\n            Stop();\n\n            if (m_rpc != null)\n            {\n                m_rpc.Clean();\n                m_rpc = null;\n            }\n        }\n\n        public void Dump()\n        {\n            m_rpc.Dump();\n        }\n\n\n        public bool IsRunning { get { return m_IsRunning; } }\n\n        public void Start()\n        {\n            Debuger.Log();\n            try\n            {\n                m_SystemSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\n                m_SystemSocket.Bind(IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, m_port));\n                m_port = (m_SystemSocket.LocalEndPoint as IPEndPoint).Port;\n\n                m_IsRunning = true;\n\n\n                m_ThreadRecv = new Thread(Thread_Recv) { IsBackground = true };\n                m_ThreadRecv.Start();\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(e.Message + e.StackTrace);\n                Stop();\n            }\n\n\n        }\n\n        public void Stop()\n        {\n            Debuger.Log();\n\n            m_IsRunning = false;\n\n            if (m_ThreadRecv != null)\n            {\n                m_ThreadRecv.Interrupt();\n                m_ThreadRecv = null;\n            }\n\n            if (m_SystemSocket != null)\n            {\n                try\n                {\n                    m_SystemSocket.Shutdown(SocketShutdown.Both);\n\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(e.Message + e.StackTrace);\n                }\n\n                m_SystemSocket.Close();\n                m_SystemSocket = null;\n            }\n        }\n\n\n\n        //=================================================================================\n        //发送逻辑\n        //=================================================================================\n        private void SendMessage(int dst, byte[] bytes, int len)\n        {\n\t\t\tm_hasSocketException = false;\n            int dstPort = IPCConfig.GetIPCInfo(dst).port;\n            IPEndPoint ep = IPUtils.GetHostEndPoint(\"127.0.0.1\", dstPort);\n            m_SystemSocket.SendTo(bytes, 0, len, SocketFlags.None, ep);\n        }\n\n\n        //=================================================================================\n        //接收逻辑\n        //=================================================================================\n        private bool m_hasSocketException = false;\n        private void Thread_Recv()\n        {\n            while (m_IsRunning)\n            {\n                try\n                {\n                    DoReceiveInThread();\n\n                    if (m_hasSocketException)\n                    {\n                        m_hasSocketException = false;\n                        Debuger.LogWarning(\"连接异常已经恢复\");\n                    }\n                }\n                catch (SocketException se)\n                {\n                    if (!m_hasSocketException)\n                    {\n                        m_hasSocketException = true;\n                    }\n\n                    Debuger.LogWarning(\"SocketErrorCode:{0}, {1}\", se.SocketErrorCode, se.Message);\n                    Thread.Sleep(1);\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(e.Message + \"\\n\" + e.StackTrace);\n                    Thread.Sleep(1);\n                }\n            }\n\n            Debuger.LogWarning(\"End!\");\n        }\n\n\n        private void DoReceiveInThread()\n        {\n            EndPoint remotePoint = IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, 0);\n            int cnt = m_SystemSocket.ReceiveFrom(m_RecvBufferTemp, m_RecvBufferTemp.Length, SocketFlags.None, ref remotePoint);\n\n            if (cnt > 0)\n            {\n                byte[] dst = new byte[cnt];\n                Buffer.BlockCopy(m_RecvBufferTemp, 0, dst, 0, cnt);\n\n                lock (m_RecvBufferQueue)\n                {\n                    m_RecvBufferQueue.Enqueue(dst);\n                }                \n            }\n        }\n\n\n        private void DoReceiveInMain()\n        {\n            lock (m_RecvBufferQueue)\n            {\n                while (m_RecvBufferQueue.Count > 0)\n                {\n                    byte[] buffer = m_RecvBufferQueue.Dequeue();\n\n                    IPCMessage msg = PBSerializer.NDeserialize<IPCMessage>(buffer);\n\n                    HandleMessage(msg);\n                }\n            }\n        }\n\n\n        public void Tick()\n        {\n            DoReceiveInMain();\n        }\n\n\n\n        //========================================================================\n        //RPC的协议处理方式\n        //========================================================================\n        private string m_currInvokingName;\n        private int m_currInvokingSrc;\n\n\n        public void AddRPCListener(object listener)\n        {\n            m_rpc.RegisterListener(listener);\n        }\n\n        public void RemoveRPCListener(object listener)\n        {\n            m_rpc.UnRegisterListener(listener);\n        }\n\n\n\n        private void HandleMessage(IPCMessage msg)\n        {\n            RPCMessage rpcmsg = msg.rpc;\n\n            Debuger.Log(\"[{0}]-> {1}({2})\", msg.src, rpcmsg.name, rpcmsg.args.ToListString());\n\n            var helper = m_rpc.GetMethodHelper(rpcmsg.name);\n            if (helper != null)\n            {\n                object[] args  = new object[rpcmsg.args.Length +1];\n                List<RPCRawArg> raw_args = rpcmsg.raw_args;\n                ParameterInfo[] paramInfo = helper.method.GetParameters();\n\n                if (args.Length == paramInfo.Length)\n                {\n                    for (int i = 0; i < raw_args.Count; i++)\n                    {\n                        if (raw_args[i].type == RPCArgType.PBObject)\n                        {\n                            args[i + 1] = PBSerializer.NDeserialize(raw_args[i].raw_value, paramInfo[i + 1].ParameterType);\n                        }\n                        else\n                        {\n                            args[i + 1] = raw_args[i].value;\n                        }\n                    }\n\n                    args[0] = msg.src;\n\n                    m_currInvokingName = rpcmsg.name;\n                    m_currInvokingSrc = msg.src;\n\n                    try\n                    {\n                        helper.method.Invoke(helper.listener, BindingFlags.NonPublic, null, args, null);\n                    }\n                    catch (Exception e)\n                    {\n                        Debuger.LogError(\"RPC调用出错：{0}\\n{1}\", e.Message, e.StackTrace);\n                    }\n\n                    m_currInvokingName = \"\";\n                    m_currInvokingSrc = 0;\n\n                }\n                else\n                {\n                    Debuger.LogWarning(\"参数数量不一致！\");\n                }\n\n            }\n            else\n            {\n                Debuger.LogWarning(\"RPC不存在！\");\n            }\n\n        }\n\n\n        public void Return(params object[] args)\n        {\n            var name = \"On\" + m_currInvokingName;\n            Debuger.Log(\"->[{0}] {1}({2})\", m_currInvokingSrc, name, args.ToListString());\n\n            RPCMessage rpcmsg = new RPCMessage();\n            rpcmsg.name = name;\n            rpcmsg.args = args;\n\n            IPCMessage msg = new IPCMessage();\n            msg.src = m_id;\n            msg.rpc = rpcmsg;\n\n\n            byte[] temp = PBSerializer.NSerialize(msg);\n            SendMessage(m_currInvokingSrc, temp, temp.Length);\n        }\n\n\n        public void ReturnError(string errinfo, int errcode = 1)\n        {\n            var name = \"On\" + m_currInvokingName + \"Error\";\n            Debuger.LogWarning(\"->[{0}] {1}({2},{3})\", m_currInvokingSrc, name, errinfo, errcode);\n\n            RPCMessage rpcmsg = new RPCMessage();\n            rpcmsg.name = name;\n            rpcmsg.args = new object[] { errinfo, errcode };\n\n            IPCMessage msg = new IPCMessage();\n            msg.src = m_id;\n            msg.rpc = rpcmsg;\n\n            byte[] temp = PBSerializer.NSerialize(msg);\n            SendMessage(m_currInvokingSrc, temp, temp.Length);\n        }\n\n\n\n\n        public void Invoke(int dst, string name, params object[] args)\n        {\n            Debuger.Log(\"->[{0}] {1}({2})\", dst, name, args.ToListString());\n\n            RPCMessage rpcmsg = new RPCMessage();\n            rpcmsg.name = name;\n            rpcmsg.args = args;\n\n            IPCMessage msg = new IPCMessage();\n            msg.src = m_id;\n            msg.rpc = rpcmsg;\n\n            byte[] temp = PBSerializer.NSerialize(msg);\n            SendMessage(dst, temp, temp.Length);\n        }\n\n\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/IPCWork/IPCMessage.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 进程通讯模块。\n * Inter-process communication module.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing ProtoBuf;\nusing SGF.Network.Core.RPCLite;\n\nnamespace SGF.IPCWork\n{\n    [ProtoContract]\n    public class IPCMessage\n    {\n        [ProtoMember(1)] public int src;//源服务模块ID\n        [ProtoMember(2)] public RPCMessage rpc;\n\n    }\n}"
  },
  {
    "path": "SGFCore/Marshals/MarshalArray.cs",
    "content": "﻿////////////////////////////////////////////////////////////////////\n//                            _ooOoo_                             //\n//                           o8888888o                            //\n//                           88\" . \"88                            //\n//                           (| ^_^ |)                            //\n//                           O\\  =  /O                            //\n//                        ____/`---'\\____                         //\n//                      .'  \\\\|     |//  `.                       //\n//                     /  \\\\|||  :  |||//  \\                      //\n//                    /  _||||| -:- |||||-  \\                     //\n//                    |   | \\\\\\  -  /// |   |                     //\n//                    | \\_|  ''\\---/''  |   |                     //\n//                    \\  .-\\__  `-`  ___/-. /                     //\n//                  ___`. .'  /--.--\\  `. . ___                   //\n//                .\"\" '<  `.___\\_<|>_/___.'  >'\"\".                //\n//              | | :  `- \\`.;`\\ _ /`;.`/ - ` : | |               //\n//              \\  \\ `-.   \\_ __\\ /__ _/   .-` /  /               //\n//        ========`-.____`-.___\\_____/___.-`____.-'========       //\n//                             `=---='                            //\n//        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^      //\n//            佛祖保佑       无BUG        不修改                   //\n////////////////////////////////////////////////////////////////////\n/*\n* 描述：\n* 作者：slicol\n*/\n\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\nnamespace SGF.Marshals\n{\n    public class MarshalArray<T> : MarshalArrayBase, IEnumerable<T>, IEnumerable where T : struct\n    {\n        public MarshalArray(int length) : base(length, typeof(T))\n        {\n        }\n\n        public T this[int index]\n        {\n            get { return GetValue<T>(index); }\n            set { SetValue(index, value); }\n        }\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            return new Enumerator(this);\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return GetEnumerator();\n        }\n\n        struct Enumerator : IEnumerator<T>\n        {\n            private MarshalArray<T> list;\n            private int index;\n            private T current;\n\n            internal Enumerator(MarshalArray<T> list)\n            {\n                this.list = list;\n                this.index = 0;\n                this.current = default(T);\n            }\n\n            public void Dispose() { }\n\n            public bool MoveNext()\n            {\n                MarshalArray<T> list = this.list;\n\n                if ((uint)this.index >= (uint)list.Length)\n                {\n                    this.index = this.list.Length + 1;\n                    this.current = default(T);\n                    return false;\n                }\n\n                this.current = list[this.index];\n                ++this.index;\n                return true;\n            }\n\n            public T Current { get { return this.current; } }\n\n            object IEnumerator.Current\n            {\n                get\n                {\n                    if (this.index == 0 || this.index == this.list.Length + 1)\n                    {\n                        throw new InvalidOperationException(\"InvalidOperation_EnumOpCantHappen\");\n                    }\n                    return (object)this.Current;\n                }\n            }\n\n            void IEnumerator.Reset()\n            {\n                this.index = 0;\n                this.current = default(T);\n            }\n        }\n    }\n\n\n    public abstract class MarshalArrayBase : IDisposable\n    {\n        public static long TotalMemory { get; private set; }\n        private static readonly List<IDisposable> ms_cache = new List<IDisposable>();\n\n        [MethodImpl(MethodImplOptions.Synchronized)]\n        public static void Cleanup()\n        {\n            foreach (var item in ms_cache)\n            {\n                item.Dispose();\n            }\n            ms_cache.Clear();\n        }\n\n        protected IntPtr m_header;\n        protected int m_length;\n        protected int m_elementSize;\n        protected bool m_disposed = false;\n        protected Type m_elementType;\n\n        [MethodImpl(MethodImplOptions.Synchronized)]\n        protected MarshalArrayBase(int length, Type type)\n        {\n            m_length = length;\n            m_elementType = type;\n            m_elementSize = Marshal.SizeOf(m_elementType);\n\n            int memSize = m_length * m_elementSize;\n            m_header = Marshal.AllocHGlobal(memSize);\n            TotalMemory += memSize;\n            ms_cache.Add(this);\n        }\n\n        ~MarshalArrayBase()\n        {\n            Dispose();\n        }\n\n        protected void Dispose(bool disposing)\n        {\n            if (m_disposed)\n            {\n                return;\n            }\n\n            if (m_header != IntPtr.Zero)\n            {\n                TotalMemory -= m_length * m_elementSize;\n                Marshal.FreeHGlobal(m_header);\n                m_length = 0;\n                m_header = IntPtr.Zero;\n            }\n\n            m_disposed = true;\n        }\n\n        public void Dispose()\n        {\n            this.Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        public int Length { get { return m_length; } }\n        public int ElementSize { get { return m_elementSize; } }\n        public Type ElementType { get { return m_elementType; } }\n        public int ByteLength { get { return m_length * m_elementSize; } }\n\n        public unsafe void* Pointer { get { return (void*)m_header; } }\n        public IntPtr Ptr { get { return m_header; } }\n        public unsafe void* GetElementPointer(int index)\n        {\n            return (void*)((byte*)m_header + index * m_elementSize);\n        }\n        public unsafe IntPtr GetElementPtr(int index)\n        {\n            return (IntPtr)((byte*)m_header + index * m_elementSize);\n        }\n\n        public unsafe T GetValue<T>(int index)\n        {\n            if (index < 0 || index >= m_length)\n            {\n                throw new IndexOutOfRangeException(\"index is out of range\");\n            }\n\n            var ptrSrc = ((byte*)m_header + index * m_elementSize);\n            return (T)Marshal.PtrToStructure((IntPtr) ptrSrc, m_elementType);\n        }\n        public unsafe void SetValue<T>(int index, T value)\n        {\n            if (index < 0 || index >= m_length)\n            {\n                throw new IndexOutOfRangeException(\"index is out of range\");\n            }\n\n            var ptrSrc = ((byte*)m_header + index * m_elementSize);\n            Marshal.StructureToPtr(value, (IntPtr)ptrSrc, true);\n        }\n\n        public static int IndexOf<T>(MarshalArrayBase source, T item, int beginIndex, int count)\n        {\n            if (beginIndex < 0 || count < 0)\n            {\n                throw new ArgumentException(\"beginIndex < 0 or count < 0\");\n            }\n\n            if (source.Length - beginIndex < count)\n            {\n                count = source.Length - beginIndex;\n            }\n\n            int end = beginIndex + count;\n            int i = beginIndex;\n            while (i < end)\n            {\n                if (source.GetValue<T>(i).Equals(item))\n                {\n                    return i;\n                }\n                ++i;\n            }\n\n            return -1;\n        }\n\n        public static int LastIndexOf<T>(MarshalArrayBase source, T item, int beginIndex, int count)\n        {\n            if (beginIndex < 0 || count < 0)\n            {\n                throw new ArgumentException(\"beginIndex < 0 or count < 0\");\n            }\n\n            if (beginIndex >= source.Length)\n            {\n                beginIndex = source.Length - 1;\n            }\n\n            if (beginIndex + 1 < count)\n            {\n                count = beginIndex + 1;\n            }\n\n            int end = beginIndex - count;\n            int i = beginIndex;\n            while (i > end)\n            {\n                if (source.GetValue<T>(i).Equals(item))\n                {\n                    return i;\n                }\n                --i;\n            }\n\n            return -1;\n        }\n\n        public static int Copy<T>(MarshalArrayBase source, int sourceOffset, T[] destination, int destOffset, int count)\n        {\n            if (sourceOffset < 0 || destOffset < 0 || count < 0)\n            {\n                throw new ArgumentException(\"sourceOffset < 0 or destOffset < 0 or count < 0\");\n            }\n\n            if (source.Length - sourceOffset < count)\n            {\n                count = source.Length - sourceOffset;\n            }\n\n            if (destination.Length - destOffset < count)\n            {\n                count = destination.Length - destOffset;\n            }\n\n            int srcIndex = sourceOffset;\n            int dstIndex = destOffset;\n            int srcEnd = sourceOffset + count;\n            while (srcIndex < srcEnd)\n            {\n                destination[dstIndex] = source.GetValue<T>(srcIndex);\n                ++dstIndex;\n                ++srcIndex;\n            }\n            return count;\n        }\n\n        public static int Copy<T>(T[] source, int sourceOffset, MarshalArrayBase destination, int destOffset, int count)\n        {\n            if (sourceOffset < 0 || destOffset < 0 || count < 0)\n            {\n                throw new ArgumentException(\"sourceOffset < 0 or destOffset < 0 or count < 0\");\n            }\n\n            if (source.Length - sourceOffset < count)\n            {\n                count = source.Length - sourceOffset;\n            }\n\n            if (destination.Length - destOffset < count)\n            {\n                count = destination.Length - destOffset;\n            }\n\n            int srcIndex = sourceOffset;\n            int dstIndex = destOffset;\n            int srcEnd = sourceOffset + count;\n            while (srcIndex < srcEnd)\n            {\n                destination.SetValue<T>(dstIndex, source[srcIndex]);\n                ++dstIndex;\n                ++srcIndex;\n            }\n            return count;\n        }\n\n        public unsafe static int Copy(MarshalArrayBase source, int sourceOffset, MarshalArrayBase destination, int destOffset, int count)\n        {\n            if (sourceOffset < 0 || destOffset < 0 || count < 0)\n            {\n                throw new ArgumentException(\"sourceOffset < 0 or destOffset < 0 or count < 0\");\n            }\n\n            if (source.Length - sourceOffset < count)\n            {\n                count = source.Length - sourceOffset;\n            }\n\n            if (destination.Length - destOffset < count)\n            {\n                count = destination.Length - destOffset;\n            }\n\n\n            return CopyBytes(source.Ptr, source.m_elementSize * sourceOffset,\n                destination.Ptr, destination.m_elementSize * destOffset,\n                source.m_elementSize * count);\n\n\n        }\n\n        public unsafe static int CopyBytes(IntPtr source, int sourceOffset, IntPtr destination, int destOffset, int count)\n        {\n            if (source == IntPtr.Zero)\n            {\n                throw new ArgumentException(\"source is null!\");\n            }\n            if (destination == IntPtr.Zero)\n            {\n                throw new ArgumentException(\"destination is null\");\n            }\n            if (sourceOffset < 0 || destOffset < 0 || count < 0)\n            {\n                throw new ArgumentException(\"sourceOffset < 0 or destOffset < 0 or count < 0\");\n            }\n\n            if (count == 0)\n            {\n                return 0;\n            }\n\n            byte* srcPtr = (byte*)source;\n            srcPtr += sourceOffset;\n\n            byte* dstPtr = (byte*)destination;\n            dstPtr += destOffset;\n\n            if (srcPtr == dstPtr)\n            {\n                return count;\n            }\n\n            int byteSize = count;\n\n            if (source != destination || srcPtr > dstPtr)\n            {\n                byte* srcEnd = srcPtr + byteSize;\n\n                while (srcPtr < srcEnd)\n                {\n                    *dstPtr = *srcPtr;\n                    ++srcPtr;\n                    ++dstPtr;\n                }\n            }\n            else\n            {\n                byte* srcEnd = srcPtr - 1;\n                srcPtr = srcPtr + byteSize - 1;\n                dstPtr = dstPtr + byteSize - 1;\n\n                while (srcPtr > srcEnd)\n                {\n                    *dstPtr = *srcPtr;\n                    --srcPtr;\n                    --dstPtr;\n                }\n            }\n\n            return count;\n\n        }\n\n    }\n\n\n\n}"
  },
  {
    "path": "SGFCore/Marshals/MarshalList.cs",
    "content": "﻿//参照System.Collections.Generic.List实现的\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Threading;\nusing SGF.Utils;\n\n\nnamespace SGF.Marshals\n{\n    public unsafe class MarshalList<T> : IList<T>, IList, IDisposable where T : struct\n    {\n        private MarshalArray<T> m_items;\n        private int m_size;\n        private int m_version;\n        private object m_syncRoot;\n\n        public MarshalList()\n        {\n            this.m_items = new MarshalArray<T>(4);\n        }\n\n        public MarshalList(int capacity)\n        {\n            if (capacity < 0)\n            {\n                throw new ArgumentException(\"CapacityStep不能小于0！\");\n            }\n\n            this.m_items = new MarshalArray<T>(capacity);\n        }\n\n        public void Dispose()\n        {\n            m_items.Dispose();\n        }\n\n        public int Capacity\n        {\n            get\n            {\n                return m_items.Length;\n            }\n            set\n            {\n                if (value == m_items.Length) return;\n\n                if (value < this.m_size)\n                {\n                    throw new ArgumentException(\"新的Capacity不能小于已有数据长度！\");\n                }\n\n                if (value > 0)\n                {\n                    var objArray = new MarshalArray<T>(value);\n                    if (this.m_size > 0) MarshalArrayBase.Copy(this.m_items, 0, objArray, 0, this.m_size);\n                    m_items.Dispose();\n\n                    this.m_items = objArray;\n                }\n                else\n                {\n                    m_items.Dispose();\n                    this.m_items = new MarshalArray<T>(4);\n                }\n            }\n        }\n\n        public int Count { get { return this.m_size; } }\n\n        private void EnsureCapacity(int min)\n        {\n            if (this.m_items.Length >= min)\n                return;\n            int num = this.m_items.Length == 0 ? 4 : this.m_items.Length * 2;\n            if (num < min)\n                num = min;\n            this.Capacity = num;\n        }\n        public void TrimExcess()\n        {\n            if (this.m_size >= (int)((double)this.m_items.Length * 0.9))\n            {\n                return;\n            }\n\n            this.Capacity = this.m_size;\n        }\n\n\n        #region ////IList////\n\n        bool IList.IsFixedSize { get { return false; } }\n        bool IList.IsReadOnly { get { return false; } }\n        object IList.this[int index]\n        {\n            get\n            {\n                return (object)this[index];\n            }\n            set\n            {\n                VerifyValueType(value);\n                this[index] = (T)value;\n            }\n        }\n        int IList.Add(object item)\n        {\n            VerifyValueType(item);\n            this.Add((T)item);\n            return this.Count - 1;\n        }\n        bool IList.Contains(object item)\n        {\n            if (IsCompatibleObject(item))\n                return this.Contains((T)item);\n            return false;\n        }\n        int IList.IndexOf(object item)\n        {\n            if (IsCompatibleObject(item))\n                return this.IndexOf((T)item);\n            return -1;\n        }\n        void IList.Insert(int index, object item)\n        {\n            VerifyValueType(item);\n            this.Insert(index, (T)item);\n        }\n        void IList.Remove(object item)\n        {\n            if (!IsCompatibleObject(item))\n                return;\n            this.Remove((T)item);\n        }\n\n        #endregion\n\n        #region ////ICollection////\n        bool ICollection<T>.IsReadOnly { get { return false; } }\n        bool ICollection.IsSynchronized { get { return false; } }\n        object ICollection.SyncRoot\n        {\n            get\n            {\n                if (this.m_syncRoot == null)\n                    Interlocked.CompareExchange(ref this.m_syncRoot, new object(), (object)null);\n                return this.m_syncRoot;\n            }\n        }\n        #endregion\n\n        #region ////IEnumerator////\n        public IEnumerator<T> GetEnumerator()\n        {\n            return new Enumerator(this);\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return new Enumerator(this);\n        }\n        #endregion\n\n        #region ////取值////\n\n        public T this[int index]\n        {\n            get\n            {\n                if ((uint)index >= (uint)this.m_size)\n                {\n                    ThrowHelper.ThrowArgumentOutOfRangeException();\n                }\n\n                return this.m_items[index];\n            }\n            set\n            {\n                if ((uint)index >= (uint)this.m_size)\n                {\n                    ThrowHelper.ThrowArgumentOutOfRangeException();\n                }\n\n                this.m_items[index] = value;\n                ++this.m_version;\n            }\n        }\n        public MarshalList<T> GetRange(int index, int count)\n        {\n            if (index < 0 || count < 0)\n            {\n                ThrowHelper.ThrowArgumentOutOfRangeException(\n                    index < 0 ? ExceptionArgument.index : ExceptionArgument.count,\n                    ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);\n            }\n\n            if (this.m_size - index < count)\n            {\n                ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);\n            }\n\n            MarshalList<T> objList = new MarshalList<T>(count);\n            MarshalArrayBase.Copy(this.m_items, index, objList.m_items, 0, count);\n            objList.m_size = count;\n            return objList;\n        }\n        public T[] ToArray()\n        {\n            T[] objArray = new T[this.m_size];\n            MarshalArrayBase.Copy(this.m_items, 0, objArray, 0, this.m_size);\n            return objArray;\n        }\n        public bool Contains(T item)\n        {\n            EqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;\n            for (int index = 0; index < this.m_size; ++index)\n            {\n                if (equalityComparer.Equals(this.m_items[index], item))\n                    return true;\n            }\n            return false;\n        }\n\n\n        #endregion\n\n        #region ////Add/Insert////\n\n        public void Add(T item)\n        {\n            if (this.m_size == this.m_items.Length)\n            {\n                this.EnsureCapacity(this.m_size + 1);\n            }\n\n            this.m_items[this.m_size++] = item;\n            ++this.m_version;\n        }\n        public void AddRange(IEnumerable<T> collection)\n        {\n            this.InsertRange(this.m_size, collection);\n        }\n\n\n        public void Insert(int index, T item)\n        {\n            if ((uint)index > (uint)this.m_size)\n                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);\n            if (this.m_size == this.m_items.Length)\n                this.EnsureCapacity(this.m_size + 1);\n            if (index < this.m_size)\n                MarshalArrayBase.Copy(this.m_items, index, this.m_items, index + 1, this.m_size - index);\n            this.m_items[index] = item;\n            ++this.m_size;\n            ++this.m_version;\n        }\n        public void InsertRange(int index, IEnumerable<T> collection)\n        {\n            if (collection == null)\n                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);\n            if ((uint)index > (uint)this.m_size)\n                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);\n            ICollection<T> objs = collection as ICollection<T>;\n            if (objs != null)\n            {\n                int count = objs.Count;\n                if (count > 0)\n                {\n                    this.EnsureCapacity(this.m_size + count);\n                    if (index < this.m_size)\n                        MarshalArrayBase.Copy(this.m_items, index, this.m_items, index + count, this.m_size - index);\n                    if (this == objs)\n                    {\n                        MarshalArrayBase.Copy(this.m_items, 0, this.m_items, index, index);\n                        MarshalArrayBase.Copy(this.m_items, index + count, this.m_items, index * 2, this.m_size - index);\n                    }\n                    else\n                    {\n                        T[] array = new T[count];\n                        objs.CopyTo(array, 0);\n                        MarshalArrayBase.Copy<T>(array, 0, m_items, index, count);\n                    }\n                    this.m_size += count;\n                }\n            }\n            else\n            {\n                foreach (T obj in collection)\n                {\n                    this.Insert(index++, obj);\n                }\n            }\n            ++this.m_version;\n        }\n\n        #endregion\n\n        #region ////Remove/Clear////\n\n\n        public bool Remove(T item)\n        {\n            int index = this.IndexOf(item);\n            if (index < 0)\n                return false;\n            this.RemoveAt(index);\n            return true;\n        }\n        public void RemoveAt(int index)\n        {\n            if ((uint)index >= (uint)this.m_size)\n                ThrowHelper.ThrowArgumentOutOfRangeException();\n            --this.m_size;\n            if (index < this.m_size)\n                MarshalArrayBase.Copy(this.m_items, index + 1, this.m_items, index, this.m_size - index);\n            this.m_items[this.m_size] = default(T);\n            ++this.m_version;\n        }\n        public void RemoveRange(int index, int count)\n        {\n            if (index < 0 || count < 0)\n                ThrowHelper.ThrowArgumentOutOfRangeException(index < 0 ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);\n            if (this.m_size - index < count)\n                ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);\n            if (count <= 0)\n                return;\n            this.m_size -= count;\n            if (index < this.m_size)\n                MarshalArrayBase.Copy(this.m_items, index + count, this.m_items, index, this.m_size - index);\n\n            //MarshalArrayBase.Clear(this.m_items, this.m_size, count);\n\n            ++this.m_version;\n        }\n        public void Clear()\n        {\n            //因为是值类型，且非托管\n            this.m_size = 0;\n            ++this.m_version;\n        }\n\n\n\n        #endregion\n\n        #region ////CopyTo////\n\n        public void CopyTo(T[] array, int arrayIndex)\n        {\n            MarshalArrayBase.Copy<T>(this.m_items, 0, array, arrayIndex, this.m_size);\n        }\n        public void CopyTo(Array array, int index)\n        {\n            MarshalArrayBase.Copy(this.m_items, 0, (T[])array, index, this.m_size);\n        }\n        public void CopyTo(MarshalArray<T> array)\n        {\n            this.CopyTo(array, 0);\n        }\n        public void CopyTo(int index, MarshalArray<T> array, int arrayIndex, int count)\n        {\n            if (this.m_size - index < count)\n            {\n                ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);\n            }\n            MarshalArrayBase.Copy(this.m_items, index, array, arrayIndex, count);\n        }\n        public void CopyTo(MarshalArray<T> array, int arrayIndex)\n        {\n            MarshalArrayBase.Copy(this.m_items, 0, array, arrayIndex, this.m_size);\n        }\n\n\n        #endregion\n\n        #region ////IndexOf////\n\n        public int IndexOf(T item)\n        {\n            return MarshalArrayBase.IndexOf<T>(this.m_items, item, 0, this.m_size);\n        }\n        public int IndexOf(T item, int index)\n        {\n            if (index > this.m_size)\n                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);\n            return MarshalArrayBase.IndexOf<T>(this.m_items, item, index, this.m_size - index);\n        }\n        public int IndexOf(T item, int index, int count)\n        {\n            if (index > this.m_size)\n                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);\n            if (count < 0 || index > this.m_size - count)\n                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);\n            return MarshalArrayBase.IndexOf<T>(this.m_items, item, index, count);\n        }\n        public int LastIndexOf(T item)\n        {\n            return this.LastIndexOf(item, this.m_size - 1, this.m_size);\n        }\n        public int LastIndexOf(T item, int index)\n        {\n            if (index >= this.m_size)\n                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);\n            return this.LastIndexOf(item, index, index + 1);\n        }\n        public int LastIndexOf(T item, int index, int count)\n        {\n            if (this.m_size == 0)\n                return -1;\n            if (index < 0 || count < 0)\n                ThrowHelper.ThrowArgumentOutOfRangeException(index < 0 ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);\n            if (index >= this.m_size || count > index + 1)\n                ThrowHelper.ThrowArgumentOutOfRangeException(index >= this.m_size ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection);\n            return MarshalArrayBase.LastIndexOf<T>(this.m_items, item, index, count);\n        }\n\n\n        #endregion\n\n\n        //--------------------------------------------------------------------\n        #region ////工具函数////\n        //--------------------------------------------------------------------\n\n        private static bool IsCompatibleObject(object value)\n        {\n            return value is T || value == null && !typeof(T).IsValueType;\n        }\n\n        private static void VerifyValueType(object value)\n        {\n            if (IsCompatibleObject(value))\n                return;\n            ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));\n        }\n        #endregion\n\n\n        //--------------------------------------------------------------------\n        //枚举器\n        //--------------------------------------------------------------------\n        struct Enumerator : IEnumerator<T>\n        {\n            private MarshalList<T> list;\n            private int index;\n            private int version;\n            private T current;\n\n            internal Enumerator(MarshalList<T> list)\n            {\n                this.list = list;\n                this.index = 0;\n                this.version = list.m_version;\n                this.current = default(T);\n            }\n\n\n            public void Dispose()\n            {\n            }\n\n\n            public bool MoveNext()\n            {\n                MarshalList<T> list = this.list;\n\n                if (this.version != list.m_version || (uint)this.index >= (uint)list.m_size)\n                {\n                    return this.MoveNextRare();\n                }\n\n                this.current = list.m_items[this.index];\n                ++this.index;\n                return true;\n            }\n\n            private bool MoveNextRare()\n            {\n                if (this.version != this.list.m_version)\n                {\n                    ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);\n                }\n\n                this.index = this.list.m_size + 1;\n                this.current = default(T);\n                return false;\n            }\n\n\n            public T Current { get { return this.current; } }\n\n            object IEnumerator.Current\n            {\n                get\n                {\n                    if (this.index == 0 || this.index == this.list.m_size + 1)\n                    {\n                        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);\n                    }\n                    return (object)this.Current;\n                }\n            }\n\n            void IEnumerator.Reset()\n            {\n                if (this.version != this.list.m_version)\n                {\n                    ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);\n                }\n                this.index = 0;\n                this.current = default(T);\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/MathLite/SGFRandom.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 基于LCG的随机数生成算法\n * https://en.wikipedia.org/wiki/Linear_congruential_generator\n * https://stackoverflow.com/questions/4768180/rand-implementation\n * LCG-based random number generation algorithm\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nnamespace SGF.MathLite\n{\n    public class SGFRandom\n    {\n        #region 默认实例\n        public static SGFRandom Default = new SGFRandom();\n        #endregion\n\n        #region 线性同余参数\n\n        //线性同余随机数生成算法\n        private const int PrimeA = 214013;\n        private const int PrimeB = 2531011;        \n\n        #endregion\n\n        //归一化\n        private const float Mask15Bit_1 = 1.0f / 0x7fff;\n        private const int Mask15Bit = 0x7fff;\n\n        private int m_Value = 0;\n\n        public int Seed\n        {\n            set { m_Value = value; }\n            get { return m_Value; }\n        }\n\n        /// <summary>\n        /// 采用线性同余算法产生一个0~1之间的随机小数\n        /// </summary>\n        /// <returns></returns>\n        public float Rnd()\n        {\n            float val = ((((m_Value = m_Value * PrimeA + PrimeB) >> 16) & Mask15Bit) - 1) * Mask15Bit_1;\n            return (val > 0.99999f ? 0.99999f : val);\n        }\n\n        public float Range(float min, float max)\n        {\n            return min + Rnd() * (max - min);\n        }\n\n        public int Range(int min, int max)\n        {\n            return (int)(min + Rnd() * (max - min));\n        }\n\n\n        public float Range(float max)\n        {\n            return Range(0, max);\n        }\n\n        public int Range(int max)\n        {\n            return Range(0, max);\n        }\n\n\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/Module/GeneralModule.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 模块管理器\n * Module Manager.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System.Reflection;\n\nnamespace SGF.Module\n{\n    public class GeneralModule:ModuleBase, ILogTag\n    {\n        private string m_name = \"\";\n        public string Name { get { return m_name; } }\n\n        public string Title;\n\n        public GeneralModule()\n        {\n            m_name = this.GetType().Name;\n            LOG_TAG = m_name;\n        }\n\n\n        /// <summary>\n        /// 调用它以创建模块\n        /// </summary>\n        /// <param name=\"args\"></param>\n        public virtual void Create(object args = null)\n        {\n            this.Log(\"args:{0}\", args);\n\n            \n        }\n\n        /// <summary>\n        /// 调用它以释放模块\n        /// </summary>\n        public override void Release()\n        {\n            base.Release();\n            this.Log();\n        }\n\n\n        /// <summary>\n        /// 当模块收到消息后，对消息进行一些处理\n        /// </summary>\n        /// <param name=\"msg\"></param>\n        /// <param name=\"args\"></param>\n        internal void HandleMessage(string msg, object[] args)\n        {\n            this.Log(\"msg:{0}, args:{1}\", msg, args);\n\n            var mi = this.GetType()\n                .GetMethod(msg, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);\n            if (mi != null)\n            {\n                mi.Invoke(this, BindingFlags.NonPublic, null, args, null);\n            }\n            else\n            {\n                OnModuleMessage(msg, args);\n            }\n\n        }\n\n\n        /// <summary>\n        /// 由派生类去实现，用于处理消息\n        /// </summary>\n        /// <param name=\"msg\"></param>\n        /// <param name=\"args\"></param>\n        protected virtual void OnModuleMessage(string msg, object[] args)\n        {\n            this.Log(\"msg:{0}, args{1}\", msg, args);\n\n        }\n\n\n        protected virtual void Show(object arg)\n        {\n            this.Log(\"args:{0}\", arg);\n        }\n\n\n        public string LOG_TAG { get; protected set; }\n    }\n}"
  },
  {
    "path": "SGFCore/Module/IModuleActivator.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 模块管理器。\n * Module Manager.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nnamespace SGF.Module\n{\n    public interface IModuleActivator\n    {\n        GeneralModule CreateInstance(string moduleName);\n\n    }\n}"
  },
  {
    "path": "SGFCore/Module/ModuleBase.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 模块管理器。\n * Module Manager.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nnamespace SGF.Module\n{\n    public abstract class ModuleBase\n    {\n        public virtual void Release()\n        {\n            \n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Module/ModuleManager.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 模块管理器。\n * 当项目的规模足够大时，就需要将整个系统划分为若干个模块。\n * 这些模块需要一套系统进行管理。\n * 它具备很好的扩展性，结合ILRuntime可以实现iOS版本中模块级别的热更新。\n * 它实现了模块间的消息通讯，并以此来解耦。\n * Module Manager.\n * When the size of the project is large enough, the entire system needs to be divided into several modules. \n * These modules require a system to manage.\n * It is very extensible, combined with ILRuntime can achieve module-level hot updates in the iOS version.\n * It implements message communication between modules and decouples it.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\n\nusing SGF.Utils;\n\nnamespace SGF.Module\n{\n    public class ModuleManager:Singleton<ModuleManager>\n    {\n        class MessageObject\n        {\n            public string msg;\n            public object[] args;\n        }\n\n        private Dictionary<string, GeneralModule> m_mapModules;\n\n        private Dictionary<string, List<MessageObject>> m_mapCacheMessage;\n\n        private List<IModuleActivator> m_listModuleActivators;\n\n\n        public ModuleManager()\n        {\n            m_mapModules = new Dictionary<string, GeneralModule>();\n            m_mapCacheMessage = new Dictionary<string, List<MessageObject>>();\n            m_listModuleActivators = new List<IModuleActivator>();\n        }\n\n        public void Init()\n        {\n            Debuger.Log();\n        }\n\n\n        public void Clean()\n        {\n            Debuger.Log();\n\n            m_mapCacheMessage.Clear();\n\n            foreach (var pair in m_mapModules)\n            {\n                pair.Value.Release();\n            }\n            m_mapModules.Clear();\n\n            m_listModuleActivators.Clear();\n        }\n\n\n        public void RegisterModuleActivator(IModuleActivator activator)\n        {\n            if (!m_listModuleActivators.Contains(activator))\n            {\n                m_listModuleActivators.Add(activator);\n            }\n            \n        }\n\n\n        public GeneralModule CreateModule(string name, object args = null)\n        {\n            Debuger.Log(\"name = \" + name + \", args = \" + args);\n\n            if (HasModule(name))\n            {\n                Debuger.LogError(\"The Module<{0}> Has Existed!\");\n                return null;\n            }\n\n            GeneralModule module = null;\n\n            for (int i = 0; i < m_listModuleActivators.Count; i++)\n            {\n                module = m_listModuleActivators[i].CreateInstance(name);\n                if (module != null)\n                {\n                    break;\n                }\n            }\n            \n\n            if (module == null)\n            {\n                Debuger.LogError(\"模块实例化失败!\");\n                return null;\n            }\n\n            m_mapModules.Add(name, module);\n            module.Create(args);\n\n            //处理缓存的消息\n            if (m_mapCacheMessage.ContainsKey(name))\n            {\n                List<MessageObject> list = m_mapCacheMessage[name];\n                for (int i = 0; i < list.Count; i++)\n                {\n                    MessageObject msgobj = list[i];\n                    module.HandleMessage(msgobj.msg, msgobj.args);\n                }\n                m_mapCacheMessage.Remove(name);\n            }\n\n            return module;\n        }\n\n\n        public bool HasModule(string name)\n        {\n            return m_mapModules.ContainsKey(name);\n        }\n\n        public GeneralModule GetModule(string name)\n        {\n            GeneralModule module = null;\n            m_mapModules.TryGetValue(name, out module);\n            return module;\n        }\n\n\n\n        //============================================================================\n        //消息机制\n        //============================================================================\n\n        public void SendMessage(string target, string msg, params object[] args)\n        {\n            GeneralModule module = GetModule(target);\n            if (module != null)\n            {\n                module.HandleMessage(msg, args);\n            }\n            else\n            {\n                var list = GetCacheMessageList(target);\n                MessageObject obj = new MessageObject();\n                obj.msg = msg;\n                obj.args = args;\n                list.Add(obj);\n                \n            }\n        }\n\n        private List<MessageObject> GetCacheMessageList(string target)\n        {\n            List<MessageObject> list = null;\n            if (!m_mapCacheMessage.TryGetValue(target, out list))\n            {\n                list = new List<MessageObject>();\n                m_mapCacheMessage.Add(target, list);\n            }\n\n            return list;\n        }\n\n\n        public void ShowModule(string target, object arg = null)\n        {\n            SendMessage(target, \"Show\", arg);\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Module/NativeModuleActivator.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 模块管理器。\n * Module Manager.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\n\n\nnamespace SGF.Module\n{\n    public class NativeModuleActivator:IModuleActivator\n    {\n        private string m_namespace = \"\";\n        private string m_assemblyName = \"\";\n\n\n        public NativeModuleActivator(string _namespace, string assemblyName)\n        {\n            m_namespace = _namespace;\n            m_assemblyName = assemblyName;\n        }\n\n\n        public GeneralModule CreateInstance(string moduleName)\n        {\n            var fullname = m_namespace + \".\" + moduleName;\n\n            var type = Type.GetType(fullname + \",\" + m_assemblyName);\n            if (type != null)\n            {\n                return Activator.CreateInstance(type) as GeneralModule;\n            }\n\n            return null;\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/MvvmLite/MvvmBinding.cs",
    "content": "﻿using SGF.SEvent;\nusing SGF.Timers;\nusing SGF.Utils;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\n\nnamespace SGF.MvvmLite\n{\n    public class MvvmBinding : IDisposable\n    {\n        //====================================================================\n        #region ////MvvmBinding Async////\n        private static Timer m_timerAsync;\n        private static List<Binder> m_listAsyncBinders = new List<Binder>();\n\n        private static void PumpAsyncBinder(Binder binder)\n        {\n            m_listAsyncBinders.Add(binder);\n            PumpAsync();\n        }\n        \n        private static void PumpAsync()\n        {\n            if(m_timerAsync == null)\n            {\n                m_timerAsync = new Timer();\n                m_timerAsync.Interval = 1;\n                m_timerAsync.AutoReset = false;\n                m_timerAsync.Elapsed += (sender, e) => TickAsync();\n            }\n\n            m_timerAsync.Enabled = true;\n        }\n\n        private static void TickAsync()\n        {\n            var binders = m_listAsyncBinders.ToArray();\n            m_listAsyncBinders.Clear();\n\n            for (int i = 0; i < binders.Length; ++i)\n            {\n                binders[i].Validate();\n            }\n        }\n\n\n        #endregion\n        //====================================================================\n\n        class Binder\n        {\n            private object target;\n            public string src;\n            private FieldInfo field;\n            private PropertyInfo property;\n            public Signal<object> onValidate = new Signal<object>();\n\n\n            public Binder(object target, string src,  MemberInfo  member)\n            {\n                this.target = target;\n                this.src = src;\n                this.field = member as FieldInfo;\n                this.property = member as PropertyInfo;\n            }\n\n            public void Validate()\n            {\n                object value = null;\n                if (field != null)\n                {\n                    value = field.GetValue(target);\n                }\n                else if(property != null)\n                {\n                    value = property.GetValue(target, null);\n                }\n                onValidate.InvokeSafe(value);\n            }\n\n            public void Clear()\n            {\n                target = null;\n                field = null;\n                property = null;\n                onValidate.RemoveAllListeners();\n            }\n            \n        }\n\n        //====================================================================\n        private bool m_disposed = false;\n        private DictionarySafe<string, Binder> m_binders = new DictionarySafe<string, Binder>();\n\n        public MvvmBinding()\n        {\n\n        }\n\n        ~MvvmBinding()\n        {\n            Dispose();\n        }\n\n        public void Dispose()\n        {\n            if (m_disposed) return;\n            m_disposed = true;\n\n            foreach (var pair in m_binders)\n            {\n                pair.Value.Clear();\n            }\n            m_binders.Clear();\n        }\n        \n\n        protected void Validate(string src)\n        {\n            var binder = m_binders[src];\n            if (binder != null)\n            {\n                binder.Validate();\n            }\n        }\n\n        protected void ValidateAsync(string src)\n        {\n            var binder = m_binders[src];\n            if (binder != null)\n            {\n                PumpAsyncBinder(binder);\n            }\n        }\n\n\n        private MemberInfo GetMemberInfo(string src)\n        {\n            var members = this.GetType().GetMembers();\n            for (int i = 0; i < members.Length; ++i)\n            {\n                var m = members[i];\n                if (m.Name == src)\n                {\n                    return m;\n                }\n            }\n            return null;\n        }\n\n        public void Bind(string src, Action<object> handler)\n        {\n            var binder = m_binders[src];\n            if (binder == null)\n            {\n                var member = GetMemberInfo(src);\n                if(member == null)\n                {\n                    Debuger.LogError(\"Bind Error, Member Not Exist: {0}\", src);\n                    return;\n                }\n\n                binder = new Binder(this, src, member);                \n                m_binders.Add(src, binder);\n            }\n            binder.onValidate.AddListener(handler);\n        }\n\n\n\n\n\n        public void UnBind(string src, Action<object> handler)\n        {\n            var binder = m_binders[src];\n            if (binder == null)\n            {\n                return;\n            }\n            binder.onValidate.RemoveListener(handler);\n        }\n\n\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/MvvmLite/MvvmCommand.cs",
    "content": "﻿using SGF.Timers;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SGF.MvvmLite\n{\n    public abstract class MvvmCommandBase\n    {\n        //====================================================================\n        #region ////MvvmCommand Async////\n        private static Timer m_timerAsync;\n        private static List<MvvmCommandBase> m_listAsyncCmds = new List<MvvmCommandBase>();\n        \n        protected static void PumpAsyncCommand(MvvmCommandBase cmd)\n        {\n            m_listAsyncCmds.Add(cmd);\n            PumpAsync();\n        }\n\n        private static void PumpAsync()\n        {\n            if (m_timerAsync == null)\n            {\n                m_timerAsync = new Timer();\n                m_timerAsync.Interval = 1;\n                m_timerAsync.AutoReset = false;\n                m_timerAsync.Elapsed += (sender, e) => TickAsync();\n            }\n\n            m_timerAsync.Enabled = true;\n        }\n\n        private static void TickAsync()\n        {\n            var cmds = m_listAsyncCmds.ToArray();\n            m_listAsyncCmds.Clear();\n\n            for (int i = 0; i < cmds.Length; ++i)\n            {\n                cmds[i].Execute();\n                Debuger.LogVerbose(\"{0} End----------------\", cmds[i].GetType().Name);\n            }\n        }\n\n        #endregion\n        //====================================================================\n\n        protected abstract void Execute();\n    }\n\n    public class MvvmCommand<T>: MvvmCommandBase where T:MvvmCommandBase, new ()\n    {\n        protected MvvmViewModel m_vm;\n        \n\n        public static void Send(MvvmViewModel vm)\n        {\n            MvvmCommand<T> cmd = (new T()) as MvvmCommand<T>;\n            cmd.m_vm = vm;\n\n            Debuger.LogVerbose(\"{0} Begin--------------\", typeof(T).Name);\n            cmd.Execute();\n            Debuger.LogVerbose(\"{0} End----------------\", typeof(T).Name);\n        }\n\n        public static void SendAsync(MvvmViewModel vm)\n        {\n            MvvmCommand<T> cmd = (new T()) as MvvmCommand<T>;\n            cmd.m_vm = vm;\n\n            Debuger.LogVerbose(\"{0} Begin--------------\", typeof(T).Name);\n            PumpAsyncCommand(cmd);\n        }\n\n        protected override void Execute()\n        {\n            throw new NotImplementedException();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFCore/MvvmLite/MvvmManager.cs",
    "content": "﻿using SGF.Timers;\nusing SGF.Utils;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SGF.MvvmLite\n{\n    public class MvvmManager : Singleton<MvvmManager>\n    {\n        public void Init()\n        {\n\n        }\n        \n\n    }\n}\n"
  },
  {
    "path": "SGFCore/MvvmLite/MvvmModel.cs",
    "content": "﻿using SGF.SEvent;\nusing SGF.Utils;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace SGF.MvvmLite\n{\n    public class MvvmModel:MvvmBinding\n    {\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/MvvmLite/MvvmViewModel.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SGF.MvvmLite\n{\n    public class MvvmViewModel: MvvmBinding\n    {\n        protected MvvmModel m_model;\n\n        public MvvmViewModel(MvvmModel model)\n        {\n            m_model = model;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFCore/Network/Core/KCP/KCPSocket.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 将KCP与Socket封装在一起，以提供可靠UDP通讯功能\n * KCP:https://github.com/skywind3000/kcp\n * KCP CSharp Port:https://github.com/limpo1989/kcp-csharp\n * Package KCP with Socket to provide reliable UDP communication\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\n\nnamespace SGF.Network.Core\n{\n    public class KCPSocket\n    {\n        private static readonly DateTime UTCTimeBegin = new DateTime(1970, 1, 1);\n\n        public static UInt32 GetClockMS()\n        {\n            return (UInt32)(Convert.ToInt64(DateTime.UtcNow.Subtract(UTCTimeBegin).TotalMilliseconds) & 0xffffffff);\n        }\n\n        public delegate void KCPReceiveListener(byte[] buff, int size, IPEndPoint remotePoint);\n\n\n\n        public string LOG_TAG = \"KCPSocket\";\n\n        private bool m_IsRunning = false;\n        private Socket m_SystemSocket;\n        private IPEndPoint m_LocalEndPoint;\n        private AddressFamily m_AddrFamily;\n        private Thread m_ThreadRecv;\n        private byte[] m_RecvBufferTemp = new byte[4096];\n        \n        //KCP参数\n        private List<KCPProxy> m_ListKcp; \n        private uint m_KcpKey = 0;\n        private KCPReceiveListener m_AnyEPListener;\n\n        //=================================================================================\n        #region 构造和析构\n\n        public KCPSocket(int bindPort, uint kcpKey, AddressFamily family = AddressFamily.InterNetwork)\n        {\n            m_AddrFamily = family;\n            m_KcpKey = kcpKey;\n            m_ListKcp = new List<KCPProxy>();\n\n            m_SystemSocket = new Socket(m_AddrFamily, SocketType.Dgram, ProtocolType.Udp);\n            IPEndPoint ipep = IPUtils.GetIPEndPointAny(m_AddrFamily, bindPort);\n            m_SystemSocket.Bind(ipep);\n\n            bindPort = (m_SystemSocket.LocalEndPoint as IPEndPoint).Port;\n            LOG_TAG = \"KCPSocket[\" + bindPort + \"-\" + kcpKey + \"]\";\n\n            m_IsRunning = true;\n            m_ThreadRecv = new Thread(Thread_Recv) {IsBackground = true};\n            m_ThreadRecv.Start();\n\n\n\n#if UNITY_EDITOR_WIN\n            uint IOC_IN = 0x80000000;\n            uint IOC_VENDOR = 0x18000000;\n            uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;\n            m_SystemSocket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);\n#endif\n\n#if UNITY_EDITOR\n            UnityEditor.EditorApplication.playmodeStateChanged -= OnEditorPlayModeChanged;\n            UnityEditor.EditorApplication.playmodeStateChanged += OnEditorPlayModeChanged;\n#endif\n        }\n\n\n#if UNITY_EDITOR\n        private void OnEditorPlayModeChanged()\n        {\n            if (UnityEngine.Application.isPlaying == false)\n            {\n                UnityEditor.EditorApplication.playmodeStateChanged -= OnEditorPlayModeChanged;\n                Dispose();\n            }\n        }\n#endif\n\n\n        public void Dispose()\n        {\n            m_IsRunning = false;\n            m_AnyEPListener = null;\n\n            if (m_ThreadRecv != null)\n            {\n                m_ThreadRecv.Interrupt();\n                m_ThreadRecv = null;\n            }\n\n            int cnt = m_ListKcp.Count;\n            for (int i = 0; i < cnt; i++)\n            {\n                m_ListKcp[i].Dispose();\n            }\n            m_ListKcp.Clear();\n            \n            if (m_SystemSocket != null)\n            {\n                try\n                {\n                    m_SystemSocket.Shutdown(SocketShutdown.Both);\n                    \n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(e.Message + e.StackTrace);\n                }\n\n                m_SystemSocket.Close();\n                m_SystemSocket = null;\n            }\n        }\n\n        public void Connect(IPEndPoint remotePoint)\n        {\n            m_SystemSocket.Connect(remotePoint);\n        }\n\n        public int SelfPort\n        {\n            get{return (m_SystemSocket.LocalEndPoint as IPEndPoint).Port;}\n        }\n\n        public string SelfIP\n        {\n\t\t\tget { return IPUtils.SelfIP; }\n        }\n\n        public IPEndPoint SelfEndPoint\n        {\n            get\n            {\n                if (m_LocalEndPoint == null || \n\t\t\t\t\tm_LocalEndPoint.Address.ToString() != IPUtils.SelfIP)\n                {\n                    IPAddress ip = IPAddress.Parse(SelfIP);\n                    m_LocalEndPoint = new IPEndPoint(ip, SelfPort);\n                }\n\n                return m_LocalEndPoint;\n            }\n        }\n\n        public Socket SystemSocket { get { return m_SystemSocket; } }\n        \n        #endregion\n\n        //=================================================================================\n\n        public bool EnableBroadcast\n        {\n            get { return m_SystemSocket.EnableBroadcast; }\n            set { m_SystemSocket.EnableBroadcast = value; }\n        }\n\n        //=================================================================================\n        #region 管理KCP\n\n        private bool IsValidKcpIPEndPoint(IPEndPoint ipep)\n        {\n            if (ipep == null || ipep.Port == 0 || \n                ipep.Address.Equals(IPAddress.Any) || \n                ipep.Address.Equals(IPAddress.IPv6Any))\n            {\n                return false;\n            }\n            return true;\n        }\n\n        private KCPProxy GetKcp(IPEndPoint ipep, bool autoAdd = true)\n        {\n            if (!IsValidKcpIPEndPoint(ipep))\n            {\n                return null;\n            }\n\n            KCPProxy proxy = null;\n            int cnt = m_ListKcp.Count;\n            for (int i = 0; i < cnt; i++)\n            {\n                proxy = m_ListKcp[i];\n                if (proxy.RemotePoint.Equals(ipep))\n                {\n                    return proxy;\n                }\n            }\n\n            if (autoAdd)\n            {\n                proxy = new KCPProxy(m_KcpKey, ipep, m_SystemSocket);\n                proxy.AddReceiveListener(OnReceiveAny);\n                m_ListKcp.Add(proxy);\n            }\n            return proxy;\n        }\n\n\n        public void CloseKcp(IPEndPoint ipep)\n        {\n            KCPProxy proxy = null;\n            int cnt = m_ListKcp.Count;\n            for (int i = 0; i < cnt; i++)\n            {\n                proxy = m_ListKcp[i];\n                if (proxy.RemotePoint.Equals(ipep))\n                {\n                    m_ListKcp.RemoveAt(i);\n                    break;\n                }\n            }\n        }\n\n        #endregion\n\n        //=================================================================================\n        #region 发送逻辑\n        public bool SendTo(byte[] buffer, int size, IPEndPoint remotePoint)\n        {\n            if (remotePoint.Address == IPAddress.Broadcast)\n            {\n                int cnt = m_SystemSocket.SendTo(buffer, size, SocketFlags.None, remotePoint);\n                return cnt > 0;\n            }\n            else\n            {\n                KCPProxy proxy = GetKcp(remotePoint);\n                if (proxy != null)\n                {\n                    return proxy.DoSend(buffer, size);\n                }\n            }\n\n            return false;\n        }\n\n        public bool SendTo(string message, IPEndPoint remotePoint)\n        {\n            byte[] buffer = Encoding.UTF8.GetBytes(message);\n            return SendTo(buffer, buffer.Length, remotePoint);\n        }\n\n        #endregion\n\n\n        //=================================================================================\n        #region 主线程驱动\n\n        public void Update()\n        {\n            if (m_IsRunning)\n            {\n                //获取时钟\n                uint current = GetClockMS();\n\n                int cnt = m_ListKcp.Count;\n                for (int i = 0; i < cnt; i++)\n                {\n                    KCPProxy proxy = m_ListKcp[i];\n                    proxy.Update(current);\n                }\n            }\n        }\n\n        #endregion\n\n        //=================================================================================\n        #region 接收逻辑\n\n        public void AddReceiveListener(IPEndPoint remotePoint, KCPReceiveListener listener)\n        {\n            KCPProxy proxy = GetKcp(remotePoint);\n            if (proxy != null)\n            {\n                proxy.AddReceiveListener(listener);\n            }\n            else\n            {\n                m_AnyEPListener += listener;\n            }\n        }\n\n        public void RemoveReceiveListener(IPEndPoint remotePoint, KCPReceiveListener listener)\n        {\n            KCPProxy proxy = GetKcp(remotePoint);\n            if (proxy != null)\n            {\n                proxy.RemoveReceiveListener(listener);\n            }\n            else\n            {\n                m_AnyEPListener -= listener;\n            }\n        }\n\n        public void AddReceiveListener(KCPReceiveListener listener)\n        {\n            m_AnyEPListener += listener;\n        }\n\n        public void RemoveReceiveListener(KCPReceiveListener listener)\n        {\n            m_AnyEPListener -= listener;\n        }\n\n\n        private void OnReceiveAny(byte[] buffer, int size,   IPEndPoint remotePoint)\n        {\n            if (m_AnyEPListener != null)\n            {\n                m_AnyEPListener(buffer, size, remotePoint);\n            }\n        }\n\n        #endregion\n\n        //=================================================================================\n        #region 接收线程\n\n        private void Thread_Recv()\n        {\n            Debuger.Log(\"Thread_Recv() Begin ......\");\n\n            while (m_IsRunning)\n            {\n                try\n                {\n                    DoReceive();\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(\"Thread_Recv() \" + e.Message + \"\\n\" + e.StackTrace);\n                    Thread.Sleep(10);\n                }\n            }\n\n            Debuger.Log(\"Thread_Recv() End!\");\n        }\n\n        private void DoReceive()\n        {\n            EndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);\n            int cnt = m_SystemSocket.ReceiveFrom(m_RecvBufferTemp, m_RecvBufferTemp.Length,\n                SocketFlags.None, ref remotePoint);\n\n            if (cnt > 0)\n            {\n                KCPProxy proxy = GetKcp((IPEndPoint)remotePoint);\n                if (proxy != null)\n                {\n                    proxy.DoReceiveInThread(m_RecvBufferTemp, cnt);\n                }    \n            }\n            \n        }\n\n        #endregion\n    }\n\n\n\n\n    class KCPProxy\n    {\n        \n        private KCP m_Kcp;\n        private bool m_NeedKcpUpdateFlag = false;\n        private uint m_NextKcpUpdateTime = 0;\n        private SwitchQueue<byte[]> m_RecvQueue = new SwitchQueue<byte[]>(128);\n\n        private IPEndPoint m_RemotePoint;\n        private Socket m_Socket;\n        private KCPSocket.KCPReceiveListener m_Listener;\n\n        public IPEndPoint RemotePoint { get { return m_RemotePoint; } }\n\n\n        public KCPProxy(uint key, IPEndPoint remotePoint, Socket socket)\n        {\n            m_Socket = socket;\n            m_RemotePoint = remotePoint;\n\n            m_Kcp = new KCP(key, HandleKcpSend);\n            m_Kcp.NoDelay(1, 10, 2, 1);\n            m_Kcp.WndSize(128, 128);\n\n        }\n\n        public void Dispose()\n        {\n            m_Socket = null;\n\n            NetDebuger.WeakNetCancel(this);\n            \n            if (m_Kcp != null)\n            {\n                m_Kcp.Dispose();\n                m_Kcp = null;\n            }\n\n            m_Listener = null;\n        }\n\n        //---------------------------------------------\n        private void HandleKcpSend(byte[] buff, int size)\n        {\n            if (NetDebuger.EnableWeakNet)\n            {\n                NetDebuger.WeakNetSimulate(this, buff, size, HandleKcpSend_Hook);\n            }\n            else\n            {\n                if (m_Socket != null)\n                {\n                    m_Socket.SendTo(buff, 0, size, SocketFlags.None, m_RemotePoint);\n                }    \n            }\n        }\n\n        private void HandleKcpSend_Hook(byte[] buff, int size)\n        {\n            if (m_Socket != null)\n            {\n                m_Socket.SendTo(buff, 0, size, SocketFlags.None, m_RemotePoint);\n            }    \n        }\n\n        public bool DoSend(byte[] buff, int size)\n        {\n            m_NeedKcpUpdateFlag = true;\n            return m_Kcp.Send(buff, size) >= 0;\n        }\n\n        //---------------------------------------------\n\n        public void AddReceiveListener(KCPSocket.KCPReceiveListener listener)\n        {\n            m_Listener += listener;\n        }\n\n        public void RemoveReceiveListener(KCPSocket.KCPReceiveListener listener)\n        {\n            m_Listener -= listener;\n        }\n\n\n\n        public void DoReceiveInThread(byte[] buffer, int size)\n        {\n            if (NetDebuger.IsPacketLoss())\n            {\n                return;\n            }\n\n            byte[] dst = new byte[size];\n            Buffer.BlockCopy(buffer, 0, dst, 0, size);\n            m_RecvQueue.Push(dst);\n        }\n\n        private void HandleRecvQueue()\n        {\n            m_RecvQueue.Switch();\n            while (!m_RecvQueue.Empty())\n            {\n                var recvBufferRaw = m_RecvQueue.Pop();\n                int ret = m_Kcp.Input(recvBufferRaw, recvBufferRaw.Length);\n\n                //收到的不是一个正确的KCP包\n                if (ret < 0)\n                {\n                    if (m_Listener != null)\n                    {\n                        m_Listener(recvBufferRaw, recvBufferRaw.Length, m_RemotePoint);\n                    }\n                    return;\n                }\n\n                m_NeedKcpUpdateFlag = true;\n                KCP kcp = m_Kcp;\n\n                for (int size = kcp.PeekSize(); size > 0; size = kcp.PeekSize())\n                {\n                    var recvBuffer = new byte[size];\n                    if (kcp.Recv(recvBuffer) > 0)\n                    {\n                        if (m_Listener != null)\n                        {\n                            m_Listener(recvBuffer, size, m_RemotePoint);\n                        }\n                    }\n                }\n            }\n        }\n\n        //---------------------------------------------\n        public void Update(uint currentTimeMS)\n        {\n            HandleRecvQueue();\n\n            if (m_NeedKcpUpdateFlag || currentTimeMS >= m_NextKcpUpdateTime)\n            {\n                if (m_Kcp != null)\n                {\n                    m_Kcp.Update(currentTimeMS);\n                    m_NextKcpUpdateTime = m_Kcp.Check(currentTimeMS);\n                    m_NeedKcpUpdateFlag = false;\n                }\n            }\n        }\n\n        //---------------------------------------------\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/Network/Core/KCP/LICENSE.txt",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {description}\n    Copyright (C) {year}  {fullname}\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  {signature of Ty Coon}, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n\n"
  },
  {
    "path": "SGFCore/Network/Core/KCP/kcp.cs",
    "content": "﻿using System;\n\nnamespace SGF.Network.Core\n{\n    public class KCP\n    {\n        public const int IKCP_RTO_NDL = 30;  // no delay min rto\n        public const int IKCP_RTO_MIN = 100; // normal min rto\n        public const int IKCP_RTO_DEF = 200;\n        public const int IKCP_RTO_MAX = 60000;\n        public const int IKCP_CMD_PUSH = 81; // cmd: push data\n        public const int IKCP_CMD_ACK = 82; // cmd: ack\n        public const int IKCP_CMD_WASK = 83; // cmd: window probe (ask)\n        public const int IKCP_CMD_WINS = 84; // cmd: window size (tell)\n        public const int IKCP_ASK_SEND = 1;  // need to send IKCP_CMD_WASK\n        public const int IKCP_ASK_TELL = 2;  // need to send IKCP_CMD_WINS\n        public const int IKCP_WND_SND = 32;\n        public const int IKCP_WND_RCV = 32;\n        public const int IKCP_MTU_DEF = 1400;\n        public const int IKCP_ACK_FAST = 3;\n        public const int IKCP_INTERVAL = 100;\n        public const int IKCP_OVERHEAD = 24;\n        public const int IKCP_DEADLINK = 10;\n        public const int IKCP_THRESH_INIT = 2;\n        public const int IKCP_THRESH_MIN = 2;\n        public const int IKCP_PROBE_INIT = 7000;   // 7 secs to probe window size\n        public const int IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window\n\n\n        // encode 8 bits unsigned int\n        public static int ikcp_encode8u(byte[] p, int offset, byte c)\n        {\n            p[0 + offset] = c;\n            return 1;\n        }\n\n        // decode 8 bits unsigned int\n        public static int ikcp_decode8u(byte[] p, int offset, ref byte c)\n        {\n            c = p[0 + offset];\n            return 1;\n        }\n\n        /* encode 16 bits unsigned int (lsb) */\n        public static int ikcp_encode16u(byte[] p, int offset, UInt16 w)\n        {\n            p[0 + offset] = (byte)(w >> 0);\n            p[1 + offset] = (byte)(w >> 8);\n            return 2;\n        }\n\n        /* decode 16 bits unsigned int (lsb) */\n        public static int ikcp_decode16u(byte[] p, int offset, ref UInt16 c)\n        {\n            UInt16 result = 0;\n            result |= (UInt16)p[0 + offset];\n            result |= (UInt16)(p[1 + offset] << 8);\n            c = result;\n            return 2;\n        }\n\n        /* encode 32 bits unsigned int (lsb) */\n        public static int ikcp_encode32u(byte[] p, int offset, UInt32 l)\n        {\n            p[0 + offset] = (byte)(l >> 0);\n            p[1 + offset] = (byte)(l >> 8);\n            p[2 + offset] = (byte)(l >> 16);\n            p[3 + offset] = (byte)(l >> 24);\n            return 4;\n        }\n\n        /* decode 32 bits unsigned int (lsb) */\n        public static int ikcp_decode32u(byte[] p, int offset, ref UInt32 c)\n        {\n            UInt32 result = 0;\n            result |= (UInt32)p[0 + offset];\n            result |= (UInt32)(p[1 + offset] << 8);\n            result |= (UInt32)(p[2 + offset] << 16);\n            result |= (UInt32)(p[3 + offset] << 24);\n            c = result;\n            return 4;\n        }\n\n        public static byte[] slice(byte[] p, int start, int stop)\n        {\n            var bytes = new byte[stop - start];\n            Array.Copy(p, start, bytes, 0, bytes.Length);\n            return bytes;\n        }\n\n        public static T[] slice<T>(T[] p, int start, int stop)\n        {\n            var arr = new T[stop - start];\n            var index = 0;\n            for (var i = start; i < stop; i++)\n            {\n                arr[index] = p[i];\n                index++;\n            }\n\n            return arr;\n        }\n\n        public static byte[] append(byte[] p, byte c)\n        {\n            var bytes = new byte[p.Length + 1];\n            Array.Copy(p, bytes, p.Length);\n            bytes[p.Length] = c;\n            return bytes;\n        }\n\n        public static T[] append<T>(T[] p, T c)\n        {\n            var arr = new T[p.Length + 1];\n            for (var i = 0; i < p.Length; i++)\n                arr[i] = p[i];\n            arr[p.Length] = c;\n            return arr;\n        }\n\n        public static T[] append<T>(T[] p, T[] cs)\n        {\n            var arr = new T[p.Length + cs.Length];\n            for (var i = 0; i < p.Length; i++)\n                arr[i] = p[i];\n            for (var i = 0; i < cs.Length; i++)\n                arr[p.Length + i] = cs[i];\n            return arr;\n        }\n\n        static UInt32 _imin_(UInt32 a, UInt32 b)\n        {\n            return a <= b ? a : b;\n        }\n\n        static UInt32 _imax_(UInt32 a, UInt32 b)\n        {\n            return a >= b ? a : b;\n        }\n\n        static UInt32 _ibound_(UInt32 lower, UInt32 middle, UInt32 upper)\n        {\n            return _imin_(_imax_(lower, middle), upper);\n        }\n\n        static Int32 _itimediff(UInt32 later, UInt32 earlier)\n        {\n            return ((Int32)(later - earlier));\n        }\n\n        // KCP Segment Definition\n        internal class Segment\n        {\n            internal UInt32 conv = 0;\n            internal UInt32 cmd = 0;\n            internal UInt32 frg = 0;\n            internal UInt32 wnd = 0;\n            internal UInt32 ts = 0;\n            internal UInt32 sn = 0;\n            internal UInt32 una = 0;\n            internal UInt32 resendts = 0;\n            internal UInt32 rto = 0;\n            internal UInt32 fastack = 0;\n            internal UInt32 xmit = 0;\n            internal byte[] data;\n\n            internal Segment(int size)\n            {\n                this.data = new byte[size];\n            }\n\n            // encode a segment into buffer\n            internal int encode(byte[] ptr, int offset)\n            {\n\n                var offset_ = offset;\n\n                offset += ikcp_encode32u(ptr, offset, conv);\n                offset += ikcp_encode8u(ptr, offset, (byte)cmd);\n                offset += ikcp_encode8u(ptr, offset, (byte)frg);\n                offset += ikcp_encode16u(ptr, offset, (UInt16)wnd);\n                offset += ikcp_encode32u(ptr, offset, ts);\n                offset += ikcp_encode32u(ptr, offset, sn);\n                offset += ikcp_encode32u(ptr, offset, una);\n                offset += ikcp_encode32u(ptr, offset, (UInt32)data.Length);\n\n                return offset - offset_;\n            }\n        }\n\n        // kcp members.\n        UInt32 conv; UInt32 mtu; UInt32 mss; UInt32 state;\n        UInt32 snd_una; UInt32 snd_nxt; UInt32 rcv_nxt;\n        UInt32 ts_recent; UInt32 ts_lastack; UInt32 ssthresh;\n        UInt32 rx_rttval; UInt32 rx_srtt; UInt32 rx_rto; UInt32 rx_minrto;\n        UInt32 snd_wnd; UInt32 rcv_wnd; UInt32 rmt_wnd; UInt32 cwnd; UInt32 probe;\n        UInt32 current; UInt32 interval; UInt32 ts_flush; UInt32 xmit;\n        UInt32 nodelay; UInt32 updated;\n        UInt32 ts_probe; UInt32 probe_wait;\n        UInt32 dead_link; UInt32 incr;\n\n        Segment[] snd_queue = new Segment[0];\n        Segment[] rcv_queue = new Segment[0];\n        Segment[] snd_buf = new Segment[0];\n        Segment[] rcv_buf = new Segment[0];\n\n        UInt32[] acklist = new UInt32[0];\n\n        byte[] buffer;\n        Int32 fastresend;\n        Int32 nocwnd;\n        Int32 logmask;\n        // buffer, size\n        Action<byte[], int> output;\n\n        /// <summary>\n        /// create a new kcp control object, 'conv' must equal in two endpoint\n        /// from the same connection.\n        /// </summary>\n        /// <param name=\"conv_\">if 0 then use first received conv</param>\n        /// <param name=\"output_\"></param>\n        public KCP(UInt32 conv_, Action<byte[], int> output_)\n        {\n            conv = conv_;\n            snd_wnd = IKCP_WND_SND;\n            rcv_wnd = IKCP_WND_RCV;\n            rmt_wnd = IKCP_WND_RCV;\n            mtu = IKCP_MTU_DEF;\n            mss = mtu - IKCP_OVERHEAD;\n\n            rx_rto = IKCP_RTO_DEF;\n            rx_minrto = IKCP_RTO_MIN;\n            interval = IKCP_INTERVAL;\n            ts_flush = IKCP_INTERVAL;\n            ssthresh = IKCP_THRESH_INIT;\n            dead_link = IKCP_DEADLINK;\n            buffer = new byte[(mtu + IKCP_OVERHEAD) * 3];\n            output = output_;\n        }\n\n        public void Dispose()\n        {\n            output = null;\n        }\n\n        public UInt32 GetConv()\n        {\n            return conv;\n        }\n\n        // check the size of next message in the recv queue\n        public int PeekSize()\n        {\n\n            if (0 == rcv_queue.Length) return -1;\n\n            var seq = rcv_queue[0];\n\n            if (0 == seq.frg) return seq.data.Length;\n\n            if (rcv_queue.Length < seq.frg + 1) return -1;\n\n            int length = 0;\n\n            foreach (var item in rcv_queue)\n            {\n                length += item.data.Length;\n                if (0 == item.frg)\n                    break;\n            }\n\n            return length;\n        }\n\n        // user/upper level recv: returns size, returns below zero for EAGAIN\n        public int Recv(byte[] buffer)\n        {\n\n            if (0 == rcv_queue.Length) return -1;\n\n            var peekSize = PeekSize();\n            if (0 > peekSize) return -2;\n\n            if (peekSize > buffer.Length) return -3;\n\n            var fast_recover = false;\n            if (rcv_queue.Length >= rcv_wnd) fast_recover = true;\n\n            // merge fragment.\n            var count = 0;\n            var n = 0;\n            foreach (var seg in rcv_queue)\n            {\n                Array.Copy(seg.data, 0, buffer, n, seg.data.Length);\n                n += seg.data.Length;\n                count++;\n                if (0 == seg.frg) break;\n            }\n\n            if (0 < count)\n            {\n                rcv_queue = slice<Segment>(rcv_queue, count, rcv_queue.Length);\n            }\n\n            // move available data from rcv_buf -> rcv_queue\n            count = 0;\n            foreach (var seg in rcv_buf)\n            {\n                if (seg.sn == rcv_nxt && rcv_queue.Length < rcv_wnd)\n                {\n                    rcv_queue = append<Segment>(rcv_queue, seg);\n                    rcv_nxt++;\n                    count++;\n                }\n                else\n                {\n                    break;\n                }\n            }\n\n            if (0 < count) rcv_buf = slice<Segment>(rcv_buf, count, rcv_buf.Length);\n\n            // fast recover\n            if (rcv_queue.Length < rcv_wnd && fast_recover)\n            {\n                // ready to send back IKCP_CMD_WINS in ikcp_flush\n                // tell remote my window size\n                probe |= IKCP_ASK_TELL;\n            }\n\n            return n;\n        }\n\n        // user/upper level send, returns below zero for error\n        public int Send(byte[] buffer, int bufferSize)\n        {\n\n            if (0 == bufferSize) return -1;\n\n            var count = 0;\n\n            if (bufferSize < mss)\n                count = 1;\n            else\n                count = (int)(bufferSize + mss - 1) / (int)mss;\n\n            if (255 < count) return -2;\n\n            if (0 == count) count = 1;\n\n            var offset = 0;\n\n            for (var i = 0; i < count; i++)\n            {\n                var size = 0;\n                if (bufferSize > mss)\n                    size = (int)mss;\n                else\n                    size = bufferSize;\n\n                var seg = new Segment(size);\n                Array.Copy(buffer, offset, seg.data, 0, size);\n                offset += size;\n                seg.frg = (UInt32)(count - i - 1);\n                snd_queue = append<Segment>(snd_queue, seg);\n            }\n\n            return 0;\n        }\n\n        // update ack.\n        void update_ack(Int32 rtt)\n        {\n            if (0 == rx_srtt)\n            {\n                rx_srtt = (UInt32)rtt;\n                rx_rttval = (UInt32)rtt / 2;\n            }\n            else\n            {\n                Int32 delta = (Int32)((UInt32)rtt - rx_srtt);\n                if (0 > delta) delta = -delta;\n\n                rx_rttval = (3 * rx_rttval + (uint)delta) / 4;\n                rx_srtt = (UInt32)((7 * rx_srtt + rtt) / 8);\n                if (rx_srtt < 1) rx_srtt = 1;\n            }\n\n            var rto = (int)(rx_srtt + _imax_(1, 4 * rx_rttval));\n            rx_rto = _ibound_(rx_minrto, (UInt32)rto, IKCP_RTO_MAX);\n        }\n\n        void shrink_buf()\n        {\n            if (snd_buf.Length > 0)\n                snd_una = snd_buf[0].sn;\n            else\n                snd_una = snd_nxt;\n        }\n\n        void parse_ack(UInt32 sn)\n        {\n\n            if (_itimediff(sn, snd_una) < 0 || _itimediff(sn, snd_nxt) >= 0) return;\n\n            var index = 0;\n            foreach (var seg in snd_buf)\n            {\n                if (sn == seg.sn)\n                {\n                    snd_buf = append<Segment>(slice<Segment>(snd_buf, 0, index), slice<Segment>(snd_buf, index + 1, snd_buf.Length));\n                    break;\n                }\n                else\n                {\n                    seg.fastack++;\n                }\n\n                index++;\n            }\n        }\n\n        void parse_una(UInt32 una)\n        {\n            var count = 0;\n            foreach (var seg in snd_buf)\n            {\n                if (_itimediff(una, seg.sn) > 0)\n                    count++;\n                else\n                    break;\n            }\n\n            if (0 < count) snd_buf = slice<Segment>(snd_buf, count, snd_buf.Length);\n        }\n\n        void ack_push(UInt32 sn, UInt32 ts)\n        {\n            acklist = append<UInt32>(acklist, new UInt32[2] { sn, ts });\n        }\n\n        void ack_get(int p, ref UInt32 sn, ref UInt32 ts)\n        {\n            sn = acklist[p * 2 + 0];\n            ts = acklist[p * 2 + 1];\n        }\n\n        void parse_data(Segment newseg)\n        {\n            var sn = newseg.sn;\n            if (_itimediff(sn, rcv_nxt + rcv_wnd) >= 0 || _itimediff(sn, rcv_nxt) < 0) return;\n\n            var n = rcv_buf.Length - 1;\n            var after_idx = -1;\n            var repeat = false;\n            for (var i = n; i >= 0; i--)\n            {\n                var seg = rcv_buf[i];\n                if (seg.sn == sn)\n                {\n                    repeat = true;\n                    break;\n                }\n\n                if (_itimediff(sn, seg.sn) > 0)\n                {\n                    after_idx = i;\n                    break;\n                }\n            }\n\n            if (!repeat)\n            {\n                if (after_idx == -1)\n                    rcv_buf = append<Segment>(new Segment[1] { newseg }, rcv_buf);\n                else\n                    rcv_buf = append<Segment>(slice<Segment>(rcv_buf, 0, after_idx + 1), append<Segment>(new Segment[1] { newseg }, slice<Segment>(rcv_buf, after_idx + 1, rcv_buf.Length)));\n            }\n\n            // move available data from rcv_buf -> rcv_queue\n            var count = 0;\n            foreach (var seg in rcv_buf)\n            {\n                if (seg.sn == rcv_nxt && rcv_queue.Length < rcv_wnd)\n                {\n                    rcv_queue = append<Segment>(rcv_queue, seg);\n                    rcv_nxt++;\n                    count++;\n                }\n                else\n                {\n                    break;\n                }\n            }\n\n            if (0 < count)\n            {\n                rcv_buf = slice<Segment>(rcv_buf, count, rcv_buf.Length);\n            }\n        }\n\n        // when you received a low level packet (eg. UDP packet), call it\n        public int Input(byte[] data, int dataLength)\n        {\n\n            var s_una = snd_una;\n            if (dataLength < IKCP_OVERHEAD) return 0;\n\n            var offset = 0;\n\n            while (true)\n            {\n                UInt32 ts = 0;\n                UInt32 sn = 0;\n                UInt32 length = 0;\n                UInt32 una = 0;\n                UInt32 conv_ = 0;\n\n                UInt16 wnd = 0;\n\n                byte cmd = 0;\n                byte frg = 0;\n\n                if (dataLength - offset < IKCP_OVERHEAD) break;\n\n                offset += ikcp_decode32u(data, offset, ref conv_);\n\n                if (conv != conv_)\n                {\n                    //如果Conv不同，则可能有如下情况\n                    if (conv_ == 0)\n                    {\n                        //Server收到来自Client的第1个包，Client发出的Conv为0\n                        conv_ = conv;\n                    }\n                    else if(conv == 0)\n                    {\n                        //Client收到来自Server的第1个包，Client自己的Conv为0\n                        conv = conv_;\n                    }\n                    else\n                    {\n                        return -1;\n                    }\n                }\n\n                offset += ikcp_decode8u(data, offset, ref cmd);\n                offset += ikcp_decode8u(data, offset, ref frg);\n                offset += ikcp_decode16u(data, offset, ref wnd);\n                offset += ikcp_decode32u(data, offset, ref ts);\n                offset += ikcp_decode32u(data, offset, ref sn);\n                offset += ikcp_decode32u(data, offset, ref una);\n                offset += ikcp_decode32u(data, offset, ref length);\n\n                if (dataLength - offset < length) return -2;\n\n                switch (cmd)\n                {\n                    case IKCP_CMD_PUSH:\n                    case IKCP_CMD_ACK:\n                    case IKCP_CMD_WASK:\n                    case IKCP_CMD_WINS:\n                        break;\n                    default:\n                        return -3;\n                }\n\n                rmt_wnd = (UInt32)wnd;\n                parse_una(una);\n                shrink_buf();\n\n                if (IKCP_CMD_ACK == cmd)\n                {\n                    if (_itimediff(current, ts) >= 0)\n                    {\n                        update_ack(_itimediff(current, ts));\n                    }\n                    parse_ack(sn);\n                    shrink_buf();\n                }\n                else if (IKCP_CMD_PUSH == cmd)\n                {\n                    if (_itimediff(sn, rcv_nxt + rcv_wnd) < 0)\n                    {\n                        ack_push(sn, ts);\n                        if (_itimediff(sn, rcv_nxt) >= 0)\n                        {\n                            var seg = new Segment((int)length);\n                            seg.conv = conv_;\n                            seg.cmd = (UInt32)cmd;\n                            seg.frg = (UInt32)frg;\n                            seg.wnd = (UInt32)wnd;\n                            seg.ts = ts;\n                            seg.sn = sn;\n                            seg.una = una;\n\n                            if (length > 0) Array.Copy(data, offset, seg.data, 0, length);\n\n                            parse_data(seg);\n                        }\n                    }\n                }\n                else if (IKCP_CMD_WASK == cmd)\n                {\n                    // ready to send back IKCP_CMD_WINS in Ikcp_flush\n                    // tell remote my window size\n                    probe |= IKCP_ASK_TELL;\n                }\n                else if (IKCP_CMD_WINS == cmd)\n                {\n                    // do nothing\n                }\n                else\n                {\n                    return -3;\n                }\n\n                offset += (int)length;\n            }\n\n            if (_itimediff(snd_una, s_una) > 0)\n            {\n                if (cwnd < rmt_wnd)\n                {\n                    var mss_ = mss;\n                    if (cwnd < ssthresh)\n                    {\n                        cwnd++;\n                        incr += mss_;\n                    }\n                    else\n                    {\n                        if (incr < mss_)\n                        {\n                            incr = mss_;\n                        }\n                        incr += (mss_ * mss_) / incr + (mss_ / 16);\n                        if ((cwnd + 1) * mss_ <= incr) cwnd++;\n                    }\n                    if (cwnd > rmt_wnd)\n                    {\n                        cwnd = rmt_wnd;\n                        incr = rmt_wnd * mss_;\n                    }\n                }\n            }\n\n            return 0;\n        }\n\n        Int32 wnd_unused()\n        {\n            if (rcv_queue.Length < rcv_wnd)\n                return (Int32)(int)rcv_wnd - rcv_queue.Length;\n            return 0;\n        }\n\n        // flush pending data\n        void flush()\n        {\n            var current_ = current;\n            var buffer_ = buffer;\n            var change = 0;\n            var lost = 0;\n\n            if (0 == updated) return;\n\n            var seg = new Segment(0);\n            seg.conv = conv;\n            seg.cmd = IKCP_CMD_ACK;\n            seg.wnd = (UInt32)wnd_unused();\n            seg.una = rcv_nxt;\n\n            // flush acknowledges\n            var count = acklist.Length / 2;\n            var offset = 0;\n            for (var i = 0; i < count; i++)\n            {\n                if (offset + IKCP_OVERHEAD > mtu)\n                {\n                    output(buffer, offset);\n                    //Array.Clear(buffer, 0, offset);\n                    offset = 0;\n                }\n                ack_get(i, ref seg.sn, ref seg.ts);\n                offset += seg.encode(buffer, offset);\n            }\n            acklist = new UInt32[0];\n\n            // probe window size (if remote window size equals zero)\n            if (0 == rmt_wnd)\n            {\n                if (0 == probe_wait)\n                {\n                    probe_wait = IKCP_PROBE_INIT;\n                    ts_probe = current + probe_wait;\n                }\n                else\n                {\n                    if (_itimediff(current, ts_probe) >= 0)\n                    {\n                        if (probe_wait < IKCP_PROBE_INIT)\n                            probe_wait = IKCP_PROBE_INIT;\n                        probe_wait += probe_wait / 2;\n                        if (probe_wait > IKCP_PROBE_LIMIT)\n                            probe_wait = IKCP_PROBE_LIMIT;\n                        ts_probe = current + probe_wait;\n                        probe |= IKCP_ASK_SEND;\n                    }\n                }\n            }\n            else\n            {\n                ts_probe = 0;\n                probe_wait = 0;\n            }\n\n            // flush window probing commands\n            if ((probe & IKCP_ASK_SEND) != 0)\n            {\n                seg.cmd = IKCP_CMD_WASK;\n                if (offset + IKCP_OVERHEAD > (int)mtu)\n                {\n                    output(buffer, offset);\n                    //Array.Clear(buffer, 0, offset);\n                    offset = 0;\n                }\n                offset += seg.encode(buffer, offset);\n            }\n\n            probe = 0;\n\n            // calculate window size\n            var cwnd_ = _imin_(snd_wnd, rmt_wnd);\n            if (0 == nocwnd)\n                cwnd_ = _imin_(cwnd, cwnd_);\n\n            count = 0;\n            for (var k = 0; k < snd_queue.Length; k++)\n            {\n                if (_itimediff(snd_nxt, snd_una + cwnd_) >= 0) break;\n\n                var newseg = snd_queue[k];\n                newseg.conv = conv;\n                newseg.cmd = IKCP_CMD_PUSH;\n                newseg.wnd = seg.wnd;\n                newseg.ts = current_;\n                newseg.sn = snd_nxt;\n                newseg.una = rcv_nxt;\n                newseg.resendts = current_;\n                newseg.rto = rx_rto;\n                newseg.fastack = 0;\n                newseg.xmit = 0;\n                snd_buf = append<Segment>(snd_buf, newseg);\n                snd_nxt++;\n                count++;\n            }\n\n            if (0 < count)\n            {\n                snd_queue = slice<Segment>(snd_queue, count, snd_queue.Length);\n            }\n\n            // calculate resent\n            var resent = (UInt32)fastresend;\n            if (fastresend <= 0) resent = 0xffffffff;\n            var rtomin = rx_rto >> 3;\n            if (nodelay != 0) rtomin = 0;\n\n            // flush data segments\n            foreach (var segment in snd_buf)\n            {\n                var needsend = false;\n                var debug = _itimediff(current_, segment.resendts);\n                if (0 == segment.xmit)\n                {\n                    needsend = true;\n                    segment.xmit++;\n                    segment.rto = rx_rto;\n                    segment.resendts = current_ + segment.rto + rtomin;\n                }\n                else if (_itimediff(current_, segment.resendts) >= 0)\n                {\n                    needsend = true;\n                    segment.xmit++;\n                    xmit++;\n                    if (0 == nodelay)\n                        segment.rto += rx_rto;\n                    else\n                        segment.rto += rx_rto / 2;\n                    segment.resendts = current_ + segment.rto;\n                    lost = 1;\n                }\n                else if (segment.fastack >= resent)\n                {\n                    needsend = true;\n                    segment.xmit++;\n                    segment.fastack = 0;\n                    segment.resendts = current_ + segment.rto;\n                    change++;\n                }\n\n                if (needsend)\n                {\n                    segment.ts = current_;\n                    segment.wnd = seg.wnd;\n                    segment.una = rcv_nxt;\n\n                    var need = IKCP_OVERHEAD + segment.data.Length;\n                    if (offset + need >= mtu)\n                    {\n                        output(buffer, offset);\n                        //Array.Clear(buffer, 0, offset);\n                        offset = 0;\n                    }\n\n                    offset += segment.encode(buffer, offset);\n                    if (segment.data.Length > 0)\n                    {\n                        Array.Copy(segment.data, 0, buffer, offset, segment.data.Length);\n                        offset += segment.data.Length;\n                    }\n\n                    if (segment.xmit >= dead_link)\n                    {\n                        state = 0;\n                    }\n                }\n            }\n\n            // flash remain segments\n            if (offset > 0)\n            {\n                output(buffer, offset);\n                //Array.Clear(buffer, 0, offset);\n                offset = 0;\n            }\n\n            // update ssthresh\n            if (change != 0)\n            {\n                var inflight = snd_nxt - snd_una;\n                ssthresh = inflight / 2;\n                if (ssthresh < IKCP_THRESH_MIN)\n                    ssthresh = IKCP_THRESH_MIN;\n                cwnd = ssthresh + resent;\n                incr = cwnd * mss;\n            }\n\n            if (lost != 0)\n            {\n                ssthresh = cwnd / 2;\n                if (ssthresh < IKCP_THRESH_MIN)\n                    ssthresh = IKCP_THRESH_MIN;\n                cwnd = 1;\n                incr = mss;\n            }\n\n            if (cwnd < 1)\n            {\n                cwnd = 1;\n                incr = mss;\n            }\n        }\n\n        // update state (call it repeatedly, every 10ms-100ms), or you can ask\n        // ikcp_check when to call it again (without ikcp_input/_send calling).\n        // 'current' - current timestamp in millisec.\n        public void Update(UInt32 current_)\n        {\n\n            current = current_;\n\n            if (0 == updated)\n            {\n                updated = 1;\n                ts_flush = current;\n            }\n\n            var slap = _itimediff(current, ts_flush);\n\n            if (slap >= 10000 || slap < -10000)\n            {\n                ts_flush = current;\n                slap = 0;\n            }\n\n            if (slap >= 0)\n            {\n                ts_flush += interval;\n                if (_itimediff(current, ts_flush) >= 0)\n                    ts_flush = current + interval;\n                flush();\n            }\n        }\n\n        // Determine when should you invoke ikcp_update:\n        // returns when you should invoke ikcp_update in millisec, if there\n        // is no ikcp_input/_send calling. you can call ikcp_update in that\n        // time, instead of call update repeatly.\n        // Important to reduce unnacessary ikcp_update invoking. use it to\n        // schedule ikcp_update (eg. implementing an epoll-like mechanism,\n        // or optimize ikcp_update when handling massive kcp connections)\n        public UInt32 Check(UInt32 current_)\n        {\n\n            if (0 == updated) return current_;\n\n            var ts_flush_ = ts_flush;\n            var tm_flush_ = 0x7fffffff;\n            var tm_packet = 0x7fffffff;\n            var minimal = 0;\n\n            if (_itimediff(current_, ts_flush_) >= 10000 || _itimediff(current_, ts_flush_) < -10000)\n            {\n                ts_flush_ = current_;\n            }\n\n            if (_itimediff(current_, ts_flush_) >= 0) return current_;\n\n            tm_flush_ = (int)_itimediff(ts_flush_, current_);\n\n            foreach (var seg in snd_buf)\n            {\n                var diff = _itimediff(seg.resendts, current_);\n                if (diff <= 0) return current_;\n                if (diff < tm_packet) tm_packet = (int)diff;\n            }\n\n            minimal = (int)tm_packet;\n            if (tm_packet >= tm_flush_) minimal = (int)tm_flush_;\n            if (minimal >= interval) minimal = (int)interval;\n\n            return current_ + (UInt32)minimal;\n        }\n\n        // change MTU size, default is 1400\n        public int SetMtu(Int32 mtu_)\n        {\n            if (mtu_ < 50 || mtu_ < (Int32)IKCP_OVERHEAD) return -1;\n\n            var buffer_ = new byte[(mtu_ + IKCP_OVERHEAD) * 3];\n            if (null == buffer_) return -2;\n\n            mtu = (UInt32)mtu_;\n            mss = mtu - IKCP_OVERHEAD;\n            buffer = buffer_;\n            return 0;\n        }\n\n        public int Interval(Int32 interval_)\n        {\n            if (interval_ > 5000)\n            {\n                interval_ = 5000;\n            }\n            else if (interval_ < 10)\n            {\n                interval_ = 10;\n            }\n            interval = (UInt32)interval_;\n            return 0;\n        }\n\n        // fastest: ikcp_nodelay(kcp, 1, 20, 2, 1)\n        // nodelay: 0:disable(default), 1:enable\n        // interval: internal update timer interval in millisec, default is 100ms\n        // resend: 0:disable fast resend(default), 1:enable fast resend\n        // nc: 0:normal congestion control(default), 1:disable congestion control\n        public int NoDelay(int nodelay_, int interval_, int resend_, int nc_)\n        {\n\n            if (nodelay_ > 0)\n            {\n                nodelay = (UInt32)nodelay_;\n                if (nodelay_ != 0)\n                    rx_minrto = IKCP_RTO_NDL;\n                else\n                    rx_minrto = IKCP_RTO_MIN;\n            }\n\n            if (interval_ >= 0)\n            {\n                if (interval_ > 5000)\n                {\n                    interval_ = 5000;\n                }\n                else if (interval_ < 10)\n                {\n                    interval_ = 10;\n                }\n                interval = (UInt32)interval_;\n            }\n\n            if (resend_ >= 0) fastresend = resend_;\n\n            if (nc_ >= 0) nocwnd = nc_;\n\n            return 0;\n        }\n\n        // set maximum window size: sndwnd=32, rcvwnd=32 by default\n        public int WndSize(int sndwnd, int rcvwnd)\n        {\n            if (sndwnd > 0)\n                snd_wnd = (UInt32)sndwnd;\n\n            if (rcvwnd > 0)\n                rcv_wnd = (UInt32)rcvwnd;\n            return 0;\n        }\n\n        // get how many packet is waiting to be sent\n        public int WaitSnd()\n        {\n            return snd_buf.Length + snd_queue.Length;\n        }\n    }\n\n\n}\n"
  },
  {
    "path": "SGFCore/Network/Core/KCP/switch_queue.cs",
    "content": "using System;\nusing System.Collections;\n\nnamespace SGF.Network.Core\n{\n    public class Utility\n    {\n\n        public static void Swap<QT>(ref QT t1, ref QT t2)\n        {\n\n            QT temp = t1;\n            t1 = t2;\n            t2 = temp;\n        }\n    }\n\n    public class SwitchQueue<T> where T : class\n    {\n\n        private Queue mConsumeQueue;\n        private Queue mProduceQueue;\n\n        public SwitchQueue()\n        {\n            mConsumeQueue = new Queue(16);\n            mProduceQueue = new Queue(16);\n        }\n\n        public SwitchQueue(int capcity)\n        {\n            mConsumeQueue = new Queue(capcity);\n            mProduceQueue = new Queue(capcity);\n        }\n\n        // producer\n        public void Push(T obj)\n        {\n            lock (mProduceQueue)\n            {\n                mProduceQueue.Enqueue(obj);\n            }\n        }\n\n        // consumer.\n        public T Pop()\n        {\n\n            return (T)mConsumeQueue.Dequeue();\n        }\n\n        public bool Empty()\n        {\n            return 0 == mConsumeQueue.Count;\n        }\n\n        public void Switch()\n        {\n            lock (mProduceQueue)\n            {\n                Utility.Swap(ref mConsumeQueue, ref mProduceQueue);\n            }\n        }\n\n        public void Clear()\n        {\n            lock (mProduceQueue)\n            {\n                mConsumeQueue.Clear();\n                mProduceQueue.Clear();\n            }\n        }\n    }\n\n\n}\n"
  },
  {
    "path": "SGFCore/Network/Core/NetBuffer.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 封装了对网络字节流的操作\n * Encapsulates operations on network byte streams\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Text;\nusing SGF.Codec;\n\nnamespace SGF.Network.Core\n{\n\n    public class NetBuffer\n    {\n        public static byte[] ReverseOrder(byte[] dt)\n        {\n            if (!BitConverter.IsLittleEndian)\n            {\n                return dt;\n            }\n\n            int count = dt.Length;\n\n            if (count > 1)\n            {\n                int half = count / 2;\n                int maxIndex = count - 1;\n\n                for (int i = 0; i < half; i++)\n                {\n                    byte temp = dt[i];\n                    int swapIndex = maxIndex - i;\n\n                    dt[i] = dt[swapIndex];\n                    dt[swapIndex] = temp;\n                }\n            }\n\n            return dt;\n        }\n\n        protected int m_pos = 0;\n        protected int m_len = 0;\n        protected int m_capacity = 0;\n        protected byte[] m_buff = null;\n\n        /// <summary>\n        /// 临时字节长度\n        /// </summary>\n        protected byte[] m_16b = new byte[2];\n        protected byte[] m_32b = new byte[4];\n        protected byte[] m_64b = new byte[8];\n\n\n        public NetBuffer(int capacity)\n        {\n            this.m_capacity = capacity;\n            this.m_buff = new byte[capacity];\n            this.m_pos = 0;\n            this.m_len = 0;\n        }\n\n        public NetBuffer(byte[] buff = null)\n        {\n            this.m_capacity = 0;\n            this.m_pos = 0;\n            this.m_len = 0;\n            this.m_buff = buff;\n            if (buff != null)\n            {\n                this.m_capacity = buff.Length;\n            }\n        }\n\n        public NetBuffer Attach(byte[] buff, int len)\n        {\n            if (buff == null)\n            {\n                throw new Exception(\"NetBuffer Attach A Null Buffer!\");\n            }\n\n            this.m_pos = 0;\n            this.m_buff = buff;\n            this.m_len = System.Math.Min(len, buff.Length);\n            this.m_capacity = buff.Length;\n            return this;\n        }\n\n        public void Clear()\n        {\n            m_len = 0;\n            m_pos = 0;\n        }\n\n        public void AdjustCapacity(int newCapacity)\n        {\n            if (newCapacity < m_len)\n            {\n                m_len = newCapacity;\n                if (m_pos > m_len)\n                {\n                    m_pos = m_len;\n                }\n            }\n\n            byte[] newBuff = new byte[newCapacity];\n            Buffer.BlockCopy(m_buff, 0, newBuff, 0, m_len);\n\n            m_capacity = newCapacity;\n            m_buff = newBuff;\n        }\n\n        public int Capacity { get { return m_capacity; } }\n\n        public int Position\n        {\n            get\n            {\n                return m_pos;\n            }\n\n            set\n            {\n                m_pos = value;\n            }\n        }\n\n        public int Length { get { return m_len; } }\n\n        public int BytesAvailable { get { return (m_len - m_pos); } }\n\n        public byte[] GetBytes()\n        {\n            return m_buff;\n        }\n\n\n\n        public void SetPositionToLength()\n        {\n            m_pos = m_len;\n        }\n\n        public string ToHexString()\n        {\n            return SGFEncoding.BytesToHex(m_buff, m_len);\n        }\n\n        public override string ToString()\n        {\n            return ToHexString();\n        }\n\n        /// <summary>\n        /// 去掉已经读完的字节\n        /// 装POSITION设置成0\n        /// </summary>\n        public void Arrangement(int pos = -1)\n        {\n            pos = pos == -1 ? m_pos : pos;\n            if (pos > m_len)\n            {\n                pos = m_len;\n            }\n\n            if (pos < 0)\n            {\n                pos = 0;\n            }\n\n            int size = 0;\n            if (pos < m_len)\n            {\n                size = m_len - pos;\n            }\n\n            Buffer.BlockCopy(m_buff, pos, m_buff, 0, size);\n            m_len = size;\n            m_pos = 0;\n        }\n\n        /// <summary>\n        /// 将位置设置到最大\n        /// </summary>\n\n\n\n        private int UpdateLenAndGetWritePos(int writePos, int writeLen)\n        {\n            if (writePos == -1)\n            {\n                if (m_len + writeLen > m_capacity)\n                {\n                    throw new Exception(\"SGFBuffer out of capacity.\");\n                }\n\n                writePos = m_len;\n                m_len = writePos + writeLen;\n            }\n            else\n            {\n                if (writePos + writeLen > m_capacity)\n                {\n                    throw new Exception(\"SGFBuffer out of capacity.\");\n                }\n\n                if (writePos + writeLen > m_len)\n                {\n                    m_len = writePos + writeLen;\n                }\n            }\n\n            return writePos;\n        }\n\n        /// <summary>\n        /// 将Byte[]写入Buffer的末尾\n        /// 不移动游标，返回长度\n        /// </summary>\n        public int AddBytes(byte[] src, int srcOffset = 0, int count = 0)\n        {\n            if (count <= 0)\n            {\n                count = src.Length - srcOffset;\n            }\n            if (m_len + count > m_capacity)\n            {\n                throw new Exception(\"SGFBuffer(\" + m_len + \"+\" + count + \") Out of Capacity(\" + m_capacity + \").\");\n            }\n\n            Buffer.BlockCopy(src, srcOffset, m_buff, m_len, count);\n            m_len += count;\n            //m_pos += count; //不移动游标\n            return m_len;\n        }\n\n        public int AddBuffer(NetBuffer src)\n        {\n            return AddBytes(src.m_buff, 0, src.m_len);\n        }\n\n        /// <summary>\n        /// 把src对象的数组copy到本对象，从dstOffect的地方开始\n        /// 不移动游标，返回长度\n        /// </summary>\n        public int CopyWith(NetBuffer src, int dstOffset = 0, bool bResetLen = false)\n        {\n            return CopyWith(src, 0, dstOffset, bResetLen);\n        }\n\n        /// <summary>\n        /// 把src对象的数组从srcOffset开始copy到本对象从dstOffect的地方开始\n        /// 不移动游标，返回长度\n        /// </summary>\n        public int CopyWith(NetBuffer src, int srcOffset, int dstOffset = 0, bool bResetLen = false)\n        {\n            Buffer.BlockCopy(src.m_buff, srcOffset, m_buff, dstOffset, src.m_len);\n\n            int newLen = dstOffset + src.m_len - srcOffset;\n            if (newLen > m_len || bResetLen)\n            {\n                m_len = newLen;\n            }\n            return m_len;\n        }\n\n        /// <summary>\n        /// 从指定Pos增加指定Len\n        /// </summary>\n        public void AddLength(int len, int writePos = -1)\n        {\n            UpdateLenAndGetWritePos(writePos, len);\n            if (writePos == 0)\n            {\n                m_len = len;\n            }\n        }\n\n\n        //=====================================================\n        //写入数据,如果WritePos是-1，则写在Buffer末尾。\n        //否则写在WritePos的位置\n        //由于很多时候不是按顺序写的，所以写入时，不改变内部的Pos。\n        //但是会返回当前写入后的新Pos值\n\n        public int WriteByte(byte value, int writePos = -1)\n        {\n            int pos = UpdateLenAndGetWritePos(writePos, 1);\n            m_buff[pos] = value;\n            return pos + 1;\n        }\n\n        public int WriteShort(short value, int writePos = -1)\n        {\n            int pos = UpdateLenAndGetWritePos(writePos, 2);\n            m_buff[pos + 0] = (byte)(value >> 8 & 0xFF);\n            m_buff[pos + 1] = (byte)(value >> 0 & 0xFF);\n            return pos + 2;\n        }\n        public int WriteInt(int value, int writePos = -1)\n        {\n            int pos = UpdateLenAndGetWritePos(writePos, 4);\n            m_buff[pos + 0] = (byte)(value >> 24 & 0xFF);\n            m_buff[pos + 1] = (byte)(value >> 16 & 0xFF);\n            m_buff[pos + 2] = (byte)(value >> 08 & 0xFF);\n            m_buff[pos + 3] = (byte)(value >> 00 & 0xFF);\n            return pos + 4;\n        }\n\n\n\n        public int WriteUShort(ushort value, int writePos = -1)\n        {\n            return WriteShort((short)value, writePos);\n        }\n\n        public int WriteUInt(uint value, int writePos = -1)\n        {\n            return WriteInt((int)value, writePos);\n        }\n\n\n        public int WriteBytes(byte[] src, int srcOffset, int count, int writePos = -1)\n        {\n            int pos = UpdateLenAndGetWritePos(writePos, count);\n            Buffer.BlockCopy(src, srcOffset, m_buff, pos, count);\n            return pos + count;\n        }\n\n\n        public int WriteBytes(byte[] value, int writePos = -1)\n        {\n            return WriteBytes(value, 0, value.Length, writePos);\n        }\n\n        public int WriteDouble(double value, int writePos = -1)\n        {\n            byte[] bytes = BitConverter.GetBytes(value);\n            return WriteBytes(NetBuffer.ReverseOrder(bytes), writePos);\n        }\n\n        public int WriteFloat(float value, int writePos = -1)\n        {\n            byte[] bytes = BitConverter.GetBytes(value);\n            return WriteBytes(NetBuffer.ReverseOrder(bytes), writePos);\n        }\n\n        public void WriteLong(long l, int writePos = -1)\n        {\n            byte[] bytes = BitConverter.GetBytes(l);\n            this.WriteBytes(NetBuffer.ReverseOrder(bytes), writePos);\n        }\n\n        public void WriteULong(ulong l, int writePos = -1)\n        {\n            byte[] bytes = BitConverter.GetBytes(l);\n            this.WriteBytes(NetBuffer.ReverseOrder(bytes), writePos);\n        }\n\n        public int WriteUTF8(string value, int writePos = -1)\n        {\n            byte[] tmp = Encoding.UTF8.GetBytes(value);\n            int nextPos = WriteInt(tmp.Length, writePos);\n            return WriteBytes(tmp, nextPos);\n        }\n\n        public int Skip(int count)\n        {\n            m_pos += count;\n            return m_pos;\n        }\n\n\n        //=============================================================\n        ///读取数据\n        /// \n\n\n        public void ReadBytes(byte[] dst, int dstOffset, int count)\n        {\n            Buffer.BlockCopy(this.m_buff, this.m_pos, dst, dstOffset, count);\n            this.m_pos += count;\n        }\n\n        public byte[] ReadBytes(int count)\n        {\n            byte[] dst = new byte[count];\n            ReadBytes(dst, 0, count);\n            return dst;\n        }\n\n        public bool ReadBool()\n        {\n            return (this.m_buff[this.m_pos++] == 1);\n        }\n\n        public byte ReadByte()\n        {\n            return this.m_buff[this.m_pos++];\n        }\n\n        public double ReadDouble()\n        {\n            ReadBytes(m_64b, 0, 8);\n            return BitConverter.ToDouble(NetBuffer.ReverseOrder(m_64b), 0);\n        }\n\n        public float ReadFloat()\n        {\n            ReadBytes(m_32b, 0, 4);\n            return BitConverter.ToSingle(NetBuffer.ReverseOrder(m_32b), 0);\n        }\n\n        public int ReadInt()\n        {\n            ReadBytes(m_32b, 0, 4);\n            return BitConverter.ToInt32(NetBuffer.ReverseOrder(m_32b), 0);\n        }\n\n        public uint ReadUInt()\n        {\n            ReadBytes(m_32b, 0, 4);\n            return BitConverter.ToUInt32(NetBuffer.ReverseOrder(m_32b), 0);\n        }\n\n        public long ReadLong()\n        {\n            ReadBytes(m_64b, 0, 8);\n            return BitConverter.ToInt64(NetBuffer.ReverseOrder(m_64b), 0);\n        }\n\n        public ulong ReadULong()\n        {\n            ReadBytes(m_64b, 0, 8);\n            return BitConverter.ToUInt64(NetBuffer.ReverseOrder(m_64b), 0);\n        }\n\n        public short ReadShort()\n        {\n            ReadBytes(m_16b, 0, 2);\n            return BitConverter.ToInt16(NetBuffer.ReverseOrder(m_16b), 0);\n        }\n\n        public ushort ReadUShort()\n        {\n            ReadBytes(m_16b, 0, 2);\n            return BitConverter.ToUInt16(NetBuffer.ReverseOrder(m_16b), 0);\n        }\n\n\n        public string ReadUTF()\n        {\n            int count = this.ReadInt();\n            string str = Encoding.UTF8.GetString(this.m_buff, this.m_pos, count);\n            this.m_pos += count;\n            return str;\n        }\n\n\n\n\n\n    }\n\n\n    /// <summary>\n    /// 字节读出\n    /// </summary>\n    public class NetBufferReader : NetBuffer\n    {\n        static public NetBufferReader DEFAULT = new NetBufferReader();\n\n        public NetBufferReader(byte[] buff = null)\n            : base(buff)\n        {\n            if (buff != null)\n            {\n                m_len = buff.Length;\n            }\n        }\n    }\n\n    /// <summary>\n    /// 字节写入...\n    /// </summary>\n    public class NetBufferWriter : NetBuffer\n    {\n        static public NetBufferWriter DEFAULT = new NetBufferWriter();\n\n        public NetBufferWriter(byte[] buff = null)\n            : base(buff)\n        {\n\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "SGFCore/Network/Core/NetErrorCode.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 网络模块\n * Network\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nnamespace SGF.Network.Core\n{\n    public enum NetErrorCode\n    {\n        UnkownError = -1,\n        NoError = 0,\n        SocketError,\n        Timeout,\n        Disconnected,\n        SessionExpire,\n        DeserializeError,\n        ReconnectFailed\n        //不能超过SocketError的枚举值\n    }\n}\n"
  },
  {
    "path": "SGFCore/Network/Core/RPCLite/RPCManagerBase.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 实现基于C#反射机制的RPC基础功能\n * 它需要结合具体的通讯模块使用\n * Implement RPC basic functions based on C# reflection mechanism\n * It needs to be used in conjunction with specific communication modules\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing SGF.Utils;\nusing System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Text;\n\n\nnamespace SGF.Network.Core.RPCLite\n{\n\n    public class RPCRequestAttribute : Attribute\n    {\n\n    }\n\n    public class RPCResponseAttribute : Attribute\n    {\n\n    }\n\n    public class RPCNotifyAttribute : Attribute\n    {\n        \n    }\n\n\n    public class RPCMethodHelper\n    {\n        public object listener;\n        public MethodInfo method;\n\n        \n    }\n\n    public class RPCManagerBase\n    {\n        protected List<object> m_listListener;\n        protected DictionarySafe<string, RPCMethodHelper> m_mapMethodHelper;\n\n\n        public void Init()\n        {\n            m_listListener = new List<object>();\n            m_mapMethodHelper = new DictionarySafe<string, RPCMethodHelper>();\n        }\n\n        public void Clean()\n        {\n            m_listListener.Clear();\n\n            foreach (var pair in m_mapMethodHelper)\n            {\n                pair.Value.listener = null;\n                pair.Value.method = null;\n            }\n            m_mapMethodHelper.Clear();\n        }\n\n        public void Dump()\n        {\n            StringBuilder sb = new StringBuilder();\n\n            foreach (var pair in m_mapMethodHelper)\n            {\n                RPCMethodHelper helper = pair.Value;\n                sb.AppendFormat(\"\\t<name:{0}, \\tmethod:{1}.{2}>\\n\", pair.Key,\n                    helper.method.DeclaringType.Name, helper.method.Name);\n            }\n\n            Debuger.LogWarning(\"\\nRPC Cached Methods ({0}):\\n{1}\", m_mapMethodHelper.Count, sb);\n        }\n\n\n        public void RegisterListener(object listener)\n        {\n            if (!m_listListener.Contains(listener))\n            {\n                Debuger.Log(\"{0}\", listener.GetType().Name);\n                m_listListener.Add(listener);\n            }\n        }\n\n        public void UnRegisterListener(object listener)\n        {\n            if (m_listListener.Contains(listener))\n            {\n                Debuger.Log(\"{0}\", listener.GetType().Name);\n                m_listListener.Remove(listener);\n            }\n\n            List<string> listMethods = new List<string>();\n\n            foreach (var helper in m_mapMethodHelper)\n            {\n                if (helper.Value.listener == listener)\n                {\n                    listMethods.Add(helper.Key);\n                }\n            }\n            for (int i = 0; i < listMethods.Count; i++)\n            {\n                m_mapMethodHelper.Remove(listMethods[i]);\n            }\n        }\n        public RPCMethodHelper GetMethodHelper(string name)\n        {\n            var helper = m_mapMethodHelper[name];\n            if (helper == null)\n            {\n                MethodInfo mi = null;\n                object listener = null;\n                for (int i = 0; i < m_listListener.Count; i++)\n                {\n                    listener = m_listListener[i];\n                    mi = listener.GetType().GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);\n                    if (mi != null)\n                    {\n                        break;\n                    }\n                }\n\n                if (mi != null)\n                {\n                    helper = new RPCMethodHelper();\n                    helper.listener = listener;\n                    helper.method = mi;\n                    m_mapMethodHelper.Add(name, helper);\n                }\n            }\n\n            return helper;\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/Core/RPCLite/RPCMessage.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 实现基于C#反射机制的RPC基础功能\n * 它需要结合具体的通讯模块使用\n * Implement RPC basic functions based on C# reflection mechanism\n * It needs to be used in conjunction with specific communication modules\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing ProtoBuf;\nusing SGF.Codec;\n\nnamespace SGF.Network.Core.RPCLite\n{\n\n    [ProtoContract]\n    public class RPCMessage\n    {\n        [ProtoMember(1)]\n        public string name;\n\n        [ProtoMember(2)]\n        public List<RPCRawArg> raw_args = new List<RPCRawArg>();\n\n        public object[] args\n        {\n            get\n            {\n                var list = new List<object>();\n                for (int i = 0; i < raw_args.Count; i++)\n                {\n                    list.Add(raw_args[i].value);\n                }\n                return list.ToArray();\n            }\n\n            set\n            {\n                raw_args = new List<RPCRawArg>();\n                object[] list = value;\n                for (int i = 0; i < list.Length; i++)\n                {\n                    var raw_arg = new RPCRawArg();\n                    raw_arg.value = list[i];\n                    raw_args.Add(raw_arg);\n                }\n            }\n        }\n\n\n    }\n\n\n    [ProtoContract]\n    public class RPCRawArg\n    {\n        [ProtoMember(1)]\n        public RPCArgType type;\n        [ProtoMember(2)]\n        public byte[] raw_value;\n\n        public object value\n        {\n            get\n            {\n                if (raw_value == null || raw_value.Length == 0)\n                {\n                    return null;\n                }\n\n                NetBufferReader reader = new NetBufferReader(raw_value);\n                switch (type)\n                {\n                    case RPCArgType.Int: return reader.ReadInt();\n                    case RPCArgType.UInt: return reader.ReadUInt();\n                    case RPCArgType.Long: return reader.ReadLong();\n                    case RPCArgType.ULong: return reader.ReadULong();\n                    case RPCArgType.Short: return reader.ReadShort();\n                    case RPCArgType.UShort: return reader.ReadUShort();\n                    case RPCArgType.Double: return reader.ReadDouble();\n                    case RPCArgType.Float: return reader.ReadFloat();\n                    case RPCArgType.String: return Encoding.UTF8.GetString(raw_value);\n                    case RPCArgType.Byte: return reader.ReadByte();\n                    case RPCArgType.Bool: return reader.ReadByte() != 0;\n                    case RPCArgType.ByteArray: return raw_value;\n                    case RPCArgType.PBObject: return raw_value;//由于数据层是不知道具体类型，由反射层去反序列化\n                    default: return raw_value;\n                }\n\n            }\n            set\n            {\n                NetBuffer writer;\n                object v = value;\n                if (v is int)\n                {\n                    type = RPCArgType.Int;\n                    raw_value = BitConverter.GetBytes((int) v);\n                    NetBuffer.ReverseOrder(raw_value);\n                }\n                else if (v is uint)\n                {\n                    type = RPCArgType.UInt;\n                    raw_value = BitConverter.GetBytes((uint)v);\n                    NetBuffer.ReverseOrder(raw_value);\n                }\n                else if (v is long)\n                {\n                    type = RPCArgType.Long;\n                    raw_value = BitConverter.GetBytes((long)v);\n                    NetBuffer.ReverseOrder(raw_value);\n                }\n                else if (v is ulong)\n                {\n                    type = RPCArgType.ULong;\n                    raw_value = BitConverter.GetBytes((ulong)v);\n                    NetBuffer.ReverseOrder(raw_value);\n                }\n                else if (v is short)\n                {\n                    type = RPCArgType.Short;\n                    raw_value = BitConverter.GetBytes((short)v);\n                    NetBuffer.ReverseOrder(raw_value);\n                }\n                else if (v is ushort)\n                {\n                    type = RPCArgType.UShort;\n                    raw_value = BitConverter.GetBytes((ushort)v);\n                    NetBuffer.ReverseOrder(raw_value);\n                }\n                else if (v is double)\n                {\n                    type = RPCArgType.Double;\n                    raw_value = BitConverter.GetBytes((double)v);\n                }\n                else if (v is float)\n                {\n                    type = RPCArgType.Float;\n                    raw_value = BitConverter.GetBytes((float)v);\n                    NetBuffer.ReverseOrder(raw_value);\n                }\n                else if (v is string)\n                {\n                    type = RPCArgType.String;\n                    raw_value = Encoding.UTF8.GetBytes((string)v);\n                }\n                else if (v is byte)\n                {\n                    type = RPCArgType.Byte;\n                    raw_value = new[] { (byte)v };\n                }\n                else if (v is bool)\n                {\n                    type = RPCArgType.Bool;\n                    raw_value = new[] { (bool)v ? (byte)1 : (byte)0 };\n                }\n                else if (v is byte[])\n                {\n                    type = RPCArgType.ByteArray;\n                    raw_value = new byte[((byte[])v).Length];\n                    Buffer.BlockCopy((byte[])v, 0, raw_value, 0, raw_value.Length);\n                }\n                else\n                {\n                    var bytes = PBSerializer.NSerialize(v);\n                    if (bytes != null)\n                    {\n                        type = RPCArgType.PBObject;\n                        raw_value = new byte[bytes.Length];\n                        Buffer.BlockCopy(bytes, 0, raw_value, 0, raw_value.Length);\n                    }\n                    else\n                    {\n                        type = RPCArgType.Unkown;\n                        Debuger.LogError(\"该参数无法序列化！value:{0}\", v);\n                    }\n                }\n            }\n        }\n    }\n\n\n    public enum RPCArgType\n    {\n        Unkown = 0,\n        Int = 1,\n        UInt = 2,\n        Long = 3,\n        ULong = 4,\n        Short = 5,\n        UShort = 6,\n        Double = 8,\n        Float = 9,\n        String = 10,\n        Byte = 11,\n        Bool = 12,\n        ByteArray = 31,\n        PBObject = 32\n    }\n}"
  },
  {
    "path": "SGFCore/Network/Core/SocketAsyncEventArgsPool.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System.Collections.Generic;\nusing System.Net.Sockets;\n\n\nnamespace SGF.Network.Core\n{\n    public class SocketAsyncEventArgsPool\n    {\n        private readonly int m_poolSize;\n        private readonly int m_packedBufferSize;\n        private readonly Stack<SocketAsyncEventArgs> m_pool = \n            new Stack<SocketAsyncEventArgs>();\n        \n        public SocketAsyncEventArgsPool(int packetBufferSize, int poolSize)\n        {\n            this.m_packedBufferSize = packetBufferSize;\n            this.m_poolSize = poolSize;\n        }\n\n        public SocketAsyncEventArgs Acquire()\n        {\n            SocketAsyncEventArgs e = null;\n            lock (m_pool)\n            {\n                if (m_pool.Count > 0)\n                {\n                    return m_pool.Pop();\n                }\n            }\n\n            e = new SocketAsyncEventArgs();\n            e.SetBuffer(new byte[this.m_packedBufferSize], 0, this.m_packedBufferSize);\n            return e;\n        }\n\n        public void Release(SocketAsyncEventArgs e)\n        {\n            lock (m_pool)\n            {\n                if (this.m_pool.Count < m_poolSize)\n                {\n                    this.m_pool.Push(e);\n                    return;\n                }\n\n            }\n\n            e.Dispose();\n        }\n\n        public void Clear()\n        {\n            lock (m_pool)\n            {\n                SocketAsyncEventArgs e = null;\n                while (m_pool.Count > 0)\n                {\n                    e = m_pool.Pop();\n                    e.Dispose();\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Network/Core/UdpSocket.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 封装了以Udp模式工作的Socket\n * Encapsulates Sockets working in Udp mode\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Net;\nusing System.Net.Sockets;\n\n\n\nnamespace SGF.Network.Core\n{\n    public class UdpSocket\n    {\n\n\n        //===========================================================\n        public static string LOG_TAG = \"UdpSocket\";\n\n        private bool m_IsActive;\n        private Socket m_SystemSocket;\n        private AddressFamily m_AddrFamily;\n        private bool m_IsBroadcast;\n        private bool m_EnableBlockOnRecv = false;//是否允许在接收数据时阻塞\n\n\n        //===========================================================\n        #region 构造与析构\n        public UdpSocket(AddressFamily family, bool enableBlockOnRecv = false)\n        {\n            m_EnableBlockOnRecv = enableBlockOnRecv;\n            m_AddrFamily = family;\n            m_SystemSocket = new Socket(m_AddrFamily, SocketType.Dgram, ProtocolType.Udp);\n        }\n\n        public AddressFamily AddressFamily { get { return m_AddrFamily; } }\n\n        public void Dispose()\n        {\n            Close();\n        }\n\n\n        public void Close()\n        {\n            if (m_SystemSocket != null)\n            {\n                try\n                {\n                    m_SystemSocket.Shutdown(SocketShutdown.Both);\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(LOG_TAG, \"Close() \" + e.Message + e.StackTrace);\n                }\n\n                m_SystemSocket.Close();\n                m_SystemSocket = null;\n            }\n\n            m_IsActive = false;\n            GC.SuppressFinalize(this);\n        }\n\n      \n\n        public string SelfIP\n        {\n            get\n            {\n\t\t\t\treturn IPUtils.SelfIP; \n                \n            }\n        }\n\n        public int SelfPort\n        {\n            get\n            {\n                IPEndPoint ipep = m_SystemSocket.LocalEndPoint as IPEndPoint;\n                return ipep.Port;\n            }\n        }\n\n        public Socket SystemSocket { get { return m_SystemSocket; } }\n\n        public int Available { get { return m_SystemSocket.Available; } }\n\n        #endregion\n\n        //------------------------------------------------------------\n#region 绑定端口函数\n        public int Bind(int port = 0)\n        {\n            Debuger.Log(LOG_TAG, \"Bind() port = \" + port);\n            if (m_SystemSocket == null)\n            {\n                return 0;\n            }\n\n            //如果Bind的端口为0，则会随机分配一个端口\n            IPEndPoint ipep = IPUtils.GetIPEndPointAny(m_AddrFamily, port);\n            m_SystemSocket.Bind(ipep);\n            m_IsActive = true;\n            return SelfPort;\n        }\n\n\n        #endregion\n\n\n        //------------------------------------------------------------\n#region ReceiveFrom和SendTo函数\n        public int ReceiveFrom(byte[] buffer, int maxsize, ref IPEndPoint remoteEP)\n        {\n            int cnt = 0;\n\n            EndPoint ip = null;\n\n            if (!m_EnableBlockOnRecv)\n            {\n                if (m_SystemSocket.Available <= 0)\n                {\n                    return 0;\n                }\n            }\n\n\n            if (m_AddrFamily == AddressFamily.InterNetwork)\n            {\n                //如果是IPv4环境，则(与Android的处理一样)\n                ip = IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, 0);\n                cnt = m_SystemSocket.ReceiveFrom(buffer, maxsize, SocketFlags.None, ref ip);\n\n                if (cnt > 0 && remoteEP != null && !remoteEP.Equals(ip))\n                {\n                    Debuger.LogWarning(LOG_TAG, \"ReceiveFrom() 收到一个自来陌生IP:Port(\" + ip + \")的数据包！\");\n                    return 0;\n                }\n            }\n            else\n            {\n                //如果是IPv6环境，则：\n                ip = remoteEP;\n                cnt = m_SystemSocket.ReceiveFrom(buffer, maxsize, SocketFlags.None, ref ip);\n            }\n\n            remoteEP = ip as IPEndPoint;\n\n            return cnt;\n        }\n\n\n\n\n        public int SendTo(byte[] buffer, int size, IPEndPoint remoteEP)\n        {\n            int cnt = 0;\n\n\n            //如果无法使用LocalSocket再使用SystemSocket\n            if (cnt == 0)\n            {\n                cnt = m_SystemSocket.SendTo(buffer, 0, size, SocketFlags.None, remoteEP);\n            }\n\n            return cnt;\n        }\n        #endregion\n    }\n}\n\n"
  },
  {
    "path": "SGFCore/Network/Debuger/NetDebugFile.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 提供网络相关的调试功能\n * Provides network-related debugging features\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Collections.Generic;\nusing SGF.Codec;\n\nusing SGF.Network.protocol;\nusing SGF.Utils;\n\n\nnamespace SGF.Network\n{\n    public class NetDebugFile\n    {\n        private NetDebugFileData m_content;\n        public NetDebugFileData Content { get { return m_content; } }\n\n\n        private DictionarySafe<string, List<NetSampleItem>> m_mapAllSampleList;\n\n        private List<string> m_listAllSampleName;\n        public List<string> ListAllSampleName { get { return m_listAllSampleName; } }\n\n        public NetDebugFile()\n        {\n            m_content = new NetDebugFileData();\n            m_mapAllSampleList = new DictionarySafe<string, List<NetSampleItem>>();\n            m_listAllSampleName = new List<string>();\n        }\n\n        public List<NetSampleItem> GetSampleList(string name)\n        {\n            return m_mapAllSampleList[name];\n        }\n\n\n\n        public bool Save(string dirname, string filename)\n        {\n            Debuger.Log(\"\");\n            \n            if (string.IsNullOrEmpty(filename))\n            {\n                return false;\n            }\n\n            string errinfo = \"\";\n            byte[] buffer = PBSerializer.NSerialize(m_content);\n            return FileUtils.SaveFile(dirname + filename, buffer) > 0;\n        }\n\n        public bool Open(string dirname, string filename)\n        {\n            string fullpath = filename;\n            if (!PathUtils.IsFullPath(filename))\n            {\n                fullpath = dirname + \"/\" + filename;\n            }\n\n            return Open(fullpath);\n        }\n\n\n        public bool Open(string fullpath)\n        {\n            Debuger.Log(\"fullpath = \" + fullpath);\n\n            Byte[] bytes = FileUtils.ReadFile(fullpath);\n            if (bytes != null && bytes.Length > 0)\n            {\n                m_content = PBSerializer.NDeserialize<NetDebugFileData>(bytes);\n                return ParserFile();\n            }\n            else\n            {\n                Debuger.LogError(\"File Is Not Exist, Or Open Wrong!\");\n                return false;\n            }\n\n            return true;\n        }\n\n\n\n        private bool ParserFile()\n        {\n            m_mapAllSampleList.Clear();\n            m_listAllSampleName.Clear();\n\n            if (m_content == null)\n            {\n                return false;\n            }\n\n            List<NetSampleItem> listAll = m_content.profiler_samples;\n            for (int i = 0; i < listAll.Count; i++)\n            {\n                NetSampleItem item = listAll[i];\n                List<NetSampleItem> list = m_mapAllSampleList[item.name];\n                if (list == null)\n                {\n                    list = new List<NetSampleItem>();\n                    m_mapAllSampleList.Add(item.name, list);\n                    m_listAllSampleName.Add(item.name);\n                }\n                list.Add(item);\n            }\n\n            return true;\n        }\n\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/Network/Debuger/NetDebuger.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 提供网络相关的调试功能\n * Provides network-related debugging features\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing SGF.MathLite;\nusing SGF.Network.protocol;\n\n\nnamespace SGF.Network\n{\n    public static class NetDebuger\n    {\n        public const string LOG_TAG = \"NetDebuger\";\n        public static string DbgFileName { get; set; }\n        public static string DbgFileDir { get; set; }\n\n        //===========================================================\n        public static bool EnableLog = false;\n        public static bool EnableProfiler = false;\n\n        //===========================================================\n        //弱网络测试\n        public static bool EnableWeakNet = false;\n\n        public static float PacketLossRate = 0;//丢包率\n        public static float JitterRate = 0;//抖动率\n        public static int JitterDelayMin = 0;//MS\n        public static int JitterDelayMax = 0;\n        //===========================================================\n\n        //=========================================================================\n        //=========================================================================\n        #region Profiler采样\n        private static List<NetSampleItem> m_ListNetSamples = new List<NetSampleItem>();\n\n        public static List<NetSampleItem> SampleList\n        {\n            get { return m_ListNetSamples; }\n        }\n\n        public static void ClearSample()\n        {\n            m_ListNetSamples.Clear();\n        }\n\n        public static void AddSample(string tag, string name, int data1 = 0, int data2 = 0, int data3 = 0)\n        {\n            if (EnableProfiler)\n            {\n                NetSampleItem item = new NetSampleItem();\n                item.name = tag + \":\" + name;\n                item.time = DateTime.Now.Ticks;\n                item.data1 = data1;\n                item.data2 = data2;\n                item.data3 = data3;\n\n                m_ListNetSamples.Add(item);\n            }\n        }\n        #endregion\n\n        //=========================================================================\n        //弱网络测试\n        #region 弱网络测试\n        public static int GetJitterDelay()\n        {\n            if (IsNetJitter())\n            {\n                return SGFRandom.Default.Range(JitterDelayMin, JitterDelayMax);\n            }\n            return 0;\n        }\n\n        public static bool IsNetJitter()\n        {\n            return EnableWeakNet && SGFRandom.Default.Rnd() < JitterRate;\n        }\n\n        public static bool IsPacketLoss()\n        {\n            return EnableWeakNet && SGFRandom.Default.Rnd() < PacketLossRate;\n        }\n\n        public static void WeakNetSimulate(object target, byte[] buffer, int size, Action<byte[], int> handler)\n        {\n            \n        }\n\n        public static void WeakNetCancel(object target)\n        {\n\n        }\n\n        private static void OnDelayInvoke(object[] args)\n        {\n            Action<byte[], int> handler = (Action<byte[], int>)args[0];\n\n            if (handler != null)\n            {\n                handler((byte[])args[1], (int)args[2]);\n            }\n        }\n\n        #endregion\n    }\n}\n\n\n"
  },
  {
    "path": "SGFCore/Network/Debuger/net_debuger.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\n// Generated from: fsp_debuger.proto\nnamespace SGF.Network.protocol\n{\n  [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@\"NetSampleItem\")]\n  public partial class NetSampleItem : global::ProtoBuf.IExtensible\n  {\n      public NetSampleItem() { }\n    \n    private string _name = \"\";\n    [global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@\"name\", DataFormat = global::ProtoBuf.DataFormat.Default)]\n    [global::System.ComponentModel.DefaultValue(\"\")]\n    public string name\n    {\n      get { return _name; }\n      set { _name = value; }\n    }\n    private long _time = default(long);\n    [global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@\"time\", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]\n    [global::System.ComponentModel.DefaultValue(default(long))]\n    public long time\n    {\n      get { return _time; }\n      set { _time = value; }\n    }\n    private int _data1 = default(int);\n    [global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@\"data1\", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]\n    [global::System.ComponentModel.DefaultValue(default(int))]\n    public int data1\n    {\n      get { return _data1; }\n      set { _data1 = value; }\n    }\n    private int _data2 = default(int);\n    [global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@\"data2\", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]\n    [global::System.ComponentModel.DefaultValue(default(int))]\n    public int data2\n    {\n      get { return _data2; }\n      set { _data2 = value; }\n    }\n    private int _data3 = default(int);\n    [global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@\"data3\", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]\n    [global::System.ComponentModel.DefaultValue(default(int))]\n    public int data3\n    {\n      get { return _data3; }\n      set { _data3 = value; }\n    }\n    private global::ProtoBuf.IExtension extensionObject;\n    global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)\n      { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }\n  }\n\n  [global::System.Serializable, global::ProtoBuf.ProtoContract(Name = @\"NetDebugFileData\")]\n  public partial class NetDebugFileData : global::ProtoBuf.IExtensible\n  {\n      public NetDebugFileData() { }\n\n      private readonly global::System.Collections.Generic.List<SGF.Network.protocol.NetSampleItem> _profiler_samples = new global::System.Collections.Generic.List<SGF.Network.protocol.NetSampleItem>();\n    [global::ProtoBuf.ProtoMember(1, Name=@\"profiler_samples\", DataFormat = global::ProtoBuf.DataFormat.Default)]\n      public global::System.Collections.Generic.List<SGF.Network.protocol.NetSampleItem> profiler_samples\n    {\n      get { return _profiler_samples; }\n    }\n  \n    private global::ProtoBuf.IExtension extensionObject;\n    global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)\n      { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }\n  }\n  \n}"
  },
  {
    "path": "SGFCore/Network/FSPLite/Client/FSPClient.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Net;\nusing System.Net.NetworkInformation;\nusing System.Net.Sockets;\nusing System.Threading;\nusing SGF.Codec;\nusing SGF.Extension;\nusing SGF.Network.Core;\nusing SGF.Time;\nusing SGF.Utils;\n\nnamespace SGF.Network.FSPLite.Client\n{\n    public class FSPClient\n    {\n        private bool m_IsRunning = false;\n\n\n        //基础通讯部分\n        private string m_ip;\n        private int m_port;\n        private uint m_sid;\n        private Socket m_SystemSocket;\n        private Thread m_ThreadRecv;\n        private IPEndPoint m_RemoteEndPoint;\n        private bool m_WaitForReconnect = false;\n        private uint m_lastRecvTimestamp = 0;\n\n\n        //KCP部分\n        private KCP m_Kcp;\n        private SwitchQueue<byte[]> m_RecvBufQueue = new SwitchQueue<byte[]>(128);\n        private bool m_NeedKcpUpdateFlag = false;\n        private uint m_NextKcpUpdateTime = 0;\n\n\n        private int m_authId;\n\n        //接收逻辑\n        private Action<FSPFrame> m_RecvListener;\n        private byte[] m_RecvBufferTemp = new byte[4096];\n\n        //发送逻辑\n        private FSPDataC2S m_TempSendData = new FSPDataC2S();\n        private byte[] m_SendBufferTemp = new byte[4096];\n\n\n        //------------------------------------------------------------\n        #region 构造相关\n        public void Init(uint sid)\n        {\n            Debuger.Log(\"sid:{0}\", sid);\n            m_sid = sid;\n            m_TempSendData.sid = sid;\n            m_TempSendData.msgs.Add(new FSPMessage());\n\n            m_Kcp = new KCP(m_sid, HandleKcpSend);\n            m_Kcp.NoDelay(1, 10, 2, 1);\n            m_Kcp.WndSize(128, 128);\n        }\n\n\n        public void Clean()\n        {\n            Debuger.Log();\n            if (m_Kcp != null)\n            {\n                m_Kcp.Dispose();\n                m_Kcp = null;\n            }\n            m_RecvListener = null;\n            Close();\n        }\n\n        #endregion\n        \n        //------------------------------------------------------------\n        #region 设置参数\n        public void SetFSPAuthInfo(int authId)\n        {\n            Debuger.Log(authId);\n            m_authId = authId;\n        }\n\n        public void SetFSPListener(Action<FSPFrame> listener)\n        {\n            Debuger.Log();\n            m_RecvListener = listener;\n\n        }\n\n\n        public void VerifyAuth()\n        {\n            Debuger.Log();\n            SendFSP(0, FSPBasicCmd.AUTH, m_authId);\n        }\n\n\n        #endregion\n\n        //------------------------------------------------------------\n\n        #region 连接相关逻辑\n\n        public bool IsRunning { get { return m_IsRunning; } }\n\n        public bool Connect(string ip, int port)\n        {\n            if (m_SystemSocket != null)\n            {\n                Debuger.LogError(\"无法建立连接，需要先关闭上一次连接！\");\n                return false;\n            }\n\n            Debuger.Log(\"建立基础连接， host = {0}, port = {1}\", ip, port);\n            m_ip = ip;\n            m_port = port;\n            m_lastRecvTimestamp = (uint)TimeUtils.GetTotalMillisecondsSince1970();\n\n            try\n            {\n                m_RemoteEndPoint = IPUtils.GetHostEndPoint(m_ip, m_port);\n                if (m_RemoteEndPoint == null)\n                {\n                    Debuger.LogError(\"无法将Host解析为IP！\");\n                    Close();\n                    return false;\n                }\n                Debuger.Log(\"HostEndPoint = {0}\", m_RemoteEndPoint.ToString());\n\n                //创建Socket\n                Debuger.Log(\"创建Socket, AddressFamily = {0}\", m_RemoteEndPoint.AddressFamily);\n                m_SystemSocket = new Socket(m_RemoteEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);\n                m_SystemSocket.Bind(IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, 0));\n\n\n                m_IsRunning = true;\n\n                m_ThreadRecv = new Thread(Thread_Recv) { IsBackground = true };\n                m_ThreadRecv.Start();\n\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(e.Message + e.StackTrace);\n                Close();\n                return false;\n            }\n\n            return true;\n        }\n\n\n        private void Close()\n        {\n            Debuger.Log();\n\n            m_IsRunning = false;\n\n            if (m_ThreadRecv != null)\n            {\n                m_ThreadRecv.Interrupt();\n                m_ThreadRecv = null;\n            }\n\n            if (m_SystemSocket != null)\n            {\n                try\n                {\n                    m_SystemSocket.Shutdown(SocketShutdown.Both);\n\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(e.Message + e.StackTrace);\n                }\n\n                m_SystemSocket.Close();\n                m_SystemSocket = null;\n            }\n        }\n\n\n        private void Reconnect()\n        {\n            m_WaitForReconnect = false;\n            Close();\n            Connect(m_ip, m_port);\n            VerifyAuth();\n        }\n\n        #endregion\n\n        //------------------------------------------------------------\n\n\n\n\n\n\n\n        private void Thread_Recv()\n        {\n            while (m_IsRunning)\n            {\n                try\n                {\n                    DoReceiveInThread();\n                }\n                catch (SocketException se)\n                {\n                    Debuger.LogWarning(\"SocketErrorCode:{0}, {1}\", se.SocketErrorCode, se.Message);\n                    Thread.Sleep(1);\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(e.Message + \"\\n\" + e.StackTrace);\n                    Thread.Sleep(1);\n                }\n            }\n        }\n\n\n        private void DoReceiveInThread()\n        {\n            EndPoint remotePoint = IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, 0);\n            int cnt = m_SystemSocket.ReceiveFrom(m_RecvBufferTemp, m_RecvBufferTemp.Length, SocketFlags.None, ref remotePoint);\n\n            if (cnt > 0)\n            {\n                if (!m_RemoteEndPoint.Equals(remotePoint))\n                {\n                    Debuger.LogError(\"收到非目标服务器的数据！\");\n                    return;\n                }\n\n                byte[] dst = new byte[cnt];\n                Buffer.BlockCopy(m_RecvBufferTemp, 0, dst, 0, cnt);\n                m_RecvBufQueue.Push(dst);\n                \n            }\n\n\n        }\n\n\n        private void DoReceiveInMain()\n        {\n            m_RecvBufQueue.Switch();\n            while (!m_RecvBufQueue.Empty())\n            {\n                var recvBufferRaw = m_RecvBufQueue.Pop();\n                int ret = m_Kcp.Input(recvBufferRaw, recvBufferRaw.Length);\n\n                //收到的不是一个正确的KCP包\n                if (ret < 0)\n                {\n                    Debuger.LogError(\"收到不正确的KCP包, Ret:{0}\", ret);\n                    return;\n                }\n\n                m_NeedKcpUpdateFlag = true;\n\n                for (int size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize())\n                {\n                    var recvBuffer = new byte[size];\n                    if (m_Kcp.Recv(recvBuffer) > 0)\n                    {\n                        m_lastRecvTimestamp = (uint)TimeUtils.GetTotalMillisecondsSince1970();\n\n                        var data = PBSerializer.NDeserialize<FSPDataS2C>(recvBuffer);\n\n                        if (m_RecvListener != null)\n                        {\n                            for (int i = 0; i < data.frames.Count; i++)\n                            {\n                                m_RecvListener(data.frames[i]);\n                            }\n                        }\n\n                    }\n                }\n\n            }\n\n\n        }\n\n\n        //------------------------------------------------------------\n        #region 发送相关逻辑\n\n        private void HandleKcpSend(byte[] buffer, int size)\n        {\n            m_SystemSocket.SendTo(buffer, 0, size, SocketFlags.None, m_RemoteEndPoint);\n        }\n\n\n        public bool SendFSP(int clientFrameId, int cmd, int arg)\n        {\n            return SendFSP(clientFrameId, cmd, new int[] {arg});\n        }\n\n\n        public bool SendFSP(int clientFrameId, int cmd, int[] args)\n        {\n            Debuger.Log(\"clientFrameId:{0}, cmd:{1}, args:{2}\", clientFrameId, cmd, args.ToListString());\n\n            if (m_IsRunning)\n            {\n\n                FSPMessage msg = m_TempSendData.msgs[0];\n                msg.cmd = cmd;\n                msg.clientFrameId = clientFrameId;\n                msg.args = args;\n\n                m_TempSendData.msgs.Clear();\n                m_TempSendData.msgs.Add(msg);\n                \n\n                int len = PBSerializer.NSerialize(m_TempSendData, m_SendBufferTemp);\n                m_Kcp.Send(m_SendBufferTemp, len);\n                return len > 0;\n            }\n\n            return false;\n        }\n\n\n        #endregion\n\n        //------------------------------------------------------------\n\n        private void CheckTimeout()\n        {\n            uint current = (uint)TimeUtils.GetTotalMillisecondsSince1970();\n            var dt = current - m_lastRecvTimestamp;\n            if (dt > 5000)\n            {\n                m_WaitForReconnect = true;\n            }\n            \n        }\n\n\n        public void Tick()\n        {\n            if (!m_IsRunning)\n            {\n                return;\n            }\n\n            DoReceiveInMain();\n\n            uint current = (uint)TimeUtils.GetTotalMillisecondsSince1970();\n            if (m_NeedKcpUpdateFlag || current >= m_NextKcpUpdateTime)\n            {\n                if (m_Kcp != null)\n                {\n                    m_Kcp.Update(current);\n                    m_NextKcpUpdateTime = m_Kcp.Check(current);\n                    m_NeedKcpUpdateFlag = false;\n\n                }\n            }\n\n\n            if (m_WaitForReconnect)\n            {\n                if (NetworkInterface.GetIsNetworkAvailable())\n                {\n                    Reconnect();\n                }\n                else\n                {\n                    Debuger.Log(\"等待重连，但是网络不可用！\");\n                }\n            }\n            \n\n            CheckTimeout();\n        }\n\n\n\n        public string ToDebugString()\n        {\n            return string.Format(\"ip:{0}, port:{1}\", m_ip, m_port);\n            \n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/FSPLite/Client/FSPFrameController.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nnamespace SGF.Network.FSPLite.Client\n{\n    public class FSPFrameController\n    {\n        //缓冲控制\n        private int m_ClientFrameRateMultiple = 2;\n        private int m_JitterBuffSize = 0;\n        private bool m_IsInBuffing = false;\n        private int m_NewestFrameId;\n\n\n        //加速控制\n        private bool m_EnableSpeedUp = true;\n        private int m_DefaultSpeed = 1;\n        private bool m_IsInSpeedUp = false;\n\n        //自动缓冲\n        private bool m_EnableAutoBuff = true;\n        private int m_AutoBuffCnt = 0;\n        private int m_AutoBuffInterval = 15;\n\n\n        public bool IsInBuffing { get { return m_IsInBuffing; } }\n        public bool IsInSpeedUp { get { return m_IsInSpeedUp; } }\n        public int JitterBufferSize { get { return m_JitterBuffSize; } set { m_JitterBuffSize = value; } }\n        public int NewestFrameId { get { return m_NewestFrameId; } }\n\n\n        public void Start(FSPParam param)\n        {\n            SetParam(param);\n        }\n\n        public void Stop()\n        {\n            \n        }\n\n        public void SetParam(FSPParam param)\n        {\n            m_ClientFrameRateMultiple = param.clientFrameRateMultiple;\n            m_JitterBuffSize = param.jitterBufferSize;\n            m_EnableSpeedUp = param.enableSpeedUp;\n            m_DefaultSpeed = param.defaultSpeed;\n            m_EnableAutoBuff = param.enableAutoBuffer;\n\n        }\n\n\n        public void AddFrameId(int frameId)\n        {\n            m_NewestFrameId = frameId;\n        }\n\n\n        public int GetFrameSpeed(int curFrameId)\n        {\n            int speed = 0;\n            var newFrameNum = m_NewestFrameId - curFrameId;\n\n            //是否正在缓冲中\n            if (!m_IsInBuffing)\n            {\n                //没有在缓冲中\n\n                if (newFrameNum == 0)\n                {\n                    //需要缓冲一下\n                    m_IsInBuffing = true;\n                    m_AutoBuffCnt = m_AutoBuffInterval;\n                }\n                else\n                {\n                    //因为即将播去这么多帧\n                    newFrameNum -= m_DefaultSpeed;\n\n                    int speedUpFrameNum = newFrameNum - m_JitterBuffSize;\n                    if (speedUpFrameNum >= m_ClientFrameRateMultiple)\n                    {\n                        //可以加速\n                        if (m_EnableSpeedUp)\n                        {\n                            speed = 2;\n                            if (speedUpFrameNum > 100)\n                            {\n                                speed = 8;\n                            }\n                            else if (speedUpFrameNum > 50)\n                            {\n                                speed = 4;\n                            }\n                        }\n                        else\n                        {\n                            speed = m_DefaultSpeed;\n                        }\n                    }\n                    else\n                    {\n                        //还达不到可加速的帧数\n                        speed = m_DefaultSpeed;\n\n                        if (m_EnableAutoBuff)\n                        {\n                            m_AutoBuffCnt--;\n                            if (m_AutoBuffCnt <= 0)\n                            {\n                                m_AutoBuffCnt = m_AutoBuffInterval;\n                                if (speedUpFrameNum < m_ClientFrameRateMultiple - 1)\n                                {\n                                    //这个时候大概率接下来会缺帧\n                                    speed = 0;\n                                }\n                            }\n                        }\n                        \n                    }\n\n                }\n            }\n            else\n            {\n                //正在缓冲中\n                int speedUpFrameNum = newFrameNum - m_JitterBuffSize;\n                if (speedUpFrameNum > 0)\n                {\n                    m_IsInBuffing = false;\n                }\n            }\n\n            m_IsInSpeedUp = speed > m_DefaultSpeed;\n            return speed;\n        }\n\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/FSPLite/Client/FSPManager.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\n\nusing SGF.Extension;\nusing SGF.Utils;\n\nnamespace SGF.Network.FSPLite.Client\n{\n    public class FSPManager:ILogTag\n    {\n\n        public string LOG_TAG { get; private set; }\n\n        //来自帧同步服务器的事件\n        public event Action<int> onGameBegin;\n        public event Action<int> onRoundBegin;\n        public event Action<int> onControlStart;\n        public event Action<int> onRoundEnd;\n        public event Action<int> onGameEnd;\n        public event Action<uint> onGameExit;\n\n\n        //基础参数\n        private bool m_IsRunning = false;\n        private FSPClient m_Client;\n        private FSPParam m_Param;\n        private uint m_MinePlayerId;\n        private Action<int, FSPFrame> m_FrameListener;\n        private int m_CurrentFrameIndex;\n        private int m_LockedFrameIndex;\n\n        public uint MainPlayerId { get { return m_MinePlayerId; } }\n\n\n        //游戏状态\n        private FSPGameState m_GameState = FSPGameState.None;\n        public FSPGameState GameState { get { return m_GameState; } }\n\n\n        //帧列表\n        private DictionarySafe<int, FSPFrame> m_FrameBuffer;//缓存的帧\n\n        private FSPFrameController m_FrameCtrl;\n        public FSPFrameController FrameController { get { return m_FrameCtrl; } }\n\n        //本地模拟\n        private FSPFrame m_NextLocalFrame;\n\n\n\n        public void Start(FSPParam param, uint playerId)\n        {\n            m_Param = param;\n            m_MinePlayerId = playerId;\n            LOG_TAG = \"FSPManager[\" + playerId + \"]\";\n\n            Debuger.Log();\n\n            if (m_Param.useLocal)\n            {\n                m_LockedFrameIndex = param.maxFrameId;\n            }\n            else\n            {\n                m_Client = new FSPClient();\n                m_Client.Init(m_Param.sid);\n                m_Client.SetFSPAuthInfo(param.authId);\n                m_Client.SetFSPListener(OnFSPListener);\n\n                m_Client.Connect(param.host, param.port);\n                m_Client.VerifyAuth();\n\n                m_LockedFrameIndex = m_Param.clientFrameRateMultiple - 1;\n            }\n\n            m_IsRunning = true;\n            m_GameState = FSPGameState.Create;\n\n            m_FrameBuffer = new DictionarySafe<int, FSPFrame>();\n            m_CurrentFrameIndex = 0;\n\n            m_FrameCtrl = new FSPFrameController();\n            m_FrameCtrl.Start(param);\n        }\n\n\n        public void Stop()\n        {\n            Debuger.Log();\n\n            m_GameState = FSPGameState.None;\n\n            if (m_Client != null)\n            {\n                m_Client.Clean();\n                m_Client = null;\n            }\n\n            m_FrameListener = null;\n            m_FrameCtrl.Stop();\n            m_FrameBuffer.Clear();\n            m_IsRunning = false;\n\n            onGameBegin = null;\n            onRoundBegin = null;\n            onControlStart = null;\n            onGameEnd = null;\n            onRoundEnd = null;\n        }\n\n        \n\n        /// <summary>\n        /// 设置帧数据的监听\n        /// </summary>\n        /// <param name=\"listener\"></param>\n        public void SetFrameListener(Action<int, FSPFrame> listener)\n        {\n            Debuger.Log();\n            m_FrameListener = listener;\n        }\n\n\n\n        /// <summary>\n        /// 监听来自FSPClient的帧数据\n        /// </summary>\n        /// <param name=\"frame\"></param>\n        private void OnFSPListener(FSPFrame frame)\n        {\n            AddServerFrame(frame);\n        }\n\n        \n\n        private void AddServerFrame(FSPFrame frame)\n        {\n            \n            if (frame.frameId <= 0)\n            {\n                ExecuteFrame(frame.frameId, frame);\n                return;\n            }\n\n\n            frame.frameId = frame.frameId * m_Param.clientFrameRateMultiple;\n            m_LockedFrameIndex = frame.frameId + m_Param.clientFrameRateMultiple - 1;\n            \n            m_FrameBuffer.Add(frame.frameId, frame);\n            m_FrameCtrl.AddFrameId(frame.frameId);\n            \n        }\n\n\n\n        #region 对基础流程Cmd的处理\n\n        public void SendGameBegin()\n        {\n            Debuger.Log();\n            SendFSP(FSPBasicCmd.GAME_BEGIN, 0);\n        }\n\n        private void Handle_GameBegin(int arg)\n        {\n            Debuger.Log(arg);\n            m_GameState = FSPGameState.GameBegin;\n            if (onGameBegin != null)\n            {\n                onGameBegin(arg);\n            }\n        }\n\n        public void SendRoundBegin()\n        {\n            Debuger.Log();\n            SendFSP(FSPBasicCmd.ROUND_BEGIN, 0);\n        }\n\n        private void Handle_RoundBegin(int arg)\n        {\n            Debuger.Log(arg);\n            m_GameState = FSPGameState.RoundBegin;\n            m_CurrentFrameIndex = 0;\n\n            if (!m_Param.useLocal)\n            {\n                m_LockedFrameIndex = m_Param.clientFrameRateMultiple - 1;\n            }\n            else\n            {\n                m_LockedFrameIndex = m_Param.maxFrameId;\n            }\n\n            m_FrameBuffer.Clear();\n\n            if (onRoundBegin != null)\n            {\n                onRoundBegin(arg);\n            }\n        }\n\n        public void SendControlStart()\n        {\n            Debuger.Log();\n            SendFSP(FSPBasicCmd.CONTROL_START, 0);\n        }\n        private void Handle_ControlStart(int arg)\n        {\n            Debuger.Log(arg);\n            m_GameState = FSPGameState.ControlStart;\n            if (onControlStart != null)\n            {\n                onControlStart(arg);\n            }\n        }\n\n        public void SendRoundEnd()\n        {\n            Debuger.Log();\n            SendFSP(FSPBasicCmd.ROUND_END, 0);\n        }\n        private void Handle_RoundEnd(int arg)\n        {\n            Debuger.Log(arg);\n            m_GameState = FSPGameState.RoundEnd;\n            if (onRoundEnd != null)\n            {\n                onRoundEnd(arg);\n            }\n        }\n\n        public void SendGameEnd()\n        {\n            Debuger.Log();\n            SendFSP(FSPBasicCmd.GAME_END, 0);\n        }\n        private void Handle_GameEnd(int arg)\n        {\n            Debuger.Log(arg);\n            m_GameState = FSPGameState.GameEnd;\n            if (onGameEnd != null)\n            {\n                onGameEnd(arg);\n            }\n        }\n\n\n        public void SendGameExit()\n        {\n            Debuger.Log();\n            SendFSP(FSPBasicCmd.GAME_EXIT, 0);\n        }\n\n        private void Handle_GameExit(uint playerId)\n        {\n            Debuger.Log(playerId);\n            if (onGameExit != null)\n            {\n                onGameExit(playerId);\n            }\n        }\n\n\n        #endregion\n\n\n\n\n        /// <summary>\n        /// 给外界用来发送FSPCmd的\n        /// </summary>\n        /// <param name=\"cmd\"></param>\n        /// <param name=\"arg\"></param>\n\n        public void SendFSP(int cmd, params int[] args)\n        {\n            if (!m_IsRunning)\n            {\n                return;\n            }\n\n            if (m_Param.useLocal)\n            {\n                SendFSPLocal(cmd, args);\n            }\n            else\n            {\n                m_Client.SendFSP(m_CurrentFrameIndex, cmd, args);\n            }\n        }\n\n\n\n        /// <summary>\n        /// 用于本地兼容，比如打PVE的时候，也可以用帧同步兼容\n        /// </summary>\n        /// <param name=\"cmd\"></param>\n        /// <param name=\"arg\"></param>\n        private void SendFSPLocal(int cmd, int[] args)\n        {\n            Debuger.Log(\"vkey={0}, arg={1}\", cmd, args.ToListString());\n\n            if (m_NextLocalFrame == null || m_NextLocalFrame.frameId != m_CurrentFrameIndex + 1)\n            {\n                m_NextLocalFrame = new FSPFrame();\n                m_NextLocalFrame.frameId = m_CurrentFrameIndex + 1;\n                \n                m_FrameBuffer.Add(m_NextLocalFrame.frameId, m_NextLocalFrame);\n            }\n\n            FSPMessage msg = new FSPMessage();\n            msg.cmd = cmd;\n            msg.args = args;\n            msg.playerId = m_MinePlayerId;\n            m_NextLocalFrame.msgs.Add(msg);\n            \n        }\n\n\n\n        /// <summary>\n        /// 由外界驱动\n        /// </summary>\n        public void Tick()\n        {\n            if (!m_IsRunning)\n            {\n                return;\n            }\n\n\n            if (m_Param.useLocal)\n            {\n                if (m_LockedFrameIndex == 0 || m_LockedFrameIndex > m_CurrentFrameIndex)\n                {\n                    m_CurrentFrameIndex++;\n                    var frame = m_FrameBuffer[m_CurrentFrameIndex];\n                    ExecuteFrame(m_CurrentFrameIndex, frame);\n                }\n            }\n            else\n            {\n                m_Client.Tick();\n\n                int speed = m_FrameCtrl.GetFrameSpeed(m_CurrentFrameIndex);\n                while (speed > 0)\n                {\n                    if (m_CurrentFrameIndex < m_LockedFrameIndex)\n                    {\n                        m_CurrentFrameIndex++;\n                        var frame = m_FrameBuffer[m_CurrentFrameIndex];\n                        ExecuteFrame(m_CurrentFrameIndex, frame);\n                    }\n                    speed--;\n                }\n                \n            }\n        }\n\n\n        /// <summary>\n        /// 执行每一帧\n        /// </summary>\n        /// <param name=\"frameId\"></param>\n        /// <param name=\"frame\"></param>\n        private void ExecuteFrame(int frameId, FSPFrame frame)\n        {\n\n            if (frame !=null && !frame.IsEmpty())\n            {\n                for (int i = 0; i < frame.msgs.Count; i++)\n                {\n                    var msg = frame.msgs[i];\n                    switch (msg.cmd)\n                    {\n                        case FSPBasicCmd.GAME_BEGIN: Handle_GameBegin(msg.args[0]);break;\n                        case FSPBasicCmd.ROUND_BEGIN: Handle_RoundBegin(msg.args[0]); break;\n                        case FSPBasicCmd.CONTROL_START: Handle_ControlStart(msg.args[0]); break;\n                        case FSPBasicCmd.ROUND_END: Handle_RoundEnd(msg.args[0]); break;\n                        case FSPBasicCmd.GAME_END: Handle_GameEnd(msg.args[0]); break;\n                        case FSPBasicCmd.GAME_EXIT: Handle_GameExit(msg.playerId); break;\n                    }\n\n                }\n\n \n            }\n\n\n            if (m_FrameListener != null)\n            {\n                m_FrameListener(frameId, frame);\n            }\n\n        }\n\n\n        //======================================================================\n\n        public string ToDebugString()\n        {\n            string str = \"\";\n            if (m_FrameCtrl != null)\n            {\n                str += (\"NewestFrameId:\" + m_FrameCtrl.NewestFrameId) + \"; \";\n                str += (\"PlayedFrameId:\" + m_CurrentFrameIndex) + \"; \";\n                str += (\"IsInBuffing:\" + m_FrameCtrl.IsInBuffing) + \"; \";\n                str += (\"IsInSpeedUp:\" + m_FrameCtrl.IsInSpeedUp) + \"; \";\n                str += (\"FrameBufferSize:\" + m_FrameCtrl.JitterBufferSize) + \"; \";\n            }\n\n            if (m_Client != null)\n            {\n                str += m_Client.ToDebugString();\n            }\n\n            return str;\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Network/FSPLite/FSPBasicCmd.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nnamespace SGF.Network.FSPLite\n{\n    public class FSPBasicCmd\n    {\n        /// <summary>\n        /// PVP战斗结束\n        /// </summary>\n        public const int GAME_BEGIN = 1000;\n\n        /// <summary>\n        /// 对局开始\n        /// </summary>\n        public const int ROUND_BEGIN = 1001;\n\n        /// <summary>\n        /// 开始加载\n        /// </summary>\n        public const int LOAD_START = 1002;\n        /// <summary>\n        /// 加载进度条\n        /// </summary>\n        public const int LOAD_PROGRESS = 1003;\n\n        /// <summary>\n        /// 可以开始控制...\n        /// </summary>\n        public const int CONTROL_START = 1004;\n\n        /// <summary>\n        /// 发送中途退出\n        /// </summary>\n        public const int GAME_EXIT = 1005;\n\n        /// <summary>\n        /// 对局结束\n        /// </summary>\n        public const int ROUND_END = 1006;\n\n        /// <summary>\n        /// PVP战斗结束\n        /// </summary>\n        public const int GAME_END = 1007;\n\n        /// <summary>\n        /// 鉴权身份字段\n        /// </summary>\n        public const int AUTH = 1008;\n\n        /// <summary>\n        /// PING 响应回包...\n        /// </summary>\n        public const int PING = 1009;\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/FSPLite/FSPGameEndReason.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nnamespace SGF.Network.FSPLite\n{\n    //由于以上有多种可能发GameEnd的情况，所以这里有一个GameEnd的原因定义\n    public enum FSPGameEndReason\n    {\n        Normal = 0, //正常结束\n        AllOtherExit = 1, //所有其他人都主动退出了\n        AllOtherLost = 2,  //所有其他人都掉线了\n    }\n}\n"
  },
  {
    "path": "SGFCore/Network/FSPLite/FSPGameState.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nnamespace SGF.Network.FSPLite\n{\n    public enum FSPGameState\n    {\n        /// <summary>\n        /// 0 初始状态\n        /// </summary>\n        None = 0,\n\n        /// <summary>\n        /// 游戏创建状态\n        /// 只有在该状态下，才允许加入玩家\n        /// 当所有玩家都发VKey.GameBegin后，进入下一个状态\n        /// </summary>\n        Create,\n\n        /// <summary>\n        /// 游戏开始状态\n        /// 在该状态下，等待所有玩家发VKey.RoundBegin，或者 判断玩家是否掉线\n        /// 当所有人都发送VKey.RoundBegin，进入下一个状态\n        /// 当有玩家掉线，则从FSPGame中删除该玩家：\n        ///     判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n        /// </summary>\n        GameBegin,\n\n        /// <summary>\n        /// 回合开始状态\n        /// （这个时候客户端可能在加载资源）\n        /// 在该状态下，等待所有玩家发VKey.ControlStart， 或者 判断玩家是否掉线\n        /// 当所有人都发送VKey.ControlStart，进入下一个状态\n        /// 当有玩家掉线，则从FSPGame中删除该玩家：\n        ///     判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n        /// </summary>\n        RoundBegin,\n\n        /// <summary>\n        /// 可以开始操作状态\n        /// （因为每个回合可能都会有加载过程，不同的玩家加载速度可能不同，需要用一个状态统一一下）\n        /// 在该状态下，接收玩家的业务VKey， 或者 VKey.RoundEnd，或者VKey.GameExit\n        /// 当所有人都发送VKey.RoundEnd，进入下一个状态\n        /// 当有玩家掉线，或者发送VKey.GameExit，则从FSPGame中删除该玩家：\n        ///     判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n        /// </summary>\n        ControlStart,\n\n        /// <summary>\n        /// 回合结束状态\n        /// （大部分游戏只有1个回合，也有些游戏有多个回合，由客户端逻辑决定）\n        /// 在该状态下，等待玩家发送VKey.GameEnd，或者 VKey.RoundBegin（如果游戏不只1个回合的话）\n        /// 当所有人都发送VKey.GameEnd，或者 VKey.RoundBegin时，进入下一个状态\n        /// 当有玩家掉线，则从FSPGame中删除该玩家：\n        ///     判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n        /// </summary>\n        RoundEnd,\n\n        /// <summary>\n        /// 游戏结束状态\n        /// 在该状态下，不再接收任何Vkey，然后给所有玩家发VKey.GameEnd，并且等待FSPServer关闭\n        /// </summary>\n        GameEnd\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/FSPLite/FSPLiteData.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System.Collections.Generic;\nusing System.Text;\nusing ProtoBuf;\nusing SGF.Codec;\nusing SGF.Extension;\n\nnamespace SGF.Network.FSPLite\n{\n    //==========================================================\n    #region FSP启动参数定义\n\n    [ProtoContract]\n    public class FSPParam\n    {\n        [ProtoMember(1)]\n        public string host;\n        [ProtoMember(2)]\n        public int port;\n        [ProtoMember(3)]\n        public uint sid;\n        [ProtoMember(4)]\n        public int serverFrameInterval = 66;\n        [ProtoMember(5)]\n        public int serverTimeout = 15000;//ms\n        [ProtoMember(6)]\n        public int clientFrameRateMultiple = 2;\n        [ProtoMember(7)]\n        public int authId = 0;\n        [ProtoMember(8)]\n        public bool useLocal = false;\n        [ProtoMember(9)]\n        public int maxFrameId = 1800;\n\n        [ProtoMember(10)]\n        public bool enableSpeedUp = true;\n        [ProtoMember(11)]\n        public int defaultSpeed = 1;\n        [ProtoMember(12)]\n        public int jitterBufferSize = 0;//缓冲大小\n        [ProtoMember(13)]\n        public bool enableAutoBuffer = true;\n\n\n\n\n\n\n        public FSPParam Clone()\n        {\n            byte[] buffer = PBSerializer.NSerialize(this);\n            return (FSPParam)PBSerializer.NDeserialize(buffer, typeof(FSPParam));\n        }\n\n        public string ToString(string prefix = \"\")\n        {\n            StringBuilder sb = new StringBuilder();\n            sb.AppendFormat(\"\\n{0}host:{1}:{2}\", prefix, host, port);\n            sb.AppendFormat(\"\\n{0}serverFrameInterval:{1}\", prefix, serverFrameInterval);\n            sb.AppendFormat(\"\\n{0}clientFrameRateMultiple:{1}\", prefix, clientFrameRateMultiple);\n            sb.AppendFormat(\"\\n{0}serverTimeout:{1}\", prefix, serverTimeout);\n            sb.AppendFormat(\"\\n{0}maxFrameId:{1}\", prefix, maxFrameId);\n\n            return sb.ToString();\n        }\n    }\n\t#endregion\n\n    [ProtoContract]\n    public class FSPMessage\n    {\n        [ProtoMember(1)] public int cmd;\n        [ProtoMember(2)] public int[] args;\n        [ProtoMember(3)] public int custom;\n\n        public uint playerId\n        {\n            get { return (uint)custom; }\n            set { custom = (int)value; }\n        }\n\n        public int clientFrameId\n        {\n            get { return custom; }\n            set { custom = value; }\n        }\n\n        public override string ToString()\n        {\n            if (args != null)\n            {\n                return string.Format(\"cmd:{0}, args:{1}, custom:{2}\", cmd, args.ToListString(), custom);\n            }\n            else\n            {\n                return string.Format(\"cmd:{0}, args:{1}, custom:{2}\", cmd, \"[]\", custom);\n            }\n        }\n        \n    }\n\n\n    [ProtoContract]\n    public class FSPDataC2S\n    {\n        [ProtoMember(1)] public uint sid = 0;\n        [ProtoMember(2)] public List<FSPMessage> msgs = new List<FSPMessage>();\n    }\n\n    [ProtoContract]\n    public class FSPDataS2C\n    {\n        [ProtoMember(1)] public List<FSPFrame> frames = new List<FSPFrame>();\n    }\n\n    [ProtoContract]\n    public class FSPFrame\n    {\n        [ProtoMember(1)] public int frameId;\n        [ProtoMember(2)] public List<FSPMessage> msgs = new List<FSPMessage>();\n\n\n        public bool IsEmpty()\n        {\n            return (msgs == null || msgs.Count == 0);\n        }\n\n\n        public bool Contains(int cmd)\n        {\n            if (!IsEmpty())\n            {\n                for (int i = 0; i < msgs.Count; i++)\n                {\n                    if (msgs[i].cmd == cmd)\n                    {\n                        return true;\n                    }\n                }\n            }\n\n            return false;\n        }\n\n        public override string ToString()\n        {\n            string tmp = \"\";\n            for (int i = 0; i < msgs.Count - 1; i++)\n            {\n                tmp += msgs[i] + \",\";\n            }\n\n            if (msgs.Count > 0)\n            {\n                tmp += msgs[msgs.Count - 1].ToString();\n            }\n\n            return string.Format(\"frameId:{0}, msgs:[{1}]\", frameId, tmp);\n        }\n\n    }\n\n\n\n\n\n\n\n}"
  },
  {
    "path": "SGFCore/Network/FSPLite/Server/FSPGame.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing SGF.Extension;\n\nnamespace SGF.Network.FSPLite.Server\n{\n    public class FSPGame\n    {\n        public static int ActiveTimeout = 10;\n\n        //有一个玩家退出游戏\n        public Action<uint> onGameExit;\n\n        //游戏真正结束\n        public Action<int> onGameEnd;\n\n\n\n        /// <summary>\n        /// 最大支持的玩家数：31\n        /// 因为用来保存玩家Flag的Int只有31位有效位可用，不过31已经足够了\n        /// </summary>\n        private const int MaxPlayerNum = 31;\n\n        //基础参数\n        private int m_authId;\n\n        private uint m_gameId;\n        public uint id { get { return m_gameId; } }\n\n        //游戏状态\n        private FSPGameState m_State;\n        private int m_StateParam1;\n        private int m_StateParam2;\n        public FSPGameState State { get { return m_State; } }\n        \n\n        //Player的Cmd标识\n        private int m_GameBeginFlag = 0;\n        private int m_RoundBeginFlag = 0;\n        private int m_ControlStartFlag = 0;\n        private int m_RoundEndFlag = 0;\n        private int m_GameEndFlag = 0;\n\n        //Round标志\n        private int m_CurRoundId = 0;\n        public int CurrentRoundId { get { return m_CurRoundId; } }\n\n\n        //服务器的当前帧\n        private FSPFrame m_LockedFrame = new FSPFrame();\n\n        private int m_CurFrameId = 0;\n\n\n\n        //玩家列表\n        private List<FSPPlayer> m_ListPlayer = new List<FSPPlayer>();\n        private List<FSPPlayer> m_ListPlayersExitOnNextFrame = new List<FSPPlayer>();\n\n\n\n        //---------------------------------------------------------\n        public void Create(uint gameId, int authId)\n        {\n            Debuger.Log();\n            m_authId = authId;\n            m_gameId = gameId;\n            m_CurRoundId = 0;\n            SetGameState(FSPGameState.Create);\n        }\n\n        public void Release()\n        {\n            SetGameState(FSPGameState.None);\n\n            for (int i = 0; i < m_ListPlayer.Count; i++)\n            {\n                FSPPlayer player = m_ListPlayer[i];\n                player.Release();\n            }\n            m_ListPlayer.Clear();\n            m_ListPlayersExitOnNextFrame.Clear();\n\n            onGameExit = null;\n            onGameEnd = null;\n\n            Debuger.Log();\n        }\n\n        public string ToString(string prefix = \"\")\n        {\n            StringBuilder sb = new StringBuilder();\n            sb.AppendFormat(\"[{0}] AuthId:{1}, State:{2}, CurrentRound:{3}, CurrentFrameId:{4}\",m_gameId, m_authId, m_State,\n                m_CurRoundId, m_CurFrameId);\n\n            sb.AppendFormat(\"\\n{0}PlayerList:\", prefix);\n            for (int i = 0; i < m_ListPlayer.Count; i++)\n            {\n                sb.AppendFormat(\"\\n{0}Player{1}\", prefix, m_ListPlayer[i].ToString(prefix + \"\\t\"));\n            }\n\n            sb.AppendFormat(\"\\n{0}ListPlayersExitOnNextFrame:\", prefix);\n            for (int i = 0; i < m_ListPlayersExitOnNextFrame.Count; i++)\n            {\n                sb.AppendFormat(\"\\n{0}Player{1}\", prefix, m_ListPlayersExitOnNextFrame[i].ToString(prefix + \"\\t\"));\n            }\n\n            return sb.ToString();\n        }\n        \n\n        //===================================================================\n\n        public FSPPlayer AddPlayer(uint playerId, FSPSession session)\n        {\n            Debuger.Log(\"playerId:{0}\", playerId);\n\n            if (m_State != FSPGameState.Create)\n            {\n                Debuger.LogError(\"当前状态下无法AddPlayer! State = {0}\", m_State);\n                return null;\n            }\n\n            FSPPlayer player = null;\n            for (int i = 0; i < m_ListPlayer.Count; i++)\n            {\n                player = m_ListPlayer[i];\n                if (player.id == playerId)\n                {\n                    Debuger.LogWarning(\"PlayerId已经存在！用新的替代旧的! PlayerId = \" + playerId);\n                    m_ListPlayer.RemoveAt(i);\n                    player.Release();\n                    break;\n                }\n            }\n\n            if (m_ListPlayer.Count >= MaxPlayerNum)\n            {\n                Debuger.LogError(\"已经达到最大玩家数了! MaxPlayerNum = {0}\", MaxPlayerNum);\n                return null;\n            }\n\n\n            player = new FSPPlayer();\n            player.Create(playerId, m_authId, session, OnRecvFromPlayer);\n            m_ListPlayer.Add(player);\n\n            return player;\n        }\n\n        private FSPPlayer GetPlayer(uint playerId)\n        {\n            FSPPlayer player = null;\n            for (int i = 0; i < m_ListPlayer.Count; i++)\n            {\n                player = m_ListPlayer[i];\n                if (player.id == playerId)\n                {\n                    return player;\n                }\n            }\n            return null;\n        }\n\n\n        internal int GetPlayerCount()\n        {\n            return m_ListPlayer.Count;\n        }\n\n        public List<FSPPlayer> GetPlayerList()\n        {\n            return m_ListPlayer;\n        }\n\n\n        //---------------------------------------------------------\n        //收到客户端Player的Cmd\n        private void OnRecvFromPlayer(FSPPlayer player, FSPMessage msg)\n        {\n            HandleClientCmd(player, msg);\n        }\n\n        protected virtual void HandleClientCmd(FSPPlayer player, FSPMessage msg)\n        {\n\n            uint playerId = player.id;\n\n            //处理鉴权\n            if (!player.HasAuthed)\n            {\n                if (msg.cmd == FSPBasicCmd.AUTH)\n                {\n                    player.SetAuth(msg.args[0]);\n                }\n                else\n                {\n                    Debuger.LogWarning(\"当前Player未鉴权，无法处理该Cmd：{0}\", msg.cmd);\n                }\n                return;\n            }\n\n            switch (msg.cmd)\n            {\n                case FSPBasicCmd.GAME_BEGIN:\n                {\n                    Debuger.Log(\"GAME_BEGIN, playerId = {0}, cmd = {1}\", playerId, msg);\n                    SetFlag(playerId, ref m_GameBeginFlag, \"m_GameBeginFlag\");\n                    break;\n                }\n                case FSPBasicCmd.ROUND_BEGIN:\n                {\n                    Debuger.Log(\"ROUND_BEGIN, playerId = {0}, cmd = {1}\", playerId, msg);\n                    SetFlag(playerId, ref m_RoundBeginFlag, \"m_RoundBeginFlag\");\n                    break;\n                }\n                case FSPBasicCmd.CONTROL_START:\n                {\n                    Debuger.Log(\"CONTROL_START, playerId = {0}, cmd = {1}\", playerId, msg);\n                    SetFlag(playerId, ref m_ControlStartFlag, \"m_ControlStartFlag\");\n                    break;\n                }\n                case FSPBasicCmd.ROUND_END:\n                {\n                    Debuger.Log(\"ROUND_END, playerId = {0}, cmd = {1}\", playerId, msg);\n                    SetFlag(playerId, ref m_RoundEndFlag, \"m_RoundEndFlag\");\n                    break;\n                }\n                case FSPBasicCmd.GAME_END:\n                {\n                    Debuger.Log(\"GAME_END, playerId = {0}, cmd = {1}\", playerId, msg);\n                    SetFlag(playerId, ref m_GameEndFlag, \"m_GameEndFlag\");\n                    break;\n                }\n                case FSPBasicCmd.GAME_EXIT:\n                {\n                    Debuger.Log(\"GAME_EXIT, playerId = {0}, cmd = {1}\", playerId, msg);\n                    HandleGameExit(playerId, msg);\n                    break;\n                }\n                default:\n                {\n                    Debuger.Log(\"playerId = {0}, cmd = {1}\", playerId, msg);\n                    AddCmdToCurrentFrame(playerId, msg);\n                    break;\n                }\n            }\n\n\n        }\n\n\n        private void AddCmdToCurrentFrame(uint playerId, FSPMessage msg)\n        {\n            msg.playerId = playerId;\n            m_LockedFrame.msgs.Add(msg);\n        }\n\n\n        private void AddBasicCmdToCurrentFrame(int cmd, int arg = 0)\n        { \n            FSPMessage msg = new FSPMessage();\n            msg.cmd = cmd;\n            msg.args = new[] {arg};\n            AddCmdToCurrentFrame(0, msg);\n        }\n\n\n\n        private void HandleGameExit(uint playerId, FSPMessage msg)\n        {\n            AddCmdToCurrentFrame(playerId, msg);\n\n            FSPPlayer player = GetPlayer(playerId);\n\n            if (player != null)\n            {\n                player.WaitForExit = true;\n\n                if (onGameExit != null)\n                {\n                    onGameExit(player.id);\n                }\n            }\n        }\n\n\n        //=======================================================================================\n\n        /// <summary>\n        /// 驱动游戏状态\n        /// </summary>\n        public void EnterFrame()\n        {\n            for (int i = 0; i < m_ListPlayersExitOnNextFrame.Count; i++)\n            {\n                var player = m_ListPlayersExitOnNextFrame[i];\n                player.Release();\n            }\n            m_ListPlayersExitOnNextFrame.Clear();\n\n\n            \n            //处理游戏状态切换\n            HandleGameState();\n\n\n            //经过上面状态处理之后，有可能状态还会发生变化\n            if (m_State == FSPGameState.None)\n            {\n                return;\n            }\n\n\n\n            if (m_LockedFrame.frameId != 0 || !m_LockedFrame.IsEmpty())\n            {\n                //将当前帧扔级Player\n                for (int i = 0; i < m_ListPlayer.Count; i++)\n                {\n                    FSPPlayer player = m_ListPlayer[i];\n                    player.SendToClient(m_LockedFrame);\n\n                    if (player.WaitForExit)\n                    {\n                        m_ListPlayersExitOnNextFrame.Add(player);\n                        m_ListPlayer.RemoveAt(i);\n                        --i;\n                    }\n\n                }\n            }\n\n\n            //0帧每个循环需要额外清除掉再重新统计\n            if (m_LockedFrame.frameId == 0)\n            {\n                m_LockedFrame = new FSPFrame();\n            }\n\n\n            //在这个阶段，帧号才会不停往上加\n            if (m_State == FSPGameState.RoundBegin || m_State == FSPGameState.ControlStart)\n            {\n                m_CurFrameId++;\n                m_LockedFrame = new FSPFrame();\n                m_LockedFrame.frameId = m_CurFrameId;\n            }\n            \n        }\n\n\n\n\n\n\n        //设置状态机\n        protected void SetGameState(FSPGameState state, int param1 = 0, int param2 = 0)\n        {\n            Debuger.Log(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n            Debuger.Log(\"{0} -> {1}, param1 = {2}, param2 = {3}\", m_State, state, param1, param2);\n            Debuger.Log(\"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\");\n\n            m_State = state;\n            m_StateParam1 = param1;\n            m_StateParam2 = param2;\n        }\n\n        private void HandleGameState()\n        {\n            switch (m_State)\n            {\n                case FSPGameState.None:\n                {\n                    //进入这个状态的游戏，马上将会被回收\n                    //这里是否要考虑session中的所有消息都发完了？\n                    break;\n                }\n                case FSPGameState.Create: //游戏刚创建，未有任何玩家加入, 这个阶段等待玩家加入\n                {\n                    OnState_Create();\n                    break;\n                }\n                case FSPGameState.GameBegin: //游戏开始，等待RoundBegin\n                {\n                    OnState_GameBegin();\n                    break;\n                }\n                case FSPGameState.RoundBegin: //回合已经开始，开始加载资源等，等待ControlStart\n                {\n                    OnState_RoundBegin();\n                    break;\n                }\n                case FSPGameState.ControlStart: //在这个阶段可操作，这时候接受游戏中的各种行为包，并等待RoundEnd\n                {\n                    OnState_ControlStart();\n                    break;\n                }\n                case FSPGameState.RoundEnd: //回合已经结束，判断是否进行下一轮，即等待RoundBegin，或者GameEnd\n                {\n                    OnState_RoundEnd();\n                    break;\n                }\n                case FSPGameState.GameEnd://游戏结束\n                {\n                    OnState_GameEnd();\n                    break;\n                }\n                default:\n                    break;\n            }\n        }\n\n\n        protected virtual int OnState_Create()\n        {\n            //如果有任何一方已经鉴权完毕，则游戏进入GameBegin状态准备加载\n            if (IsFlagFull(m_GameBeginFlag))\n            {\n                SetGameState(FSPGameState.GameBegin);\n                AddBasicCmdToCurrentFrame(FSPBasicCmd.GAME_BEGIN);\n                return 0;\n            }\n            return 0;\n        }\n\n\n        /// <summary>\n        /// 游戏开始状态\n        /// 在该状态下，等待所有玩家发VKey.RoundBegin，或者 判断玩家是否掉线\n        /// 当所有人都发送VKey.RoundBegin，进入下一个状态\n        /// 当有玩家掉线，则从FSPGame中删除该玩家：\n        ///     判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n        /// </summary>\n        protected virtual int OnState_GameBegin()\n        {\n            if (CheckGameAbnormalEnd())\n            {\n                return 0;\n            }\n\n            if (IsFlagFull(m_RoundBeginFlag))\n            {\n                SetGameState(FSPGameState.RoundBegin);\n                IncRoundId();\n                ClearRound();\n                AddBasicCmdToCurrentFrame(FSPBasicCmd.ROUND_BEGIN, m_CurRoundId);\n\n                return 0;\n            }\n\n            return 0;\n        }\n\n\n        /// <summary>\n        /// 回合开始状态\n        /// （这个时候客户端可能在加载资源）\n        /// 在该状态下，等待所有玩家发VKey.ControlStart， 或者 判断玩家是否掉线\n        /// 当所有人都发送VKey.ControlStart，进入下一个状态\n        /// 当有玩家掉线，则从FSPGame中删除该玩家：\n        ///     判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n        /// </summary>\n        protected virtual int OnState_RoundBegin()\n        {\n            if (CheckGameAbnormalEnd())\n            {\n                return 0;\n            }\n\n            if (IsFlagFull(m_ControlStartFlag))\n            {\n                ResetRoundFlag();\n                SetGameState(FSPGameState.ControlStart);\n                AddBasicCmdToCurrentFrame(FSPBasicCmd.CONTROL_START);\n                return 0;\n            }\n\n            return 0;\n        }\n\n\n        /// <summary>\n        /// 可以开始操作状态\n        /// （因为每个回合可能都会有加载过程，不同的玩家加载速度可能不同，需要用一个状态统一一下）\n        /// 在该状态下，接收玩家的业务VKey， 或者 VKey.RoundEnd，或者VKey.GameExit\n        /// 当所有人都发送VKey.RoundEnd，进入下一个状态\n        /// 当有玩家掉线，或者发送VKey.GameExit，则从FSPGame中删除该玩家：\n        ///     判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n        /// </summary>\n        protected virtual int OnState_ControlStart()\n        {\n            if (CheckGameAbnormalEnd())\n            {\n                return 0;\n            }\n\n            if (IsFlagFull(m_RoundEndFlag))\n            {\n                SetGameState(FSPGameState.RoundEnd);\n                ClearRound();\n                AddBasicCmdToCurrentFrame(FSPBasicCmd.ROUND_END, m_CurRoundId);\n                return 0;\n            }\n\n            return 0;\n        }\n\n\n        /// <summary>\n        /// 回合结束状态\n        /// （大部分游戏只有1个回合，也有些游戏有多个回合，由客户端逻辑决定）\n        /// 在该状态下，等待玩家发送VKey.GameEnd，或者 VKey.RoundBegin（如果游戏不只1个回合的话）\n        /// 当所有人都发送VKey.GameEnd，或者 VKey.RoundBegin时，进入下一个状态\n        /// 当有玩家掉线，则从FSPGame中删除该玩家：\n        ///     判断如果只剩下1个玩家了，则直接进入GameEnd状态，否则不影响游戏状态\n        /// </summary>\n        protected virtual int OnState_RoundEnd()\n        {\n            if (CheckGameAbnormalEnd())\n            {\n                return 0;\n            }\n\n\n            //这是正常GameEnd\n            if (IsFlagFull(m_GameEndFlag))\n            {\n                SetGameState(FSPGameState.GameEnd, (int)FSPGameEndReason.Normal);\n                AddBasicCmdToCurrentFrame(FSPBasicCmd.GAME_END, (int)FSPGameEndReason.Normal);\n                return 0;\n            }\n\n\n            if (IsFlagFull(m_RoundBeginFlag))\n            {\n                SetGameState(FSPGameState.RoundBegin);\n                ClearRound();\n                IncRoundId();\n                AddBasicCmdToCurrentFrame(FSPBasicCmd.ROUND_BEGIN, m_CurRoundId);\n                return 0;\n            }\n\n\n            return 0;\n        }\n\n\n        protected virtual int OnState_GameEnd()\n        {\n            //到这里就等业务层去读取数据了 \n            if (onGameEnd != null)\n            {\n                onGameEnd(m_StateParam1);\n                onGameEnd = null;\n            }\n            return 0;\n        }\n\n\n        public bool IsGameEnd()\n        {\n            return m_State == FSPGameState.GameEnd;\n        }\n\n\n        //============================================================\n\n        /// <summary>\n        /// 检测游戏是否异常结束\n        /// </summary>\n        private bool CheckGameAbnormalEnd()\n        {\n            //判断还剩下多少玩家，如果玩家少于2，则表示至少有玩家主动退出\n            if (m_ListPlayer.Count < 1)\n            {\n                //直接进入GameEnd状态\n                SetGameState(FSPGameState.GameEnd, (int)FSPGameEndReason.AllOtherExit);\n                AddBasicCmdToCurrentFrame(FSPBasicCmd.GAME_END, (int)FSPGameEndReason.AllOtherExit);\n                return true;\n            }\n\n            // 检测玩家在线状态\n            for (int i = 0; i < m_ListPlayer.Count; i++)\n            {\n                FSPPlayer player = m_ListPlayer[i];\n                if (player.IsLose())\n                {\n                    m_ListPlayer.RemoveAt(i);\n                    player.Release();\n                    --i;\n                }\n            }\n\n            //判断还剩下多少玩家，如果玩家少于1，则表示至少有玩家主动退出\n            if (m_ListPlayer.Count < 1)\n            {\n                //直接进入GameEnd状态\n                SetGameState(FSPGameState.GameEnd, (int)FSPGameEndReason.AllOtherLost);\n                AddBasicCmdToCurrentFrame(FSPBasicCmd.GAME_END, (int)FSPGameEndReason.AllOtherLost);\n                return true;\n            }\n\n\n            return false;\n        }\n\n\n\n        private void IncRoundId()\n        {\n            ++m_CurRoundId;\n        }\n\n        private int ClearRound()\n        {\n            m_LockedFrame = new FSPFrame();\n            m_CurFrameId = 0;\n\n            ResetRoundFlag();\n\n            for (int i = 0; i < m_ListPlayer.Count; i++)\n            {\n                if (m_ListPlayer[i] != null)\n                {\n                    m_ListPlayer[i].ClearRound();\n                }\n            }\n\n            return 0;\n        }\n\n\n        private void ResetRoundFlag()\n        {\n            m_RoundBeginFlag = 0;\n            m_ControlStartFlag = 0;\n            m_RoundEndFlag = 0;\n            m_GameEndFlag = 0;\n        }\n\n\n\n        //============================================================\n\n        //--------------------------------------------------------------------\n        #region Player 状态标志工具函数\n\n        private void SetFlag(uint playerId, ref int flag, string flagname)\n        {\n            flag |= (0x01 << ((int)playerId - 1));\n            Debuger.Log(\"player = {0}, flag = {1}\", playerId, flagname);\n        }\n\n        private void ClsFlag(int playerId, ref int flag, string flagname)\n        {\n            flag &= (~(0x01 << (playerId - 1)));\n        }\n\n        public bool IsAnyFlagSet(int flag)\n        {\n            return flag != 0;\n        }\n\n        public bool IsFlagFull(int flag)\n        {\n            if (m_ListPlayer.Count > 0)\n            {\n                for (int i = 0; i < m_ListPlayer.Count; i++)\n                {\n                    FSPPlayer player = m_ListPlayer[i];\n                    int playerId = (int)player.id;\n                    if ((flag & (0x01 << (playerId - 1))) == 0)\n                    {\n                        return false;\n                    }\n                }\n                return true;\n            }\n\n            return false;\n\n        }\n\n\n        #endregion\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/FSPLite/Server/FSPGateway.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nusing SGF.Network.Core;\nusing SGF.Utils;\n\nnamespace SGF.Network.FSPLite.Server\n{\n    \n    public class FSPGateway\n    {\n        private static uint ms_lastSid = 0;\n        public static uint NewSessionID()\n        {\n            return ++ms_lastSid;\n        }\n\n\n        //=====================================================================\n\n        //基础数据\n        private bool m_IsRunning = false;\n        public bool IsRunning { get { return m_IsRunning; } }\n\n\n        //线程模块\n        private Thread m_ThreadRecv;\n\n\n        //通讯部分\n        private Socket m_SystemSocket;\n        private byte[] m_RecvBufferTemp = new byte[4096];\n        private NetBufferReader m_RecvBufferTempReader = new NetBufferReader();\n        private int m_port;\n        \n\n        //Session管理\n        private MapList<uint, FSPSession> m_mapSession;\n\n\n\n        public void Init(int port)\n        {\n            Debuger.Log(\"port:{0}\", port);\n            m_port = port;\n            m_mapSession = new MapList<uint, FSPSession>();\n            Start();\n        }\n\n        public void Clean()\n        {\n            Debuger.Log();\n            m_mapSession.Clear();\n            Close();\n        }\n\n        public int Port\n        {\n            get { return (m_SystemSocket.LocalEndPoint as IPEndPoint).Port; }\n        }\n\n        public string Host\n        {\n            get { return IPUtils.SelfIP; }\n        }\n\n        public void Dump()\n        {\n            StringBuilder sb = new StringBuilder();\n\n            var dic = m_mapSession.AsDictionary();\n            foreach (var pair in dic)\n            {\n                var session = pair.Value;\n                sb.AppendLine(\"\\t\" + session.ToString());\n            }\n\n            Debuger.LogWarning(\"\\nFSPGateway Sessions ({0}):\\n{1}\", m_mapSession.Count, sb);\n\n        }\n\n\n        public void Start()\n        {\n            Debuger.Log();\n\n            m_IsRunning = true;\n\n            m_SystemSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\n            m_SystemSocket.Bind(IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, m_port));\n\n            m_ThreadRecv = new Thread(Thread_Recv) { IsBackground = true };\n            m_ThreadRecv.Start();\n        }\n\n\n\n        public void Close()\n        {\n            Debuger.Log();\n\n            m_IsRunning = false;\n\n            if (m_ThreadRecv != null)\n            {\n                m_ThreadRecv.Interrupt();\n                m_ThreadRecv = null;\n            }\n\n            if (m_SystemSocket != null)\n            {\n                try\n                {\n                    m_SystemSocket.Shutdown(SocketShutdown.Both);\n\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(e.Message + e.StackTrace);\n                }\n\n                m_SystemSocket.Close();\n                m_SystemSocket = null;\n            }\n        }\n\n\n        public FSPSession CreateSession()\n        {\n            Debuger.Log();\n            uint sid = NewSessionID();\n            FSPSession session = new FSPSession(sid, HandleSessionSend);\n            m_mapSession.Add(sid, session);\n            return session;\n        }\n\n\n        public FSPSession GetSession(uint sid)\n        {\n            FSPSession session = null;\n            lock (m_mapSession)\n            {\n                session = m_mapSession[sid];\n            }\n            return session;\n        }\n\n\n        private void HandleSessionSend(IPEndPoint remoteEndPoint, byte[] buffer, int size)\n        {\n            if (m_SystemSocket != null)\n            {\n                int cnt = m_SystemSocket.SendTo(buffer, 0, size, SocketFlags.None, remoteEndPoint);\n            }\n            else\n            {\n                Debuger.LogError(\"Socket已经关闭！\");\n            }\n        }\n\n        //=================================================================================\n        //接收线程 \n        //=================================================================================\n\n        private void Thread_Recv()\n        {\n            while (m_IsRunning)\n            {\n                try\n                {\n                    DoReceiveInThread();\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(e.Message + \"\\n\" + e.StackTrace);\n                    Thread.Sleep(1);\n                }\n\n            }\n        }\n\n\n        private void DoReceiveInThread()\n        {\n            EndPoint remotePoint = IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, 0);\n            int cnt = m_SystemSocket.ReceiveFrom(m_RecvBufferTemp, m_RecvBufferTemp.Length, SocketFlags.None, ref remotePoint);\n\n            if (cnt > 0)\n            {\n                \n                m_RecvBufferTempReader.Attach(m_RecvBufferTemp, cnt);\n                byte[] m_32b = new byte[4];\n                m_RecvBufferTempReader.ReadBytes(m_32b, 0, 4);\n                uint sid = BitConverter.ToUInt32(m_32b, 0);\n\n                lock (m_mapSession)\n                {\n                    FSPSession session = null;\n                    if (sid == 0)\n                    {\n                        Debuger.LogError(\"基于KCP的Sid为0，该包需要被丢掉\");\n                    }\n                    else\n                    {\n                        session = m_mapSession[sid];\n                    }\n\n                    if (session != null)\n                    {\n                        session.Active(remotePoint as IPEndPoint);\n                        session.DoReceiveInGateway(m_RecvBufferTemp, cnt);\n                    }\n                    else\n                    {\n                        Debuger.LogWarning(\"无效的包! sid:{0}\", sid);\n                    }\n                }\n\n            }\n        }\n\n\n\n\n        //=================================================================================\n        //时钟信号 \n        //=================================================================================\n\n        private uint m_lastClearSessionTime = 0;\n        public void Tick()\n        {\n            if (m_IsRunning)\n            {\n                lock (m_mapSession)\n                {\n                    uint current = (uint)TimeUtils.GetTotalMillisecondsSince1970();\n\n                    if (current - m_lastClearSessionTime > FSPSession.ActiveTimeout * 1000 / 2)\n                    {\n                        m_lastClearSessionTime = current;\n                        ClearNoActiveSession();\n                    }\n\n\n                    var list = m_mapSession.AsList();\n                    int cnt = list.Count;\n                    for (int i = 0; i < cnt; i++)\n                    {\n                        var session = list[i];\n                        session.Tick(current);\n                    }\n                }\n            }\n        }\n\n        private void ClearNoActiveSession()\n        {\n            var list = m_mapSession.AsList();\n            var dir = m_mapSession.AsDictionary();\n            int cnt = list.Count;\n\n            for (int i = cnt - 1; i >= 0; i--)\n            {\n                var session = list[i];\n                if (!session.IsActived())\n                {\n                    list.RemoveAt(i);\n                    dir.Remove(session.id);\n                }\n            }\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/FSPLite/Server/FSPManager.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nusing SGF.Extension;\nusing SGF.Utils;\n\nnamespace SGF.Network.FSPLite.Server\n{\n    public class FSPManager\n    {\n\n        private long m_lastTicks = 0;\n\n        private bool m_UseCustomEnterFrame;\n        //===========================================================\n        private FSPParam m_param = new FSPParam();\n        private FSPGateway m_gateway;\n\n        private MapList<uint, FSPGame> m_mapGame;\n        private uint m_lastClearGameTime = 0;\n\n        public void Init(int port)\n        {\n            Debuger.Log(\"port:{0}\", port);\n            m_gateway = new FSPGateway();\n            m_gateway.Init(port);\n            m_param.port = m_gateway.Port;\n            m_param.host = m_gateway.Host;\n            m_mapGame = new MapList<uint, FSPGame>();\n        }\n\n        public void Clean()\n        {\n            Debuger.Log();\n            m_mapGame.Clear();\n        }\n\n\n        public void Dump()\n        {\n            m_gateway.Dump();\n\n            StringBuilder sb = new StringBuilder();\n\n            sb.AppendFormat(\"\\nFSPParam:{0}\", m_param.ToString(\"\\t\"));\n            sb.AppendLine(\"\\nGameList:\");\n\n            var listGame = m_mapGame.AsDictionary();\n            foreach (var game in listGame)\n            {\n                sb.AppendFormat(\"\\n\\tGame {0}\", game.Value.ToString(\"\\t\\t\"));\n            }\n            \n            Debuger.LogWarning(sb.ToString());\n        }\n\n\n        //=======================================================================\n        //设置FSP参数\n        public void SetFrameInterval(int serverFrameInterval, int clientFrameRateMultiple) //MS\n        {\n            Debuger.Log(\"serverFrameInterval:{0}, clientFrameRateMultiple:{1}\", serverFrameInterval, clientFrameRateMultiple);\n            m_param.serverFrameInterval = serverFrameInterval;\n            m_param.clientFrameRateMultiple = clientFrameRateMultiple;\n\n        }\n\n\n        public void SetServerTimeout(int serverTimeout)\n        {\n            m_param.serverTimeout = serverTimeout;\n        }\n\n        public int GetFrameInterval()\n        {\n            return m_param.serverFrameInterval;\n        }\n\n        public FSPParam GetParam()\n        {\n            m_param.port = m_gateway.Port;\n            m_param.host = m_gateway.Host;\n            return m_param.Clone();\n        }\n\n\n        //=======================================================================\n        //管理Game单局\n        public FSPGame CreateGame(uint gameId, int authId)\n        {\n            Debuger.Log(\"gameId:{0}, auth:{1}\", gameId, authId);\n\n            FSPGame game = new FSPGame();\n            game.Create(gameId, authId);\n            \n            m_mapGame.Add(gameId, game);\n            return game;\n        }\n\n        public void ReleaseGame(uint gameId)\n        {\n            Debuger.Log(\"gameId:{0}\", gameId);\n\n            FSPGame game = m_mapGame[gameId];\n            if (game != null)\n            {\n                game.Release();\n                m_mapGame.Remove(gameId);\n            }\n        }\n\n\n        /// <summary>\n        /// 创建一个玩家\n        /// </summary>\n        /// <param name=\"gameId\"></param>\n        /// <param name=\"playerId\"></param>\n        /// <returns>SessionId</returns>\n        public uint AddPlayer(uint gameId, uint playerId)\n        {\n            var game = m_mapGame[gameId];\n            var session = m_gateway.CreateSession();\n            game.AddPlayer(playerId, session);\n            return session.id;\n        }\n\n        /// <summary>\n        /// 创建一组玩家\n        /// </summary>\n        /// <param name=\"gameId\"></param>\n        /// <param name=\"listPlayerId\"></param>\n        /// <returns>SessionId列表</returns>\n        public List<uint> AddPlayer(uint gameId, List<uint> listPlayerId)\n        {\n            Debuger.Log(\"gameId:{0}, players:{1}\", gameId, listPlayerId.ToListString());\n\n            var game = m_mapGame[gameId];\n            List<uint> listSid = new List<uint>();\n            for (int i = 0; i < listPlayerId.Count; i++)\n            {\n                var session = m_gateway.CreateSession();\n                game.AddPlayer(listPlayerId[i], session);\n                listSid.Add(session.id);\n            }\n\n            return listSid;\n\n        }\n\n\n        //=======================================================================\n\n        //时钟信号\n        public void Tick()\n        {\n            m_gateway.Tick();\n\n\n            //清除非激活的Game\n            uint current = (uint)TimeUtils.GetTotalMillisecondsSince1970();\n\n            if (current - m_lastClearGameTime > FSPGame.ActiveTimeout * 1000 / 2)\n            {\n                m_lastClearGameTime = current;\n                ClearNoActiveGame();\n            }\n\n            long nowticks = DateTime.Now.Ticks;\n            long interval = nowticks - m_lastTicks;\n\n            //这里做了Fixbug\n            long frameIntervalTicks = m_param.serverFrameInterval * 10000;\n            if (interval > frameIntervalTicks)\n            {\n                m_lastTicks = nowticks - (nowticks % (frameIntervalTicks));\n\n                if (!m_UseCustomEnterFrame)\n                {\n                    EnterFrame();\n                }\n            }\n        }\n\n\n        public void EnterFrame()\n        {\n            if (m_gateway.IsRunning)\n            {\n                var listGame = m_mapGame.AsList();\n                for (int i = 0; i < listGame.Count; i++)\n                {\n                    listGame[i].EnterFrame();\n                }\n            }\n            \n        }\n\n\n        private void ClearNoActiveGame()\n        {\n            var list = m_mapGame.AsList();\n            var dir = m_mapGame.AsDictionary();\n            int cnt = list.Count;\n\n            for (int i = cnt - 1; i >= 0; i--)\n            {\n                var game = list[i];\n                if (game.IsGameEnd())\n                {\n                    list.RemoveAt(i);\n                    dir.Remove(game.id);\n                }\n            }\n        }\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/FSPLite/Server/FSPPlayer.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace SGF.Network.FSPLite.Server\n{\n    public class FSPPlayer\n    {\n        private uint m_id;\n        public uint id { get { return m_id; } }\n\n        private bool m_hasAuthed = false;\n        private FSPSession m_session;\n        private Action<FSPPlayer, FSPMessage> m_RecvListener;\n\n        //发送数据\n        private Queue<FSPFrame> m_FrameCache = null;\n\n        private int m_LastAddFrameId = 0;\n\n        private int m_authId = 0;\n\n        public bool WaitForExit = false;\n\n        //=================================================================\n        public void Create(uint id, int authId, FSPSession session, Action<FSPPlayer, FSPMessage> listener)\n        {\n            Debuger.Log(\"id:{0}, authId:{1}, sid:{2}\", id, authId, session.id);\n\n            m_id = id;\n            m_authId = authId;\n            m_RecvListener = listener;\n            m_session = session;\n            m_session.SetReceiveListener(OnRecvFromSession);\n\n            m_FrameCache = new Queue<FSPFrame>();\n\n        }\n\n        public void Release()\n        {\n            Debuger.Log();\n            if (m_session != null)\n            {\n                m_session.SetReceiveListener(null);\n                m_session.Active(false);\n                m_session = null;\n            }\n        }\n\n        public string ToString(string prefix = \"\")\n        {\n            StringBuilder sb = new StringBuilder();\n            sb.AppendFormat(\"[{0}] Auth:{1}, IsLose:{2}, EndPoint:{3}\", m_id, HasAuthed, IsLose(), m_session.RemoteEndPoint);\n            return sb.ToString();\n        }\n\n\n        //====================================================================\n        //接收数据逻辑\n\n        private void OnRecvFromSession(FSPDataC2S data)\n        {\n            if (m_session.IsEndPointChanged)\n            {\n                m_session.IsEndPointChanged = false;\n                m_hasAuthed = false;\n            }\n\n            if (m_RecvListener != null)\n            {\n                for (int i = 0; i < data.msgs.Count; i++)\n                {\n                    m_RecvListener(this, data.msgs[i]);\n                }\n            }\n        }\n\n\n        //====================================================================\n        //发送相关逻辑\n        public void SendToClient(FSPFrame frame)\n        {\n            if (frame != null)\n            {\n                if (!m_FrameCache.Contains(frame))\n                {\n                    m_FrameCache.Enqueue(frame);\n                }\n            }\n\n\n            while (m_FrameCache.Count > 0)\n            {\n                if (SendInternal(m_FrameCache.Peek()))\n                {\n                    m_FrameCache.Dequeue();\n                }\n            }\n        }\n\n        private bool SendInternal(FSPFrame frame)\n        {\n            if (frame.frameId != 0 && frame.frameId <= m_LastAddFrameId)\n            {\n                //已经Add过了\n                return true;\n            }\n\n\n            if (m_session != null)\n            {\n                if (m_session.Send(frame))\n                {\n                    m_LastAddFrameId = frame.frameId;\n                    return true;\n                }\n            }\n\n            return false;\n        }\n\n        //====================================================================\n        //鉴权相关逻辑\n\n        public void SetAuth(int authId)\n        {\n            Debuger.Log(authId);\n            //这里暂时不做真正的鉴权，只是让流程完整\n            m_hasAuthed = m_authId == authId;\n\n        }\n\n        public bool HasAuthed { get { return m_hasAuthed; } }\n\n        //====================================================================\n\n\n        public void ClearRound()\n        {\n            Debuger.Log();\n            m_FrameCache.Clear();\n            m_LastAddFrameId = 0;\n        }\n\n        public bool IsLose()\n        {\n            return !m_session.IsActived();\n        }\n\n\n    }\n\n\n}"
  },
  {
    "path": "SGFCore/Network/FSPLite/Server/FSPSession.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 帧同步模块\n * Frame synchronization module\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Net;\nusing System.Text;\nusing SGF.Codec;\nusing SGF.Network.Core;\nusing SGF.Time;\nusing SGF.Utils;\n\n\nnamespace SGF.Network.FSPLite.Server\n{\n    public class FSPSession\n    {\n        public static int ActiveTimeout = 300;\n        private int m_lastActiveTime;\n        private bool m_active = false;\n        \n\n        private uint m_id;\n        private ushort m_ping;\n        private Action<IPEndPoint, byte[], int> m_sender;\n        private Action<FSPDataC2S> m_listener;\n\n        //RUDP\n        private KCP m_Kcp;\n        private SwitchQueue<byte[]> m_RecvBufQueue = new SwitchQueue<byte[]>();\n        private uint m_NextKcpUpdateTime = 0;\n        private bool m_NeedKcpUpdateFlag = false;\n\n        //数据发送\n        private byte[] m_SendBufferTemp = new byte[4096];\n        private FSPDataS2C m_TempSendData = new FSPDataS2C();\n\n\n        public FSPSession(uint sid, Action<IPEndPoint, byte[], int> sender)\n        {\n            Debuger.Log();\n            m_id = sid;\n            m_sender = sender;\n\n            m_Kcp = new KCP(sid, HandleKcpSend);\n            m_Kcp.NoDelay(1, 10, 2, 1);\n            m_Kcp.WndSize(128, 128);\n\n            m_active = true;\n        }\n\n        public string ToString(string prefix = \"\")\n        {\n            StringBuilder sb = new StringBuilder();\n            sb.AppendFormat(\"[{0}] Active:{1}, Ping:{2}, EndPoint:{3}\", m_id, m_active, m_ping, RemoteEndPoint);\n            return sb.ToString();\n        }\n\n        public void SetReceiveListener(Action<FSPDataC2S> listener)\n        {\n            Debuger.Log();\n            m_listener = listener;\n        }\n\n        public uint id { get { return m_id; } }\n        public ushort ping { get { return m_ping; } set { m_ping = value; } }\n        public IPEndPoint RemoteEndPoint { get; private set; }\n        public bool IsEndPointChanged { get; set; }\n\n\n        public void Active(IPEndPoint remoteEndPoint)\n        {\n            m_lastActiveTime = (int)SGFTime.GetTimeSinceStartup();\n            m_active = true;\n\n            if (this.RemoteEndPoint == null || !this.RemoteEndPoint.Equals(remoteEndPoint))\n            {\n                IsEndPointChanged = true;\n                this.RemoteEndPoint = remoteEndPoint;\n            }\n            \n        }\n\n        public void Active(bool value)\n        {\n            m_active = value;\n        }\n\n        public bool IsActived()\n        {\n            if (!m_active)\n            {\n                return false;\n            }\n\n            int dt = (int)SGFTime.GetTimeSinceStartup() - m_lastActiveTime;\n            if (dt > ActiveTimeout)\n            {\n                m_active = false;\n            }\n            return m_active;\n        }\n\n\n        //==================================================================\n        //发送数据\n        //==================================================================\n        public bool Send(FSPFrame frame)\n        {\n            if (!IsActived())\n            {\n                Debuger.LogWarning(\"Session已经不活跃了！\");\n                return false;\n            }\n\n            m_TempSendData.frames.Clear();\n            m_TempSendData.frames.Add(frame);\n            int len = PBSerializer.NSerialize(m_TempSendData, m_SendBufferTemp);\n            return m_Kcp.Send(m_SendBufferTemp, len) == 0;\n        }\n\n        private void HandleKcpSend(byte[] buffer, int size)\n        {\n            m_sender(RemoteEndPoint, buffer, size);\n        }\n\n        //==================================================================\n        //接收数据\n        //==================================================================\n        public void DoReceiveInGateway(byte[] buffer, int size)\n        {\n            byte[] dst = new byte[size];\n            Buffer.BlockCopy(buffer, 0, dst, 0, size);\n            m_RecvBufQueue.Push(dst);\n        }\n\n        private void DoReceiveInMain()\n        {\n            m_RecvBufQueue.Switch();\n\n            while (!m_RecvBufQueue.Empty())\n            {\n                var recvBufferRaw = m_RecvBufQueue.Pop();\n                int ret = m_Kcp.Input(recvBufferRaw, recvBufferRaw.Length);\n\n                //收到的不是一个正确的KCP包\n                if (ret < 0)\n                {\n                    Debuger.LogError(\"收到不正确的KCP包!Ret:{0}\", ret);\n                    return;\n                }\n\n                m_NeedKcpUpdateFlag = true;\n\n                for (int size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize())\n                {\n                    var recvBuffer = new byte[size];\n                    if (m_Kcp.Recv(recvBuffer) > 0)\n                    {\n                        if (m_listener != null)\n                        {\n                            FSPDataC2S data = PBSerializer.NDeserialize<FSPDataC2S>(recvBuffer);\n                            m_listener(data);\n                        }\n                        else\n                        {\n                            Debuger.LogError(\"找不到接收者！\");\n                        }\n                    }\n                }\n            }\n        }\n\n\n        public void Tick(uint currentTimeMS)\n        {\n            DoReceiveInMain();\n\n            uint current = currentTimeMS;\n\n            if (m_NeedKcpUpdateFlag || current >= m_NextKcpUpdateTime)\n            {\n                m_Kcp.Update(current);\n                m_NextKcpUpdateTime = m_Kcp.Check(current);\n                m_NeedKcpUpdateFlag = false;\n            }\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Client/IConnection.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 连接接口定义（客户端）\n * Connection interface definition (client)\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Net;\nusing SGF.Network.General.Proto;\nusing SGF.SEvent;\n\nnamespace SGF.Network.General.Client\n{\n    public interface IConnection\n    {\n        /// <summary>\n        /// 当收到数据时发出信号\n        /// 参数：字节数组，长度\n        /// </summary>\n        Signal<NetMessage> onReceive { get; }\n        Signal<IConnection, int, string> onServerError{ get; }\n        \n        /// <summary>\n        /// 清理整个连接，即反初始化\n        /// 它是统一管理的\n        /// </summary>\n        void Clean();\n\n        /// <summary>\n        /// 主动关闭连接\n        /// 对于Client来讲，有可能再次重连\n        /// 对于Server来讲，用于强制将 Client断线，然后由Gateway统一Clean\n        /// </summary>\n        void Close();\n\n        /// <summary>\n        /// 连接操作\n        /// </summary>\n        /// <param name=\"remoteIP\"></param>\n        /// <param name=\"remotePort\"></param>\n        void Connect(string remoteIP, int remotePort);\n        void Connect(IPEndPoint[] listRemoteEndPoints);\n\n        /// <summary>\n        /// SessionID\n        /// </summary>\n        uint Id { get; }\n\n        /// <summary>\n        /// 连接是否被激活\n        /// </summary>\n        bool IsActived { get; }\n\n        /// <summary>\n        /// 连接的Ping值\n        /// </summary>\n        ushort Ping { get; set; }\n\n        /// <summary>\n        /// 初始化成功后，可以获取本地EndPoint\n        /// </summary>\n        IPEndPoint LocalEndPoint { get; }\n\n        /// <summary>\n        /// 连接建立后，可以获取远端EndPoint\n        /// </summary>\n        IPEndPoint RemoteEndPoint { get; }\n\n        /// <summary>\n        /// 数据发送\n        /// 有可能是同步模式\n        /// 也可能是异步模式\n        /// </summary>\n        /// <param name=\"msg\"></param>\n        /// <returns></returns>\n        bool Send(NetMessage msg);\n\n\n        /// <summary>\n        /// 无论是用IOCP，还是自己实现的IO模型\n        /// 都可能需要在网络线程与主线程之间【统一】同步数据\n        /// 当然只是可能，也不是必要的\n        /// 但是参照Apollo的设计，还是统一同步数据的\n        /// </summary>\n        void Tick();\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Client/KCPConnection.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 基于KCP的可靠UDP连接类（客户端）\n * KCP-based reliable UDP connection class (client)\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading;\nusing SGF.SEvent;\nusing SGF.Network.Core;\nusing SGF.Utils;\nusing SGF.Network.General.Proto;\nusing System.Collections.Generic;\nusing SGF.Codec;\n\nnamespace SGF.Network.General.Client\n{\n    public class KcpConnection:IConnection, ILogTag\n    {\n        public string LOG_TAG { get; protected set; }\n\n        //==========================================================\n        //事件\n        //==========================================================\n        public Signal<IConnection, int, string> onSendError { get; private set; }\n        public Signal<IConnection, int, string> onReceiveError { get; private set; }\n        public Signal<IConnection, int, string> onServerError { get; private set; }\n\n        /// <summary>\n        /// 当收到数据时发出信号\n        /// 参数：字节数组，长度\n        /// </summary>\n        public Signal<NetMessage> onReceive { get; private set; }\n\n        //==========================================================\n        //公共成员变量\n        //==========================================================\n        public uint Id { get; protected set; }\n        public IPEndPoint LocalEndPoint { get; private set; }\n        public IPEndPoint RemoteEndPoint { get; private set; }\n        public ushort Ping { get; set; }\n        public bool IsActived { get { return Thread.VolatileRead(ref this.m_actived) == 1; } }\n        private int m_actived = 0;\n\n\n        //==========================================================\n        //私有成员变量\n        //==========================================================\n        private Socket m_socket;\n        private Thread m_ThreadRecv;\n        private byte[] m_RecvBufferTemp = new byte[4096];\n        \n        private List<IPEndPoint> m_listRemoteEndPoint;\n        private int m_currRemoteEndPointIndex = -1;\n        private int m_localPort;\n        \n        private bool m_waitReconnect = false;\n\n        //KCP\n        private KCP m_Kcp;\n        private SwitchQueue<byte[]> m_RecvBufQueue = new SwitchQueue<byte[]>();\n        private uint m_NextKcpUpdateTime = 0;\n        private bool m_NeedKcpUpdateFlag = false;\n\n        //发送相关\n        private NetBufferWriter m_bufferSend;\n        private NetBufferWriter m_bufferReceive = null;\n\n\n        //==========================================================\n        //构造函数\n        //==========================================================\n        public KcpConnection(int localPort)\n        {\n            LOG_TAG = \"KcpConnection[\" + 0 + \",\" + localPort + \"]\";\n            this.Log(\"connId:{0}, localPort:{1}\", 0, localPort);\n\n            onReceive = new Signal<NetMessage>();\n            onSendError = new Signal<IConnection, int, string>();\n            onReceiveError = new Signal<IConnection, int, string>();\n            onServerError = new Signal<IConnection, int, string>();\n\n            m_listRemoteEndPoint = new List<IPEndPoint>();\n            m_currRemoteEndPointIndex = -1;\n\n            m_bufferSend = new NetBufferWriter(new byte[0]);\n            m_bufferReceive = new NetBufferWriter(new byte[NetDefine.ReceiveBufferMinSize]);\n\n            m_localPort = localPort;\n        }\n\n\n        public void Clean()\n        {\n            this.Log();\n\n            onReceive.RemoveAllListeners();\n            onReceiveError.RemoveAllListeners();\n            onSendError.RemoveAllListeners();\n            onServerError.RemoveAllListeners();\n\n            Close();\n        }\n\n        //======================================================================\n        //连接与断开连接\n        //======================================================================\n\n        public void Connect(string remoteIP, int remotePort)\n        {\n            this.Log(\"{0}:{1}\", remoteIP, remotePort);\n\n            IPAddress ipaddr = null;\n            if (!IPAddress.TryParse(remoteIP, out ipaddr))\n            {\n                this.LogError(\"无法解析为有效的IPAddress:{0}\", remoteIP);\n                return;\n            }\n\n            m_listRemoteEndPoint.Clear();\n            m_listRemoteEndPoint.Add(new IPEndPoint(ipaddr, remotePort));\n            m_currRemoteEndPointIndex = 0;\n            \n            ConnectInternal(m_listRemoteEndPoint[m_currRemoteEndPointIndex]);\n        }\n\n        public void Connect(IPEndPoint[] listRemoteEndPoint)\n        {\n\n            if (listRemoteEndPoint.Length == 0)\n            {\n                this.LogError(\"参数错误：listRemoteEndPoint.Length = 0\");\n                return;\n            }\n\n            m_listRemoteEndPoint.Clear();\n            m_listRemoteEndPoint.AddRange(listRemoteEndPoint);\n            m_currRemoteEndPointIndex = 0;\n\n            ConnectInternal(m_listRemoteEndPoint[m_currRemoteEndPointIndex]);\n        }\n\n        public void Close()\n        {\n            this.Log();\n            this.m_actived = 0;\n\n            if (m_Kcp != null)\n            {\n                m_Kcp.Dispose();\n                m_Kcp = null;\n            }\n\n\n            if (m_ThreadRecv != null)\n            {\n                m_ThreadRecv.Interrupt();\n                m_ThreadRecv = null;\n            }\n\n            if (m_socket != null)\n            {\n                try { m_socket.Shutdown(SocketShutdown.Both); }\n                catch (Exception ex) { this.LogWarning(ex.Message); }\n\n                m_socket.Close();\n                m_socket = null;\n            }\n        }\n\n        private void TryReconnect()\n        {\n            Debuger.LogWarning(\"\");\n\n            if (!IsActived)\n            {\n                m_currRemoteEndPointIndex++;\n                m_currRemoteEndPointIndex = m_currRemoteEndPointIndex % m_listRemoteEndPoint.Count;\n                ConnectInternal(m_listRemoteEndPoint[m_currRemoteEndPointIndex]);\n            }\n            else\n            {\n                this.LogWarning(\"当前连接还在，不能重连！\");\n            }\n        }\n\n\n        private void ConnectInternal(IPEndPoint remoteEndPoint)\n        {\n            this.Log();\n            m_waitReconnect = false;\n\n            var socket = new Socket(remoteEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);\n            var localEndPoint = new IPEndPoint(IPAddress.Any, m_localPort);\n            try { socket.Bind(localEndPoint); }\n            catch (Exception exception) { this.LogWarning(\"指定的Port无法绑定:{0}\", localEndPoint); }\n\n            Active(socket, (IPEndPoint)remoteEndPoint);\n\n            LOG_TAG = \"KcpConnection[\" + Id + \",\" + LocalEndPoint.Port + \"]\";\n            this.LogVerbose(\"连接成功！\");\n        }\n\n        public void Active(Socket socket, IPEndPoint remoteEndPoint)\n        {\n            if (Interlocked.CompareExchange(ref this.m_actived, 1, 0) == 0)\n            {\n                m_socket = socket;\n\n                socket.ReceiveBufferSize = NetDefine.SocketBufferSize;\n                socket.SendBufferSize = NetDefine.SocketBufferSize;\n\n                RemoteEndPoint = (IPEndPoint)remoteEndPoint;\n                LocalEndPoint = (IPEndPoint)socket.LocalEndPoint;\n\n                ResetKcp();\n\n                m_ThreadRecv = new Thread(Thread_Recv) { IsBackground = true };\n                m_ThreadRecv.Start();\n            }\n        }\n\n        private void ResetKcp()\n        {\n            m_Kcp = new KCP(0, HandleKcpSend);\n            m_Kcp.NoDelay(1, 10, 2, 1);\n            m_Kcp.WndSize(128, 128);\n        }\n\n        //======================================================================\n        //发送数据\n        //======================================================================\n        public bool Send(NetMessage msg)\n        {\n            //主线程\n            this.LogVerbose();\n\n            msg.head.sid = Id;\n\n            m_bufferSend.Attach(new byte[msg.Length], 0);\n            msg.Serialize(m_bufferSend);\n\n            var bytes = m_bufferSend.GetBytes();\n            var len = m_bufferSend.Length;\n\n            return m_Kcp.Send(bytes, len) > 0;\n        }\n\n\n        private void HandleKcpSend(byte[] bytes, int len)\n        {\n            //主线程\n            m_hasSocketException = false;\n            m_socket.SendTo(bytes, 0, len, SocketFlags.None, RemoteEndPoint);\n        }\n\n        //======================================================================\n        //接收数据\n        //======================================================================\n        protected void DoReceiveInThread()\n        {\n            //子线程\n            this.LogVerbose();\n\n            bool result = false;\n            try\n            {\n                EndPoint remotePoint = IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, 0);\n                int cnt = m_socket.ReceiveFrom(m_RecvBufferTemp, m_RecvBufferTemp.Length, SocketFlags.None, ref remotePoint);\n\n                if (cnt > 0)\n                {\n                    if (!RemoteEndPoint.Equals(remotePoint))\n                    {\n                        Debuger.LogVerbose(\"收到非目标服务器的数据！\");\n                        return;\n                    }\n\n                    m_bufferReceive.Attach(m_RecvBufferTemp, cnt);\n                    byte[] m_32b = new byte[4];\n                    m_bufferReceive.ReadBytes(m_32b, 0, 4);\n                    uint sid = BitConverter.ToUInt32(m_32b, 0);\n                    \n                    if(sid == 0)\n                    {\n                        //Session过期了\n                        HandleServerError((int)NetErrorCode.SessionExpire);\n                        return;\n                    }\n\n                    byte[] dst = new byte[cnt];\n                    Buffer.BlockCopy(m_RecvBufferTemp, 0, dst, 0, cnt);\n                    \n                    m_RecvBufQueue.Push(dst);\n                }\n            }\n            catch (Exception ex)\n            {\n                this.LogWarning(\"接收数据出错：{0}\", ex.Message);\n                onReceiveError.InvokeSafe(this, (int)NetErrorCode.UnkownError, ex.Message);\n            }\n        }\n\n        private void DoReceiveInMain()\n        {\n            //主线程\n            m_RecvBufQueue.Switch();\n\n            while (!m_RecvBufQueue.Empty())\n            {\n                var recvBufferRaw = m_RecvBufQueue.Pop();\n                int ret = m_Kcp.Input(recvBufferRaw, recvBufferRaw.Length);\n\n                //收到的不是一个正确的KCP包\n                if (ret < 0)\n                {\n                    Debuger.LogError(\"收到不正确的KCP包!Ret:{0}\", ret);\n                    return;\n                }\n\n                m_NeedKcpUpdateFlag = true;\n\n                for (int size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize())\n                {\n                    var recvBuffer = new byte[size];\n                    if (m_Kcp.Recv(recvBuffer) > 0)\n                    {\n                        NetMessage msg = new NetMessage();\n                        msg.Deserialize(recvBuffer, size);\n\n\n                        if (msg.head.sid == 0)\n                        {\n                            var errmsg = PBSerializer.NDeserialize<NetErrorMessage>(msg.content);\n                            this.LogWarning(\"服务器返回错误:{0},{1}\", errmsg.code, errmsg.info);\n\n                            HandleServerError(errmsg.code);\n\n                            onServerError.InvokeSafe(this, errmsg.code, errmsg.info);\n                        }\n                        else\n                        {\n                            //更新SessionId\n                            if (Id != msg.head.sid)\n                            {\n                                Id = msg.head.sid;\n                                LOG_TAG = \"KcpConnection[\" + Id + \",\" + m_localPort + \"]\";\n                                this.LogWarning(\"SessionId发生变化：{0}\", Id);\n                            }\n\n                            onReceive.InvokeSafe(msg);\n                        }\n                    }\n                }\n\n            }\n\n        }\n\n        private void HandleServerError(int errcode)\n        {\n            if (errcode == (int)NetErrorCode.SessionExpire)\n            {\n                Id = 0;\n                LOG_TAG = \"KcpConnection[\" + Id + \",\" + m_localPort + \"]\";\n                this.LogWarning(\"Session过期!\");\n            }\n\n            onServerError.InvokeSafe(this, (int)NetErrorCode.UnkownError, \"\");\n        }\n\n        //=================================================================================\n        //接收线程 \n        //=================================================================================\n        private bool m_hasSocketException = false;\n        private void Thread_Recv()\n        {\n            while (IsActived)\n            {\n                try\n                {\n                    DoReceiveInThread();\n\n                    if (m_hasSocketException)\n                    {\n                        m_hasSocketException = false;\n                        Debuger.LogWarning(\"连接异常已经恢复\");\n                    }\n                }\n                catch (SocketException se)\n                {\n                    if (!m_hasSocketException)\n                    {\n                        m_hasSocketException = true;\n                    }\n\n                    Debuger.LogWarning(\"SocketErrorCode:{0}, {1}\", se.SocketErrorCode, se.Message);\n                    Thread.Sleep(1);\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(e.Message + \"\\n\" + e.StackTrace);\n                    Thread.Sleep(1);\n                }\n                \n            }\n\n            Debuger.LogWarning(\"End!\");\n        }\n\n\n\n\n        public void Tick()\n        {\n            if (IsActived)\n            {\n                DoReceiveInMain();\n\n                uint current = (uint) TimeUtils.GetTotalMillisecondsSince1970();\n\n                if (m_NeedKcpUpdateFlag || current >= m_NextKcpUpdateTime)\n                {\n                    if (m_Kcp != null)\n                    {\n                        m_Kcp.Update(current);\n                        m_NextKcpUpdateTime = m_Kcp.Check(current);\n                        m_NeedKcpUpdateFlag = false;\n                    }\n                }\n            }\n            else\n            {\n                if (m_waitReconnect)\n                {\n                    TryReconnect();\n                }\n            }\n        }\n\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/Network/General/Client/NetManager.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 网络模块管理器（客户端）\n * Network Module Manager (Client)\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Net;\nusing System.Reflection;\nusing System.Text;\nusing SGF.Codec;\nusing SGF.Network.Core;\nusing SGF.Network.Core.RPCLite;\nusing SGF.Network.General.Proto;\nusing SGF.SEvent;\nusing SGF.Time;\nusing SGF.Utils;\n\n\nnamespace SGF.Network.General.Client\n{\n    public class NetManager\n    {\n        public Signal onDisconnected { get; private set; }\n        public Signal onConnectFailed { get; private set; }\n        private IConnection m_conn;\n        private uint m_token;\n        private RPCManager m_rpc;\n\n        public void Init(ConnectionType connType, int localPort = 0)\n        {\n            Debuger.Log(\"connType:{0}, localPort:{1}\", connType, localPort);\n\n            if (connType == ConnectionType.TCP)\n            {\n                var conn = new TcpConnection(localPort, null, 3);\n                m_conn = conn;\n                conn.onDisconnected.AddListener(OnDisconnected);\n                conn.onConnectError.AddListener(OnConnectError);\n            }\n            else if (connType == ConnectionType.UDP)\n            {\n                m_conn = new UdpConnection(localPort, null);\n            }\n            else if(connType == ConnectionType.RUDP)\n            {\n                m_conn = new KcpConnection(localPort);\n            }\n            else\n            {\n                throw new ArgumentException(\"未实现该连接类型：\" + connType);\n            }\n\n            onDisconnected = new Signal();\n            onConnectFailed = new Signal();\n\n            m_rpc = new RPCManager(m_conn);\n            m_rpc.Init();\n        }\n\n        public RPCManager Rpc { get { return m_rpc; } }\n\n        public void Clean()\n        {\n            Debuger.Log();\n            if (m_conn != null)\n            {\n                m_conn.Clean();\n                m_conn = null;\n            }\n\n            if (m_rpc != null)\n            {\n                m_rpc.Clean();\n                m_rpc = null;\n            }\n\n\n            m_listNtfListener.Clear();\n            m_listRspListener.Clear();\n\n        }\n\n        private void OnDisconnected(IConnection  conn)\n        {\n            onDisconnected.Invoke();\n        }\n\n        private void OnConnectError(IConnection conn, int code)\n        {\n            if(code == (int)NetErrorCode.ReconnectFailed)\n            {\n                onConnectFailed.Invoke();\n            }\n        }\n\n        public void Dump()\n        {\n            StringBuilder sb = new StringBuilder();\n\n            foreach (var pair in m_listNtfListener)\n            {\n                ListenerHelper helper = pair.Value;\n                sb.AppendFormat(\"\\t<cmd:{0}, msg:{1}, \\tlistener:{2}.{3}>\\n\", pair.Key, helper.TMsg.Name,\n                    helper.onMsgMethod.DeclaringType.Name, helper.onMsgMethod.Name);\n            }\n\n            Debuger.LogWarning(\"\\nNotify Listeners ({0}):\\n{1}\", m_listNtfListener.Count, sb);\n\n            sb.Length = 0;\n            var dic = m_listRspListener.AsDictionary();\n            foreach (var pair in dic)\n            {\n                ListenerHelper helper = pair.Value;\n                sb.AppendFormat(\"\\t<index:{0}, msg:{1}, \\tlistener:{2}.{3}>\\n\", pair.Key, helper.TMsg.Name,\n                    helper.onMsgMethod.DeclaringType.Name, helper.onMsgMethod.Name);\n            }\n\n            Debuger.LogWarning(\"\\nRespond Listeners ({0}):\\n{1}\", m_listRspListener.Count, sb);\n\n            m_rpc.Dump();\n        }\n\n        public void SetToken(uint token)\n        {\n            Debuger.Log(token);\n            m_token = token;\n            m_rpc.SetToken(token);\n        }\n\n\n        public void Connect(string ip, int port)\n        {\n            Debuger.Log(\"ip:{0}, port:{1}\", ip, port);\n\n            if (m_conn.IsActived)\n            {\n                Debuger.Log(\"旧的连接还在，先关闭旧的连接\");\n                m_conn.Close();\n            }\n\n            m_conn.Connect(ip, port);\n            m_conn.onReceive.AddListener(OnReceive);\n        }\n\n        public void Connect(IPEndPoint[] listEndPoints)\n        {\n            if (m_conn.IsActived)\n            {\n                Debuger.Log(\"旧的连接还在，先关闭旧的连接\");\n                m_conn.Close();\n            }\n\n            m_conn.Connect(listEndPoints);\n            m_conn.onReceive.AddListener(OnReceive);\n        }\n\n        public bool IsConnected { get { return m_conn.IsActived; } }\n\n        public void Close()\n        {\n            Debuger.Log();\n            m_conn.Close();\n        }\n\n\n        public void Tick()\n        {\n            m_conn.Tick();\n            CheckTimeout();\n        }\n\n\n        private void OnReceive(NetMessage msg)\n        {\n            if (msg.head.cmd == 0)\n            {\n                RPCMessage rpcmsg = PBSerializer.NDeserialize<RPCMessage>(msg.content);\n                m_rpc.OnReceive(rpcmsg);\n            }\n            else\n            {\n                HandlePBMessage(msg);\n            }\n        }\n\n\n\n\n\n        //========================================================================\n        //传统的协议(Protobuf)处理方式\n        //========================================================================\n\n\n        class ListenerHelper\n        {\n            public uint cmd;\n            public uint index;\n            public Type TMsg;\n            public Delegate onMsg0;\n            public Delegate onMsg1;\n            public Delegate onErr;\n            public float timeout;\n            public float timestamp;\n\n            public MethodInfo onMsgMethod\n            {\n                get\n                {\n                    var onMsg_ = onMsg0 != null ? onMsg0 : (onMsg1 != null ? onMsg1 : null);\n                    return onMsg_.Method;\n                }\n            }\n        }\n\n        static class MessageIndexGenerator\n        {\n            private static uint m_lastIndex;\n            public static uint NewIndex()\n            {\n                return ++m_lastIndex;\n            }\n        }\n\n        private DictionarySafe<uint, ListenerHelper> m_listNtfListener = new DictionarySafe<uint, ListenerHelper>();\n        private MapList<uint, ListenerHelper> m_listRspListener = new MapList<uint, ListenerHelper>();\n\n\n        /// <summary>\n        /// 发送数据\n        /// </summary>\n        /// <typeparam name=\"TRsp\"></typeparam>\n        /// <param name=\"cmd\"></param>\n        /// <param name=\"req\"></param>\n        /// <param name=\"onRsp\"></param>\n        /// <param name=\"timeout\"></param>\n        /// <param name=\"onErr\"></param>\n        /// <returns>返回唯一的发送Index</returns>\n        public uint Send<TRsp>(uint cmd, object req, Action<uint, TRsp> onRsp, float timeout = 30,\n            Action<NetErrorCode> onErr = null)\n        {\n            Debuger.LogVerbose(\"cmd:{0}, timeout:{1}\", cmd, timeout);\n            uint index = MessageIndexGenerator.NewIndex();\n            ListenerHelper helper = new ListenerHelper()\n            {\n                cmd = cmd,\n                index = index,\n                TMsg = typeof(TRsp),\n                onErr = onErr,\n                onMsg0 = onRsp,\n                timeout = timeout,\n                timestamp = SGFTime.GetTimeSinceStartup()\n            };\n\n            m_listRspListener.Add(index, helper);\n\n\n            NetMessage msg = new NetMessage();\n            msg.head.index = index;\n            msg.head.cmd = cmd;\n            msg.head.token = m_token;\n            msg.content = PBSerializer.NSerialize(req);\n            msg.head.dataSize = (uint)msg.content.Length;\n\n            m_conn.Send(msg);\n            return index;\n        }\n\n\n        public void Send<TReq>(uint cmd, TReq req)\n        {\n            Debuger.LogVerbose(\"cmd:{0}\", cmd);\n\n            NetMessage msg = new NetMessage();\n            msg.head.index = 0;\n            msg.head.cmd = cmd;\n            msg.head.token = m_token;\n            msg.content = PBSerializer.NSerialize(req);\n            msg.head.dataSize = (uint)msg.content.Length;\n\n            m_conn.Send(msg);\n        }\n\n        public void Send<TMsg>(ProtocolHead head, uint cmd, TMsg msg)\n        {\n            Debuger.LogVerbose(\"cmd:{0}\", cmd);\n\n            NetMessage msgobj = new NetMessage();\n            msgobj.head = head;\n            msgobj.head.cmd = cmd;\n            msgobj.head.token = m_token;\n            msgobj.content = PBSerializer.NSerialize(msg);\n            msgobj.head.dataSize = (uint)msgobj.content.Length;\n\n            m_conn.Send(msgobj);\n        }\n\n\n        public void AddListener<TNtf>(uint cmd, Action<ProtocolHead, TNtf> onNtf)\n        {\n            Debuger.Log(\"cmd:{0}, listener:{1}.{2}\", cmd, onNtf.Method.DeclaringType.Name, onNtf.Method.Name);\n\n\n            ListenerHelper helper = new ListenerHelper()\n            {\n                TMsg = typeof(TNtf),\n                onMsg1 = onNtf\n            };\n\n            m_listNtfListener.Add(cmd, helper);\n        }\n\n        public void RemoveListener(uint cmd)\n        {\n            Debuger.Log(\"cmd:{0}\", cmd);\n            m_listNtfListener.Remove(cmd);\n        }\n\n\n        private void HandlePBMessage(NetMessage msg)\n        {\n            Debuger.LogVerbose(\"msg.head:{0}\", msg.head);\n\n            if (msg.head.index == 0)\n            {\n                var helper = m_listNtfListener[msg.head.cmd];\n                if (helper != null)\n                {\n                    object obj = null;\n\n                    try\n                    {\n                        obj = PBSerializer.NDeserialize(msg.content, helper.TMsg);\n                    }\n                    catch (Exception e)\n                    {\n                        Debuger.LogError(\"MsgName:{0}, msg.head:{0}\", helper.TMsg.Name, msg.head);\n                        Debuger.LogError(\"DeserializeError:\" + e.Message);\n                    }\n\n                    if (obj != null)\n                    {\n                        try\n                        {\n                            helper.onMsg1.DynamicInvoke(msg.head, obj);\n                        }\n                        catch (Exception e)\n                        {\n                            Debuger.LogError(\"MsgName:{0}, msg.head:{0}\", helper.TMsg.Name, msg.head);\n                            Debuger.LogError(\"BusinessError:\" + e.Message + \"\\n\" + e.StackTrace);\n                        }\n\n                    }\n                    else\n                    {\n                        Debuger.LogError(\"协议格式错误！ cmd:{0}\", msg.head.cmd);\n                    }\n                }\n                else\n                {\n                    Debuger.LogError(\"未找到对应的监听者! cmd:{0}\", msg.head.cmd);\n                }\n            }\n            else\n            {\n                var helper = m_listRspListener[msg.head.index];\n                if (helper != null)\n                {\n                    m_listRspListener.Remove(msg.head.index);\n\n                    object obj = PBSerializer.NDeserialize(msg.content, helper.TMsg);\n                    if (obj != null)\n                    {\n                        helper.onMsg0.DynamicInvoke(msg.head.index, obj);\n                    }\n                    else\n                    {\n                        Debuger.LogError(\"协议格式错误！ cmd:{0}, index:{0}\", msg.head.cmd, msg.head.index);\n                    }\n                }\n                else\n                {\n                    Debuger.LogError(\"未找到对应的监听者! cmd:{0}, index:{0}\", msg.head.cmd, msg.head.index);\n                }\n            }\n        }\n\n\n        private float m_lastCheckTimeoutStamp = 0;\n\n        private void CheckTimeout()\n        {\n            float curTime = SGFTime.GetTimeSinceStartup();\n\n            if (curTime - m_lastCheckTimeoutStamp >= 5)\n            {\n                m_lastCheckTimeoutStamp = curTime;\n\n                var list = m_listRspListener.ToArray();\n                for (int i = 0; i < list.Length; i++)\n                {\n                    var helper = list[i];\n                    float dt = curTime - helper.timestamp;\n                    if (dt >= helper.timeout && helper.timeout > 0)\n                    {\n                        m_listRspListener.Remove(helper.index);\n                        if (helper.onErr != null)\n                        {\n                            helper.onErr.DynamicInvoke(NetErrorCode.Timeout);\n                        }\n\n                        Debuger.LogWarning(\"cmd:{0} Is Timeout!\", helper.cmd);\n                    }\n                }\n            }\n\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Client/RPCManager.cs",
    "content": "﻿using SGF.Codec;\nusing SGF.Network.Core.RPCLite;\nusing SGF.Network.General.Proto;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\n\nnamespace SGF.Network.General.Client\n{\n    public class RPCManager:RPCManagerBase\n    {\n        private IConnection m_conn;\n        private uint m_token;\n\n        public  RPCManager(IConnection conn)\n        {\n            m_conn = conn;\n        }\n\n        public void OnReceive(RPCMessage msg)\n        {\n            HandleRPCMessage(msg);\n        }\n\n        public void SetToken(uint token)\n        {\n            Debuger.Log(token);\n            m_token = token;\n        }\n\n        //========================================================================\n        //RPC的协议处理方式\n        //========================================================================\n\n        private string m_currInvokingName;\n\n        private void HandleRPCMessage(RPCMessage rpcmsg)\n        {\n            Debuger.LogVerbose(\"Connection[{0}]-> {1}({2})\", m_conn.Id, rpcmsg.name, rpcmsg.args);\n            \n            var helper = GetMethodHelper(rpcmsg.name);\n            if (helper != null)\n            {\n                object[] args = rpcmsg.args;\n                var raw_args = rpcmsg.raw_args;\n\n                var paramInfo = helper.method.GetParameters();\n\n                if (raw_args.Count == paramInfo.Length)\n                {\n                    for (int i = 0; i < raw_args.Count; i++)\n                    {\n                        if (raw_args[i].type == RPCArgType.PBObject)\n                        {\n                            var type = paramInfo[i].ParameterType;\n                            object arg = PBSerializer.NDeserialize(raw_args[i].raw_value, type);\n                            args[i] = arg;\n                        }\n                    }\n\n                    m_currInvokingName = rpcmsg.name;\n\n                    try\n                    {\n                        helper.method.Invoke(helper.listener, BindingFlags.NonPublic, null, args, null);\n                    }\n                    catch (Exception e)\n                    {\n                        Debuger.LogError(\"RPC调用出错：{0}\\n{1}\", e.Message, e.StackTrace);\n                    }\n\n                    m_currInvokingName = null;\n                }\n                else\n                {\n                    Debuger.LogWarning(\"参数数量不一致！\");\n                }\n\n            }\n            else\n            {\n                Debuger.LogWarning(\"RPC不存在！\");\n            }\n        }\n\n\n\n        public void Invoke(string name, params object[] args)\n        {\n            Debuger.LogVerbose(\"->Connection[{0}] {1}({2})\", m_conn.Id, name, args);\n            \n            RPCMessage rpcmsg = new RPCMessage();\n            rpcmsg.name = name;\n            rpcmsg.args = args;\n            byte[] buffer = PBSerializer.NSerialize(rpcmsg);\n\n            NetMessage msg = new NetMessage();\n            msg.head = new ProtocolHead();\n            msg.head.token = m_token;\n            msg.head.dataSize = (uint)buffer.Length;\n            msg.content = buffer;\n\n            m_conn.Send(msg);\n\n        }\n\n        public void Return(params object[] args)\n        {\n            if (m_conn != null)\n            {\n                var name = \"On\" + m_currInvokingName;\n                Debuger.Log(\"->Connection[{0}] {1}({2})\", m_conn.Id, name, args);\n\n                RPCMessage rpcmsg = new RPCMessage();\n                rpcmsg.name = name;\n                rpcmsg.args = args;\n                byte[] buffer = PBSerializer.NSerialize(rpcmsg);\n\n                NetMessage msg = new NetMessage();\n                msg.head = new ProtocolHead();\n                msg.head.token = m_token;\n                msg.head.dataSize = (uint)buffer.Length;\n                msg.content = buffer;\n                \n                m_conn.Send(msg);\n            }\n        }\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/Network/General/Client/TcpConnection.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading;\nusing SGF.Network.Core;\nusing SGF.Network.General.Proto;\nusing SGF.SEvent;\n\n\nnamespace SGF.Network.General.Client\n{\n    public class TcpConnection:TcpConnectionBase, IConnection\n    {\n        //==========================================================\n        //事件\n        //==========================================================\n        public Signal<IConnection> onConnecting { get; private set; }\n        public Signal<IConnection> onConnectSuccess { get; private set; }\n        public Signal<IConnection, int> onConnectError { get; private set; }\n        public Signal<IConnection> onDisconnected { get; private set; }\n        public Signal<IConnection, int, string> onSendError { get; private set; }\n        public Signal<IConnection> onSendSuccess { get; private set; }\n        public Signal<IConnection, int, string> onReceiveError{ get; private set; }\n        public Signal<IConnection, int, string> onServerError { get; private set; }\n        /// <summary>\n        /// 当收到数据时发出信号\n        /// 参数：字节数组，长度\n        /// </summary>\n        public Signal<NetMessage> onReceive { get; private set; }\n\n        \n        //==========================================================\n        //私有成员变量\n        //==========================================================\n        private List<IPEndPoint> m_listRemoteEndPoint;\n        private int m_currRemoteEndPointIndex = -1;\n        private int m_localPort;\n        private int m_maxReconnCnt = 0;\n        private int m_curReconnIndex = 0;\n\n        //==========================================================\n        //构造函数\n        //==========================================================\n        public TcpConnection(int localPort, SocketAsyncEventArgsPool pool, int maxReconnCnt = 0):base(pool)\n        {\n            LOG_TAG = \"TcpConnection[\" + 0 + \",\" + localPort + \"]\";\n            this.Log(\"connId:{0}, localPort:{1}, maxReconnCnt\", 0, localPort, maxReconnCnt);\n            m_maxReconnCnt = maxReconnCnt;\n            onReceive = new Signal<NetMessage>();\n            onConnectSuccess = new Signal<IConnection>();\n            onConnectError = new Signal<IConnection, int>();\n            onDisconnected = new Signal<IConnection>();\n            onSendSuccess = new Signal<IConnection>();\n            onSendError = new Signal<IConnection, int, string>();\n            onConnecting = new Signal<IConnection>();\n            onReceiveError = new Signal<IConnection, int, string>();\n            onServerError = new Signal<IConnection, int, string>();\n            m_listRemoteEndPoint = new List<IPEndPoint>();\n            m_currRemoteEndPointIndex = -1;\n\n            m_localPort = localPort;\n        }\n\n\n        public override void Clean()\n        {\n            base.Clean();\n            onReceive.RemoveAllListeners();\n            onConnectSuccess.RemoveAllListeners();\n            onConnectError.RemoveAllListeners();\n            onDisconnected.RemoveAllListeners();\n            onSendSuccess.RemoveAllListeners();\n            onSendError.RemoveAllListeners();\n            onConnecting.RemoveAllListeners();\n            onReceiveError.RemoveAllListeners();\n            onServerError.RemoveAllListeners();\n            m_listRemoteEndPoint.Clear();\n            GC.SuppressFinalize(this);\n            \n        }\n        \n        //======================================================================\n        //连接与断开连接\n        //======================================================================\n        /// <summary>\n        /// 连接\n        /// </summary>\n        /// <param name=\"remoteIP\"></param>\n        /// <param name=\"remotePort\"></param>\n        public void Connect(string remoteIP, int remotePort)\n        {\n            this.Log(\"{0}:{1}\", remoteIP, remotePort);\n            \n            IPAddress ipaddr = null;\n            if (!IPAddress.TryParse(remoteIP, out ipaddr))\n            {\n                this.LogError(\"无法解析为有效的IPAddress:{0}\", remoteIP);\n                return;\n            }\n\n            m_listRemoteEndPoint.Clear();\n            m_listRemoteEndPoint.Add(new IPEndPoint(ipaddr, remotePort));\n            m_currRemoteEndPointIndex = 0;\n\n            ConnectInternal(m_listRemoteEndPoint[m_currRemoteEndPointIndex]);\n        }\n\n        public void Connect(IPEndPoint[] listRemoteEndPoint)\n        {\n            \n            if (listRemoteEndPoint.Length == 0)\n            {\n                this.LogError(\"参数错误：listRemoteEndPoint.Length = 0\");\n                return;\n            }\n\n            m_listRemoteEndPoint.Clear();\n            m_listRemoteEndPoint.AddRange(listRemoteEndPoint);\n            m_currRemoteEndPointIndex = 0;\n\n            ConnectInternal(m_listRemoteEndPoint[m_currRemoteEndPointIndex]);\n        }\n\n\n\n        private void TryReconnect()\n        {\n            this.Log();\n\n            if (!IsActived)\n            {\n\n                if (m_maxReconnCnt == 0 || m_curReconnIndex < m_maxReconnCnt)\n                {\n                    m_curReconnIndex++;\n\n                    if (m_listRemoteEndPoint.Count > 0)\n                    {\n                        m_currRemoteEndPointIndex++;\n                        m_currRemoteEndPointIndex = m_currRemoteEndPointIndex % m_listRemoteEndPoint.Count;\n                        ConnectInternal(m_listRemoteEndPoint[m_currRemoteEndPointIndex]);\n                    }\n                }\n                else\n                {\n                    onConnectError.Invoke(this, (int)NetErrorCode.ReconnectFailed);\n                }\n            }\n            else\n            {\n                this.LogWarning(\"当前连接还在，不能重连！\");\n            }\n        }\n\n        private void ConnectInternal(IPEndPoint remoteEndPoint)\n        {\n            this.Log();\n\n            onConnecting.Invoke(this);\n\n            var socket = new Socket(remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);\n\n            var localEndPoint = new IPEndPoint(IPAddress.Any, m_localPort);\n            try { socket.Bind(localEndPoint); }\n            catch (Exception exception) { this.LogWarning(\"指定的Port无法绑定:{0}\", localEndPoint); }\n\n            \n            var e = new SocketAsyncEventArgs();\n            e.UserToken = socket;\n            e.RemoteEndPoint = remoteEndPoint;\n            e.Completed += OnConnectCompleted;\n\n            bool result = false;\n            try\n            {\n                result = socket.ConnectAsync(e);\n            }\n            catch (Exception ex)\n            {\n                this.LogWarning(ex.Message);\n            }\n\n            if (!result)\n            {\n                ThreadPool.QueueUserWorkItem(_ => OnConnectCompleted(null, e));\n            }\n\n        }\n\n        private void OnConnectCompleted(object sender, SocketAsyncEventArgs e)\n        {\n            this.Log(e.SocketError.ToString());\n\n            var socket = e.UserToken as Socket;\n            var error = e.SocketError;\n            e.UserToken = null;\n            e.Completed -= OnConnectCompleted;\n            e.Dispose();\n\n            if (error != SocketError.Success)\n            {\n                socket.Close();\n                this.LogWarning(\"连接失败：{0}\", error);\n\n                OnConnectError((int)error);\n            }\n            else\n            {\n                base.Active(socket);\n\n                LOG_TAG = \"TcpConnection[\" + Id + \",\" + LocalEndPoint.Port + \"]\";\n                this.Log(\"连接成功！\");\n\n                onConnectSuccess.Invoke(this);\n            }\n        }\n\n        private void OnConnectError(int errcode)\n        {\n            this.LogWarning(errcode.ToString());\n            onConnectError.Invoke(this, errcode);\n\n            ThreadPool.QueueUserWorkItem(_ => TryReconnect());\n        }\n\n        protected override void OnDisconnected()\n        {\n            base.OnDisconnected();\n            onDisconnected.Invoke(this);\n        }\n\n\n        //======================================================================\n        //发送数据\n        //======================================================================\n        \n        protected override void OnSendError(int errcode, string info)\n        {\n            this.LogWarning(\"{0}:{1}\", errcode, info);\n            onSendError.Invoke(this, errcode,info);\n        }\n\n        protected override void OnSendSuccess()\n        {\n            onSendSuccess.Invoke(this);\n        }\n\n        //======================================================================\n        //接收数据\n        //======================================================================\n        protected override void OnReceiveError(int errcode, string info)\n        {\n            this.LogWarning(\"{0}:{1}\", errcode, info);\n            onReceiveError.Invoke(this, errcode,info);\n        }\n\n\n        public void Tick()\n        {\n            var msg = base.Receive();\n            while (msg != null)\n            {\n                //更新SessionId\n                if (Id != msg.head.sid)\n                {\n                    Id = msg.head.sid;\n                    LOG_TAG = \"TcpConnection[\" + Id + \",\" + m_localPort + \"]\";\n                    this.LogWarning(\"SessionId发生变化：{0}\", Id);\n                }\n\n                onReceive.Invoke(msg);\n                msg = base.Receive();\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Client/UdpConnection.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 基于UDP的不可靠连接类（客户端）\n * UDP-based unreliable connection class (client)\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading;\nusing SGF.Codec;\nusing SGF.Network.Core;\nusing SGF.Network.General.Proto;\nusing SGF.SEvent;\n\nnamespace SGF.Network.General.Client\n{\n    public class UdpConnection: IConnection, ILogTag\n    {\n        public string LOG_TAG { get; protected set; }\n\n        //==========================================================\n        //事件\n        //==========================================================\n        public Signal<IConnection, int, string> onSendError { get; private set; }\n        public Signal<IConnection, int, string> onReceiveError { get; private set; }\n        public Signal<IConnection, int, string> onServerError { get; private set; }\n\n        /// <summary>\n        /// 当收到数据时发出信号\n        /// 参数：字节数组，长度\n        /// </summary>\n        public Signal<NetMessage> onReceive { get; private set; }\n\n        //==========================================================\n        //公共成员变量\n        //==========================================================\n        public uint Id { get; protected set; }\n        public IPEndPoint LocalEndPoint { get; private set; }\n        public IPEndPoint RemoteEndPoint { get; private set; }\n        public ushort Ping { get; set; }\n        public bool IsActived { get { return Thread.VolatileRead(ref this.m_actived) == 1; } }\n        private int m_actived = 0;\n        //==========================================================\n        //私有成员变量\n        //==========================================================\n        private Socket m_socket;\n        private SocketAsyncEventArgsPool m_pool;\n\n        private List<IPEndPoint> m_listRemoteEndPoint;\n        private int m_currRemoteEndPointIndex = -1;\n        private int m_localPort;\n\n        //发送相关\n        private SocketAsyncEventArgs m_saeSend = null;\n        private NetPacket m_currSendingPacket = null;\n        private Queue<NetPacket> m_queueSend;\n        private NetBufferWriter m_bufferSend;\n        private int m_sending = 0;\n\n        //接收相关\n        private SocketAsyncEventArgs m_saeReceive = null;\n        private Queue<NetMessage> m_queueReceive;\n        private NetBufferWriter m_bufferReceive;\n\n\n        //==========================================================\n        //构造函数\n        //==========================================================\n        public UdpConnection(int localPort, SocketAsyncEventArgsPool pool)\n        {\n            LOG_TAG = \"UdpConnection[\" + 0 + \",\" + localPort + \"]\";\n            this.Log(\"connId:{0}, localPort:{1}\", 0, localPort);\n\n            onReceive = new Signal<NetMessage>();\n            onSendError = new Signal<IConnection, int, string>();\n            onReceiveError = new Signal<IConnection, int, string>();\n            onServerError = new Signal<IConnection, int, string>();\n\n            m_listRemoteEndPoint = new List<IPEndPoint>();\n            m_currRemoteEndPointIndex = -1;\n\n            m_pool = new SocketAsyncEventArgsPool(NetDefine.PacketBufferSize, 0);\n\n            m_queueSend = new Queue<NetPacket>();\n            m_bufferSend = new NetBufferWriter(new byte[0]);\n\n            m_queueReceive = new Queue<NetMessage>();\n            m_bufferReceive = new NetBufferWriter(new byte[NetDefine.ReceiveBufferMinSize]);\n\n            m_localPort = localPort;\n        }\n\n\n        public void Clean()\n        {\n            this.Log();\n            \n            onReceive.RemoveAllListeners();\n            onReceiveError.RemoveAllListeners();\n            onSendError.RemoveAllListeners();\n            onServerError.RemoveAllListeners();\n\n            Close();\n        }\n\n\n\n        private void CleanSend()\n        {\n            this.Log();\n\n            m_currSendingPacket = null;\n\n            if (m_saeSend != null)\n            {\n                m_saeSend.Completed -= OnSendCompleted;\n                m_pool.Release(m_saeSend);\n                m_saeSend = null;\n            }\n        }\n\n        private void CleanReceive()\n        {\n            this.Log();\n\n            if (m_saeReceive != null)\n            {\n                m_saeReceive.Completed -= OnReceiveCompleted;\n                m_pool.Release(m_saeReceive);\n                m_saeReceive = null;\n            }\n        }\n\n        //======================================================================\n        //连接与断开连接\n        //======================================================================\n        /// <summary>\n        /// 连接\n        /// </summary>\n        /// <param name=\"remoteIP\"></param>\n        /// <param name=\"remotePort\"></param>\n        public void Connect(string remoteIP, int remotePort)\n        {\n            this.Log(\"{0}:{1}\", remoteIP, remotePort);\n\n            IPAddress ipaddr = null;\n            if (!IPAddress.TryParse(remoteIP, out ipaddr))\n            {\n                this.LogError(\"无法解析为有效的IPAddress:{0}\", remoteIP);\n                return;\n            }\n\n            m_listRemoteEndPoint.Clear();\n            m_listRemoteEndPoint.Add(new IPEndPoint(ipaddr, remotePort));\n            m_currRemoteEndPointIndex = 0;\n\n            ConnectInternal(m_listRemoteEndPoint[m_currRemoteEndPointIndex]);\n        }\n\n        public void Connect(IPEndPoint[] listRemoteEndPoint)\n        {\n\n            if (listRemoteEndPoint.Length == 0)\n            {\n                this.LogError(\"参数错误：listRemoteEndPoint.Length = 0\");\n                return;\n            }\n\n            m_listRemoteEndPoint.Clear();\n            m_listRemoteEndPoint.AddRange(listRemoteEndPoint);\n            m_currRemoteEndPointIndex = 0;\n\n            ConnectInternal(m_listRemoteEndPoint[m_currRemoteEndPointIndex]);\n        }\n\n        public void Close()\n        {\n            this.Log();\n            this.m_actived = 0;\n\n            if (m_socket != null)\n            {\n                try { m_socket.Shutdown(SocketShutdown.Both); }\n                catch (Exception ex) { this.LogWarning(ex.Message); }\n\n                m_socket.Close();\n                m_socket = null;\n            }\n\n\n            CleanSend();\n            CleanReceive();\n        }\n\n\n        private void TryReconnect()\n        {\n            this.Log();\n\n            if (!IsActived)\n            {\n                m_currRemoteEndPointIndex++;\n                m_currRemoteEndPointIndex = m_currRemoteEndPointIndex % m_listRemoteEndPoint.Count;\n                ConnectInternal(m_listRemoteEndPoint[m_currRemoteEndPointIndex]);\n            }\n            else\n            {\n                this.LogWarning(\"当前连接还在，不能重连！\");\n            }\n        }\n\n        private void ConnectInternal(IPEndPoint remoteEndPoint)\n        {\n            this.Log();\n\n            var socket = new Socket(remoteEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);\n\n            var localEndPoint = new IPEndPoint(IPAddress.Any, m_localPort);\n            try { socket.Bind(localEndPoint); }\n            catch (Exception exception) { this.LogWarning(\"指定的Port无法绑定:{0}\", localEndPoint); }\n\n\n            var e = new SocketAsyncEventArgs();\n            e.UserToken = socket;\n            e.RemoteEndPoint = remoteEndPoint;\n            e.Completed += OnConnectCompleted;\n\n            ThreadPool.QueueUserWorkItem(_ => OnConnectCompleted(null, e));\n        }\n\n        private void OnConnectCompleted(object sender, SocketAsyncEventArgs e)\n        {\n            this.LogVerbose(e.SocketError.ToString());\n\n            var socket = e.UserToken as Socket;\n            var error = e.SocketError;\n            e.UserToken = null;\n            e.Completed -= OnConnectCompleted;\n            e.Dispose();\n\n            Active(socket, (IPEndPoint)e.RemoteEndPoint);\n\n            LOG_TAG = \"UdpConnection[\" + Id + \",\" + LocalEndPoint.Port + \"]\";\n            this.LogVerbose(\"连接成功！\");          \n        }\n\n\n        public void Active(Socket socket, IPEndPoint remoteEndPoint)\n        {\n            if (Interlocked.CompareExchange(ref this.m_actived, 1, 0) == 0)\n            {\n                m_socket = socket;\n                \n                socket.ReceiveBufferSize = NetDefine.SocketBufferSize;\n                socket.SendBufferSize = NetDefine.SocketBufferSize;\n\n                RemoteEndPoint = (IPEndPoint)remoteEndPoint;\n                LocalEndPoint = (IPEndPoint)socket.LocalEndPoint;\n\n                m_saeSend = m_pool.Acquire();\n                m_saeSend.Completed += OnSendCompleted;\n                m_saeSend.RemoteEndPoint = remoteEndPoint;\n\n                m_saeReceive = m_pool.Acquire();\n                m_saeReceive.Completed += OnReceiveCompleted;\n                m_saeReceive.RemoteEndPoint = remoteEndPoint;\n\n                BeginSend();\n                BeginReceive();\n            }\n        }\n\n\n        //======================================================================\n        //发送数据\n        //======================================================================\n\n        public bool Send(NetMessage msg)\n        {\n            this.LogVerbose();\n\n            msg.head.sid = Id;\n\n            m_bufferSend.Attach(new byte[msg.Length], 0);\n            msg.Serialize(m_bufferSend);\n\n            NetPacket packet = new NetPacket(m_bufferSend.GetBytes());\n\n            lock (m_queueSend)\n            {\n                m_queueSend.Enqueue(packet);\n            }\n\n            if (m_sending == 0 && m_actived == 1)\n            {\n                if (m_currSendingPacket == null)\n                {\n                    lock (m_queueSend)\n                    {\n                        if (m_queueSend.Count > 0)\n                        {\n                            m_currSendingPacket = m_queueSend.Dequeue();\n                            SendInternal(m_saeSend);\n                        }\n                    }\n                }\n            }\n\n            return true;\n        }\n\n        protected void BeginSend()\n        {\n            TrySendNext();\n        }\n\n        private void TrySendNext()\n        {\n            this.LogVerbose();\n\n            if (m_sending == 0)\n            {\n                if (m_currSendingPacket == null)\n                {\n                    lock (m_queueSend)\n                    {\n                        if (m_queueSend.Count > 0)\n                        {\n                            m_currSendingPacket = m_queueSend.Dequeue();\n                            SendInternal(m_saeSend);\n                        }\n                    }\n                }\n            }\n        }\n\n        private void SendInternal(SocketAsyncEventArgs e)\n        {\n            this.LogVerbose(e.SocketError.ToString());\n\n            m_sending = 1;\n\n            var packet = m_currSendingPacket;\n\n            var length = Math.Min(packet.Bytes.Length - packet.SentSize, e.Buffer.Length);\n            var result = false;\n            try\n            {\n                Buffer.BlockCopy(packet.Bytes, packet.SentSize, e.Buffer, 0, length);\n                e.SetBuffer(0, length);\n                result = m_socket.SendToAsync(e);\n            }\n            catch (Exception ex)\n            {\n                this.LogWarning(\"发送数据出错：{0}\", ex.Message);\n                onSendError.InvokeSafe(this, (int)NetErrorCode.UnkownError,ex.Message);\n            }\n\n            if (!result)\n            {\n                ThreadPool.QueueUserWorkItem(_ => OnSendCompleted(this, e));\n            }\n        }\n\n        private void OnSendCompleted(object sender, SocketAsyncEventArgs e)\n        {\n            this.LogVerbose(e.SocketError.ToString());\n\n            if (e.SocketError != SocketError.Success)\n            {\n                this.LogWarning(\"发送失败！{0}\", e.SocketError);\n                onSendError.InvokeSafe(this,(int)NetErrorCode.UnkownError, e.SocketError.ToString());\n\n                //继续发下一个Packet\n                m_currSendingPacket = null;\n                m_sending = 0;\n                TrySendNext();\n\n                return;\n            }\n\n            var packed = m_currSendingPacket;\n            packed.SentSize += e.BytesTransferred;\n\n            //将PackedBufferSize的Buffer发送完\n            if (e.Offset + e.BytesTransferred < e.Count)\n            {\n                var result = true;\n                try\n                {\n                    e.SetBuffer(e.Offset + e.BytesTransferred, e.Count - e.BytesTransferred - e.Offset);\n                    result = m_socket.SendAsync(e);\n                }\n                catch (Exception ex)\n                {\n                    this.LogWarning(\"发送数据出错：{0}\", ex.Message);\n                    onSendError.InvokeSafe(this, (int)NetErrorCode.UnkownError, ex.Message);\n                }\n\n                if (!result)\n                {\n                    ThreadPool.QueueUserWorkItem(_ => OnSendCompleted(this, e));\n                }\n            }\n            else\n            {\n\n                if (!packed.IsSent)\n                {\n                    //继续发当前Packet的下一个分组\n                    SendInternal(e);\n                }\n                else\n                {\n                    //一个Packet发送完成\n                    m_currSendingPacket = null;\n                    m_sending = 0;\n                    \n                    //继续发下一个Packet\n                    TrySendNext();\n                }\n            }\n        }\n\n\n        //======================================================================\n        //接收数据\n        //======================================================================\n        protected void BeginReceive()\n        {\n            ReceiveInternal();\n        }\n\n        private void ReceiveInternal()\n        {\n            this.LogVerbose();\n\n            bool result = false;\n            try\n            {\n                result = m_socket.ReceiveFromAsync(m_saeReceive);\n            }\n            catch (Exception ex)\n            {\n                this.LogWarning(\"接收数据出错：{0}\", ex.Message);\n                onReceiveError.InvokeSafe(this, (int) NetErrorCode.UnkownError, ex.Message);\n            }\n\n            if (!result)\n            {\n                ThreadPool.QueueUserWorkItem(_ => OnReceiveCompleted(this, m_saeReceive));\n            }\n\n        }\n\n        private void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)\n        {\n            this.LogVerbose(e.SocketError.ToString());\n\n            if (e.SocketError != SocketError.Success)\n            {\n                this.LogWarning(\"接收出错！{0}\", e.SocketError);\n                onReceiveError.InvokeSafe(this, (int)NetErrorCode.SocketError, e.SocketError.ToString());\n                ReceiveInternal();\n                return;\n            }\n\n            if (e.BytesTransferred < 1)\n            {\n                this.LogWarning(\"接收出错！{0}\", e.SocketError);\n                onReceiveError.InvokeSafe(this, (int)NetErrorCode.SocketError, e.SocketError.ToString());\n                ReceiveInternal();\n                return;\n            }\n\n\n            m_bufferReceive.Attach(e.Buffer, e.BytesTransferred);\n            NetMessage msg = new NetMessage();\n            if (msg.Deserialize(m_bufferReceive))\n            {\n                lock (m_queueReceive)\n                {\n                    m_queueReceive.Enqueue(msg);\n                }\n            }\n            else\n            {\n                this.LogError(\"反序列化失败！\");\n                onReceiveError.InvokeSafe(this, (int)NetErrorCode.DeserializeError, \"反序列化失败\");\n            }\n            \n            ReceiveInternal();\n        }\n\n\n\n        //===================================================================\n        /// <summary>\n        /// 主线程读取数据\n        /// </summary>\n        /// <returns></returns>\n        private NetMessage Receive()\n        {\n            NetMessage msg = null;\n            lock (m_queueReceive)\n            {\n                if (m_queueReceive.Count > 0)\n                {\n                    msg = m_queueReceive.Dequeue();\n                    return msg;\n                }\n            }\n\n            return null;\n\n        }\n\n        public void Tick()\n        {\n            var msg = Receive();\n            while (msg != null)\n            {\n                if (msg.head.sid == 0)\n                {\n                    var errmsg = PBSerializer.NDeserialize<NetErrorMessage>(msg.content);\n                    this.LogWarning(\"服务器返回错误:{0},{1}\", errmsg.code, errmsg.info);\n\n                    HandleServerError(errmsg.code);\n\n                    onServerError.InvokeSafe(this, errmsg.code, errmsg.info);\n                }\n                else\n                {\n                    //更新SessionId\n                    if (Id != msg.head.sid)\n                    {\n                        Id = msg.head.sid;\n                        LOG_TAG = \"UdpConnection[\" + Id + \",\" + m_localPort + \"]\";\n                        this.LogWarning(\"SessionId发生变化：{0}\", Id);\n                    }\n\n                    onReceive.InvokeSafe(msg);\n                }\n\n                msg = Receive();\n            }\n        }\n\n        private void HandleServerError(int errcode)\n        {\n            if (errcode == (int) NetErrorCode.SessionExpire)\n            {\n                Id = 0;\n                LOG_TAG = \"UdpConnection[\" + Id + \",\" + m_localPort + \"]\";\n                this.LogWarning(\"Session过期!\");\n            }\n\n            onServerError.InvokeSafe(this, (int)NetErrorCode.UnkownError, \"\");\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/ConnectionType.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nnamespace SGF.Network.General\n{\n    public enum ConnectionType\n    {\n        TCP = 1,\n        UDP = 2,\n        RUDP = 3,\n        FSP = 4\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/NetDefine.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nnamespace SGF.Network.General\n{\n    public class NetDefine\n    {\n        /// <summary>\n        /// 收包数据的最小Buffer大小\n        /// 实际收包时，如果Buffer里的数据没有人读取，会自动扩容\n        /// </summary>\n        public static int ReceiveBufferMinSize = 1024;\n\n        /// <summary>\n        /// Socket的Buffer大小\n        /// </summary>\n        public static int SocketBufferSize = 8192;\n\n        /// <summary>\n        /// 底层分包的Buffer大小\n        /// </summary>\n        public static int PacketBufferSize = 8192;\n    }\n\n    \n}"
  },
  {
    "path": "SGFCore/Network/General/NetPacket.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\n\nnamespace SGF.Network.General\n{\n    public class NetPacket\n    {\n        internal int SentSize;\n        public readonly byte[] Bytes;\n        \n        public NetPacket(byte[] bytes)\n        {\n            if (bytes == null) throw new ArgumentNullException(\"bytes\");\n            this.Bytes = bytes;\n        }\n\n\n\n        public bool IsSent { get { return this.SentSize == Bytes.Length; } }\n    }\n\n    \n\n}"
  },
  {
    "path": "SGFCore/Network/General/Proto/NetErrorProto.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing ProtoBuf;\n\nnamespace SGF.Network.General.Proto\n{\n    [ProtoContract]\n    public class NetErrorMessage\n    {\n        [ProtoMember(1)]\n        public int code;\n        [ProtoMember(2)]\n        public string info;\n    }\n\n    [ProtoContract]\n    public class ReturnCode\n    {\n        public static ReturnCode Success = new ReturnCode();\n        public static ReturnCode UnkownError = new ReturnCode(1, \"UnkownError\");\n\n        public ReturnCode(int code, string info)\n        {\n            this.code = code;\n            this.info = info;\n        }\n\n        public ReturnCode()\n        {\n            this.code = 0;\n            this.info = \"\";\n        }\n\n\n\n        [ProtoMember(1)]\n        public int code = 0;\n        [ProtoMember(2)]\n        public string info = \"\";\n\n        public override string ToString()\n        {\n            return string.Format(\"ErrCode:{0}, Info:{1}\", code, info);\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Proto/NetMessage.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 封装了网络消息\n * Encapsulates network messages\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\nusing SGF.Network.Core;\n\nnamespace SGF.Network.General.Proto\n{\n    public class NetMessage\n    {\n        private static NetBuffer DefaultWriter = new NetBuffer(4096);\n        private static NetBuffer DefaultReader = new NetBuffer(4096);\n\n        public ProtocolHead head = new ProtocolHead();\n        public byte[] content;\n\n        public uint Length{get { return head.dataSize + ProtocolHead.Length; } }\n\n        public bool Deserialize(NetBuffer buffer)\n        {\n            if (head.Deserialize(buffer))\n            {\n                if (buffer.BytesAvailable >= head.dataSize)\n                {\n                    content = new byte[head.dataSize];\n                    buffer.ReadBytes(content, 0, (int)head.dataSize);\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        public NetBuffer Serialize(NetBuffer buffer)\n        {\n            head.Serialize(buffer);\n            buffer.WriteBytes(content, 0, (int)head.dataSize);\n            return buffer;\n        }\n\n        public bool Deserialize(byte[] buffer, int size)\n        {\n            lock (DefaultReader)\n            {\n                DefaultReader.Attach(buffer, size);\n                return Deserialize(DefaultReader);\n            }\n        }\n\n        public int Serialize(out byte[] tempBuffer)\n        {\n            lock (DefaultWriter)\n            {\n                DefaultWriter.Clear();\n                this.Serialize(DefaultWriter);\n                tempBuffer = DefaultWriter.GetBytes();\n                return DefaultWriter.Length;\n            }\n\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Proto/ProfilerTestProto.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing ProtoBuf;\n\nnamespace SGF.Network.General.Proto\n{\n    internal class ProfilerTestProto\n    {\n        public class ProtoCmd\n        {\n            public static uint LoginReq = 1;\n            public static uint LoginRsp = 2;\n            public static uint HeartBeatReq = 3;\n            public static uint HeartBeatRsp = 4;\n        }\n\n\n        [ProtoContract]\n        public class LoginReq\n        {\n            [ProtoMember(1)]\n            public uint id;\n            [ProtoMember(2)]\n            public string name;\n        }\n\n        [ProtoContract]\n        public class LoginRsp\n        {\n            [ProtoMember(1)]\n            public int ret;\n            [ProtoMember(2)]\n            public string name;\n        }\n\n        [ProtoContract]\n        public class HeartBeatReq\n        {\n            [ProtoMember(1)]\n            public ushort ping;\n            [ProtoMember(2)]\n            public uint timestamp;\n        }\n\n        [ProtoContract]\n        public class HeartBeatRsp\n        {\n            [ProtoMember(1)]\n            public int ret;\n            [ProtoMember(2)]\n            public uint timestamp;\n        }\n    }\n    \n\n}"
  },
  {
    "path": "SGFCore/Network/General/Proto/ProtocolHead.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 封装了协议头\n * Encapsulates protocol head\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing SGF.Network.Core;\n\nnamespace SGF.Network.General.Proto\n{\n    public class ProtocolHead\n    {\n        public const int Length = 44;\n        public uint sid = 0;\n        public uint token = 0;\n        public uint cmd = 0;\n        public uint index = 0;\n        public ulong player = 0;\n        public int zone = 0;\n        public ulong runner = 0; \n        public uint dataSize = 0;\n        public uint checksum = 0;\n\n        public override string ToString()\n        {\n            return string.Format(\"sid:{0}, token:{1}, cmd:{2}, index:{3}, player:{4}, zone:{5}, runner:{6}, dataSize:{7}, checksum:{8}\", sid, token, cmd,\n                index, player,zone,runner, dataSize, checksum);\n        }\n\n        public bool Deserialize(NetBuffer buffer)\n        {\n            if (buffer.BytesAvailable >= Length)\n            {\n                ProtocolHead head = this;\n                head.sid = buffer.ReadUInt();\n                head.token = buffer.ReadUInt();\n                head.cmd = buffer.ReadUInt();\n                head.index = buffer.ReadUInt();\n                head.player = buffer.ReadULong();\n                head.zone = buffer.ReadInt();\n                head.runner = buffer.ReadULong();\n                head.dataSize = buffer.ReadUInt();\n                head.checksum = buffer.ReadUInt();\n                return true;\n            }\n\n            return false;\n        }\n\n        public NetBuffer Serialize(NetBuffer buffer)\n        {\n            buffer.WriteUInt(sid);\n            buffer.WriteUInt(token);\n            buffer.WriteUInt(cmd);\n            buffer.WriteUInt(index);\n            buffer.WriteULong(player);\n            buffer.WriteInt(zone);\n            buffer.WriteULong(runner);\n            buffer.WriteUInt(dataSize);\n            buffer.WriteUInt(checksum);\n            return buffer;\n        }\n\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Server/IGateway.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nnamespace SGF.Network.General.Server\n{\n    public interface IGateway\n    {\n        void Clean();\n        void Dump();\n        void Tick();\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Server/ISession.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 会话接口定义（客户端）\n * Session interface definition (client)\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System.Net;\nusing SGF.Network.General.Proto;\n\n\nnamespace SGF.Network.General.Server\n{\n    public interface ISessionListener\n    {\n        void OnReceive(ISession session, NetMessage msg);\n        void OnDisconnected(ISession session);\n    }\n\n    public interface ISession\n    {\n        uint AuthToken { get; set; }\n        /// <summary>\n        /// SessionID\n        /// </summary>\n        uint Id { get; }\n        /// <summary>\n        /// 连接是否被激活\n        /// </summary>\n        bool IsActived { get; }\n\n        /// <summary>\n        /// 连接的Ping值\n        /// </summary>\n        ushort Ping { get; set; }\n        /// <summary>\n        /// 初始化成功后，可以获取本地EndPoint\n        /// </summary>\n        IPEndPoint LocalEndPoint { get; }\n\n        /// <summary>\n        /// 连接建立后，可以获取远端EndPoint\n        /// </summary>\n        IPEndPoint RemoteEndPoint { get; }\n\n        /// <summary>\n        /// 数据发送\n        /// 有可能是同步模式\n        /// 也可能是异步模式\n        /// </summary>\n        /// <param name=\"bytes\"></param>\n        /// <returns></returns>\n        bool Send(NetMessage msg);\n\n        void Tick(int currentMS);\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Server/KCPGateway.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 网关类（服务器）\n * Gateway class (Server)\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nusing SGF.Network.Core;\nusing SGF.Utils;\n\nnamespace SGF.Network.General.Server\n{\n    public class KcpGateway : IGateway, ILogTag\n    {\n        public string LOG_TAG { get; protected set; }\n        public IPEndPoint LocalEndPoint { get; private set; }\n        public static int SessionActiveTimeout = 5;\n        private MapList<uint, KcpSession> m_mapSession;\n        private bool m_IsRunning = false;\n        private ISessionListener m_listener;\n        private int m_port;\n\n        private Socket m_socket = null;\n        private NetBufferWriter m_bufferReceive = null;\n        private Thread m_ThreadRecv;\n        private byte[] m_RecvBufferTemp = new byte[4096];\n        private bool m_waitStart = false;\n\n\n        public KcpGateway(int port, ISessionListener listener)\n        {\n            LOG_TAG = \"KcpGateway<\" + port + \">\";\n            this.Log(\"port:{0}\", port);\n\n            m_bufferReceive = new NetBufferWriter();\n\n            m_port = port;\n            m_listener = listener;\n\n            m_mapSession = new MapList<uint, KcpSession>();\n\n            Start();\n        }\n\n        public void Clean()\n        {\n            this.Log();\n            m_mapSession.Clear();\n            Close();\n        }\n\n        public void Dump()\n        {\n            StringBuilder sb = new StringBuilder();\n\n            var dic = m_mapSession.AsDictionary();\n            foreach (var pair in dic)\n            {\n                ISession session = pair.Value;\n                sb.AppendLine(\"\\t\" + session.ToString());\n            }\n\n            this.LogWarning(\"\\nGateway Sessions ({0}):\\n{1}\", m_mapSession.Count, sb);\n\n        }\n\n        private static long m_lastSessionId = 0;\n        private uint NewSessionID()\n        {\n            return (uint)Interlocked.Increment(ref m_lastSessionId);\n        }\n\n\n        private void Start()\n        {\n            this.LogWarning(\"\");\n\n            m_IsRunning = true;\n\n            if (m_socket == null)\n            {\n                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\n                m_socket.Bind(new IPEndPoint(IPAddress.Any, m_port));\n                LocalEndPoint = m_socket.LocalEndPoint as IPEndPoint;\n                m_port = LocalEndPoint.Port; ;\n\n                m_ThreadRecv = new Thread(Thread_Recv) { IsBackground = true };\n                m_ThreadRecv.Start();\n            }\n        }\n\n        private void DoReceiveInThread()\n        {\n            EndPoint remotePoint = IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, 0);\n            int cnt = m_socket.ReceiveFrom(m_RecvBufferTemp, m_RecvBufferTemp.Length, SocketFlags.None, ref remotePoint);\n\n            if (cnt > 0)\n            {\n                m_bufferReceive.Attach(m_RecvBufferTemp, cnt);\n                byte[] m_32b = new byte[4];\n                m_bufferReceive.ReadBytes(m_32b, 0, 4);\n                uint sid = BitConverter.ToUInt32(m_32b, 0);\n\n                lock (m_mapSession)\n                {\n                    KcpSession session = null;\n\n                    if (sid == 0)\n                    {\n                        //来自Client的第1个包，只能是鉴权包\n                        session = new KcpSession(NewSessionID(), m_listener);\n                        m_mapSession.Add(session.Id, session);\n                    }\n                    else\n                    {\n                        session = m_mapSession[sid];\n                    }\n\n\n                    if (session != null)\n                    {\n                        session.Active(m_socket, remotePoint as IPEndPoint);\n                        session.DoReceiveInGateway(m_RecvBufferTemp, cnt);\n                    }\n                    else\n                    {\n                        this.LogWarning(\"无效的包! sid:{0}\", sid);\n                        //需要返回给客户端，Session无效了,直接返回一个Sid为0的包\n                        //当客户端收到包好，会抛出Session过期事件\n                        //因为正常情况下，客户端收到的Session肯定不为0\n                        m_socket.SendTo(new byte[4], remotePoint);\n                    }\n                }\n            }\n        }\n\n\n\n\n        private void Close()\n        {\n            this.LogWarning(\"\");\n\n            m_IsRunning = false;\n\n            if (m_ThreadRecv != null)\n            {\n                m_ThreadRecv.Interrupt();\n                m_ThreadRecv = null;\n            }\n\n            if (m_socket != null)\n            {\n                try\n                {\n                    m_socket.Shutdown(SocketShutdown.Both);\n\n                }\n                catch (Exception e)\n                {\n                    this.LogWarning(e.Message + e.StackTrace);\n                }\n\n                m_socket.Close();\n                m_socket = null;\n            }\n        }\n\n\n\n        //=================================================================================\n        //接收线程 \n        //=================================================================================\n        private bool m_hasSocketException = false;\n\n        private void Thread_Recv()\n        {\n            Debuger.LogWarning(\"Begin ......\");\n\n            while (m_IsRunning)\n            {\n                try\n                {\n                    DoReceiveInThread();\n\n                    if (m_hasSocketException)\n                    {\n                        m_hasSocketException = false;\n                        Debuger.LogWarning(\"连接异常已经恢复\");\n                    }\n                }\n                catch (SocketException se)\n                {\n                    if (!m_hasSocketException)\n                    {\n                        m_hasSocketException = true;  \n                    }\n                    \n                    Debuger.LogWarning(\"SocketErrorCode:{0}, {1}\", se.SocketErrorCode,se.Message);\n                    Thread.Sleep(1);\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(e.Message + \"\\n\" + e.StackTrace);\n                    Thread.Sleep(1);\n                }\n            }\n\n            Debuger.LogWarning(\"End!\");\n        }\n\n\n\n        private int m_lastClearSessionTime = 0;\n        public void Tick()\n        {\n            if (m_IsRunning)\n            {\n                lock (m_mapSession)\n                {\n                    int current = (int)TimeUtils.GetTotalMillisecondsSince1970();\n\n                    if (current - m_lastClearSessionTime > SessionActiveTimeout * 1000 / 2)\n                    {\n                        m_lastClearSessionTime = current;\n                        ClearNoActiveSession();\n                    }\n\n                    var list = m_mapSession.AsList();\n                    int cnt = list.Count;\n                    for (int i = 0; i < cnt; i++)\n                    {\n                        list[i].Tick(current);\n                    }\n                }\n            }\n        }\n\n        private void ClearNoActiveSession()\n        {\n            var list = m_mapSession.AsList();\n            var dir = m_mapSession.AsDictionary();\n            int cnt = list.Count;\n\n            for (int i = cnt - 1; i >= 0; i--)\n            {\n                var session = list[i];\n                if (!session.IsActived)\n                {\n                    list.RemoveAt(i);\n                    dir.Remove(session.Id);\n                    session.Clean();\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Server/KCPSession.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 基于KCP的可靠UDP会话类（服务器）\n * KCP-based reliable UDP session class (server)\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\nusing SGF.Network.Core;\nusing SGF.Network.General.Proto;\nusing SGF.SEvent;\nusing SGF.Time;\n\n\nnamespace SGF.Network.General.Server\n{\n    public class KcpSession:ISession, ILogTag\n    {\n        public string LOG_TAG { get; protected set; }\n\n        //==========================================================\n        //事件\n        //==========================================================\n        public Signal<ISession, int> onSendError { get; private set; }\n        public Signal<ISession, int> onReceiveError { get; private set; }\n\n        //==========================================================\n        //公共成员变量\n        //==========================================================\n        public uint AuthToken { get; set; }\n        public uint Id { get; protected set; }\n        public IPEndPoint LocalEndPoint { get; private set; }\n        public IPEndPoint RemoteEndPoint { get; private set; }\n        public ushort Ping { get; set; }\n        public bool IsActived { get { return Thread.VolatileRead(ref this.m_actived) == 1; } }\n        private int m_actived = 0;\n\n        //==========================================================\n        //私有成员变量\n        //==========================================================\n        private Socket m_socket;\n        private ISessionListener m_listener;\n\n        private NetBufferWriter m_bufferSend;\n        private Queue<NetMessage> m_queueReceive;\n\n        //KCP\n        private KCP m_Kcp;\n        private SwitchQueue<byte[]> m_RecvBufQueue = new SwitchQueue<byte[]>();\n        private uint m_NextKcpUpdateTime = 0;\n        private bool m_NeedKcpUpdateFlag = false;\n\n\n        public KcpSession(uint sid, ISessionListener listener)\n        {\n            LOG_TAG = \"KcpSession[\" + sid + \"]\";\n            this.Log();\n\n            onSendError = new Signal<ISession, int>();\n            onReceiveError = new Signal<ISession, int>();\n\n            m_bufferSend = new NetBufferWriter(new byte[0]);\n            m_queueReceive = new Queue<NetMessage>();\n\n            this.Id = sid;\n            m_listener = listener;\n\n\n        }\n\n        public string ToString(string prefix = \"\")\n        {\n            return \"KcpSession[\" + Id + \",\" + RemoteEndPoint.Port + \"]\";\n        }\n\n        public virtual void Clean()\n        {\n            this.Log();\n\n            m_socket = null;\n            m_actived = 0;\n        }\n\n        //======================================================================\n        //连接与断开连接相关\n        //======================================================================\n        public void Active(Socket socket, IPEndPoint remoteEndPoint)\n        {\n            RemoteEndPoint = (IPEndPoint)remoteEndPoint;\n\n            if (Interlocked.CompareExchange(ref this.m_actived, 1, 0) == 0)\n            {\n                m_socket = socket;\n\n                LocalEndPoint = (IPEndPoint)socket.LocalEndPoint;\n\n                m_Kcp = new KCP(Id, HandleKcpSend);\n                m_Kcp.NoDelay(1, 10, 2, 1);\n                m_Kcp.WndSize(128, 128);\n            }\n        }\n\n\n        //======================================================================\n        //发送数据\n        //======================================================================\n        public bool Send(NetMessage msg)\n        {\n            this.Log();\n\n            if (!IsActived)\n            {\n                Debuger.LogWarning(\"Session已经不活跃了！\");\n                return false;\n            }\n\n\n            msg.head.sid = Id;\n\n            m_bufferSend.Attach(new byte[msg.Length], 0);\n            msg.Serialize(m_bufferSend);\n\n            var bytes = m_bufferSend.GetBytes();\n            var len = m_bufferSend.Length;\n\n            return m_Kcp.Send(bytes, len) == 0;\n            \n        }\n\n        private void HandleKcpSend(byte[] bytes, int len)\n        {\n            m_socket.SendTo(bytes, 0, len, SocketFlags.None, RemoteEndPoint);\n        }\n\n\n        //======================================================================\n        //接收数据\n        //======================================================================\n\n        public void DoReceiveInGateway(byte[] buffer, int size)\n        {\n            byte[] dst = new byte[size];\n            Buffer.BlockCopy(buffer, 0, dst, 0, size);\n            m_RecvBufQueue.Push(dst);\n        }\n\n        private void DoReceiveInMain()\n        {\n            m_RecvBufQueue.Switch();\n\n            while (!m_RecvBufQueue.Empty())\n            {\n                var recvBufferRaw = m_RecvBufQueue.Pop();\n                int ret = m_Kcp.Input(recvBufferRaw, recvBufferRaw.Length);\n\n                //收到的不是一个正确的KCP包\n                if (ret < 0)\n                {\n                    Debuger.LogError(\"收到不正确的KCP包!Ret:{0}\", ret);\n                    return;\n                }\n\n                m_NeedKcpUpdateFlag = true;\n\n                for (int size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize())\n                {\n                    var recvBuffer = new byte[size];\n                    if (m_Kcp.Recv(recvBuffer) > 0)\n                    {\n                        NetMessage msg = new NetMessage();\n                        msg.Deserialize(recvBuffer, size);\n\n                        m_listener.OnReceive(this, msg);\n                    }\n                }\n\n            }\n        }\n\n\n        public void Tick(int currentTimeMS)\n        {\n            DoReceiveInMain();\n\n            uint current = (uint)currentTimeMS;\n\n            if (m_NeedKcpUpdateFlag || current >= m_NextKcpUpdateTime)\n            {\n                m_Kcp.Update(current);\n                m_NextKcpUpdateTime = m_Kcp.Check(current);\n                m_NeedKcpUpdateFlag = false;\n            }\n        }\n\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Server/NetManager.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 网络模块管理器（服务器）\n * Network Module Manager (Server)\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Reflection;\nusing System.Text;\nusing SGF.Codec;\nusing SGF.Network.Core.RPCLite;\nusing SGF.Network.General.Proto;\nusing SGF.SEvent;\nusing SGF.Utils;\n\n\nnamespace SGF.Network.General.Server\n{\n    public class NetManager : ISessionListener\n    {\n        public Signal<ISession> onDisconnected { get; private set; }\n        private IGateway m_gateway;\n        private uint m_authCmd = 0;\n        private RPCManager m_rpc;\n\n        public void Init(ConnectionType connType, int port)\n        {\n            Debuger.Log(\"connType:{0}, port:{1}\", connType, port);\n\n            if (connType == ConnectionType.TCP)\n            {\n                m_gateway = new TcpGateway(port, this);\n            }\n            else if (connType == ConnectionType.UDP)\n            {\n                m_gateway = new UdpGateway(port, this);\n            }\n            else if (connType == ConnectionType.RUDP)\n            {\n                m_gateway = new KcpGateway(port, this);\n            }\n            else\n            {\n                throw new ArgumentException(\"未实现该连接类型：\" + connType);\n            }\n\n            onDisconnected = new Signal<ISession>();\n\n            m_rpc = new RPCManager();\n            m_rpc.Init();\n        }\n\n        public RPCManager Rpc { get { return m_rpc; } }\n\n        public void Clean()\n        {\n            Debuger.Log();\n            if (m_gateway != null)\n            {\n                m_gateway.Clean();\n                m_gateway = null;\n            }\n\n            if (m_rpc != null)\n            {\n                m_rpc.Clean();\n                m_rpc = null;\n            }\n\n\n            m_listMsgListener.Clear();\n            onDisconnected.RemoveAllListeners();\n        }\n\n\n        public void Dump()\n        {\n            m_gateway.Dump();\n\n            StringBuilder sb = new StringBuilder();\n\n            foreach (var pair in m_listMsgListener)\n            {\n                ListenerHelper helper = pair.Value;\n                sb.AppendFormat(\"\\t<cmd:{0}, msg:{1}, \\tlistener:{2}.{3}>\\n\", pair.Key, helper.TMsg.Name,\n                    helper.onMsgMethod.DeclaringType.Name, helper.onMsgMethod.Name);\n            }\n\n            Debuger.LogWarning(\"\\nNet Listeners ({0}):\\n{1}\", m_listMsgListener.Count, sb);\n\n            m_rpc.Dump();\n        }\n\n\n        public void SetAuthCmd(uint cmd)\n        {\n            m_authCmd = cmd;\n        }\n\n\n        public void Tick()\n        {\n            m_gateway.Tick();\n        }\n\n\n\n        public void OnReceive(ISession session, NetMessage msg)\n        {\n            if (session.AuthToken == msg.head.token)\n            {\n                if (msg.head.cmd == 0)\n                {\n                    RPCMessage rpcmsg = PBSerializer.NDeserialize<RPCMessage>(msg.content);\n                    m_rpc.OnReceive(session, rpcmsg);\n                }\n                else\n                {\n                    HandlePBMessage(session, msg);\n                }\n            }\n            else\n            {\n                Debuger.LogWarning(\"收到消息的Token与Session的Token不一致！session.token:{0}, msg.token:{1}\", session.AuthToken, msg.head.token);\n\n                if (m_authCmd == 0 || msg.head.cmd == m_authCmd)\n                {\n                    HandlePBMessage(session, msg);\n                }\n                else\n                {\n                    Debuger.LogWarning(\"收到未鉴权的消息! cmd:{0}\", msg.head.cmd);\n                }\n            }\n            \n        }\n\n        public void OnDisconnected(ISession session)\n        {\n            onDisconnected.Invoke(session);\n        }\n\n\n        //========================================================================\n        //传统的协议处理方式\n        //========================================================================\n\n        class ListenerHelper\n        {\n            public Type TMsg;\n            public Delegate onMsg0;\n            public Delegate onMsg1;\n\n            public MethodInfo onMsgMethod\n            {\n                get\n                {\n                    var onMsg = onMsg0 != null ? onMsg0 : (onMsg1 != null ? onMsg1 : null);\n                    return onMsg.Method;\n                }\n            }\n        }\n\n        private DictionarySafe<uint, ListenerHelper> m_listMsgListener = new DictionarySafe<uint, ListenerHelper>();\n\n        private void HandlePBMessage(ISession session, NetMessage msg)\n        {\n            Debuger.LogVerbose(\"msg.head:{0}\", msg.head);\n\n            var helper = m_listMsgListener[msg.head.cmd];\n            if (helper != null)\n            {\n                object obj = null;\n\n                try\n                {\n                    obj = PBSerializer.NDeserialize(msg.content, helper.TMsg);\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogError(\"MsgName:{0}, msg.head:{0}\", helper.TMsg.Name, msg.head);\n                    Debuger.LogError(\"DeserializeError:\" + e.Message);\n                }\n\n                if (obj != null)\n                {\n                    try\n                    {\n                        if (helper.onMsg0 != null)\n                        {\n                            helper.onMsg0.DynamicInvoke(session, msg.head.index, obj);\n                        }\n                        else if (helper.onMsg1 != null)\n                        {\n                            helper.onMsg1.DynamicInvoke(session, msg.head, obj);\n                        }\n                    }\n                    catch (Exception e)\n                    {\n                        Debuger.LogError(\"MsgName:{0}, msg.head:{0}\", helper.TMsg.Name, msg.head);\n                        Debuger.LogError(\"BusinessError:\" + e.Message + \"\\n\" + e.StackTrace);\n                    }\n                }\n            }\n            else\n            {\n                Debuger.LogWarning(\"未找到对应的监听者! cmd:{0}\", msg.head.cmd);\n            }\n        }\n\n\n        public void Send<TMsg>(ISession session, ProtocolHead head, uint cmd, TMsg msg)\n        {\n            Debuger.LogVerbose(\"index:{0}, cmd:{1}\", head.index, cmd);\n\n            NetMessage msgobj = new NetMessage();\n            msgobj.head = head;\n            msgobj.head.cmd = cmd;\n            msgobj.head.token = session.AuthToken;\n            msgobj.content = PBSerializer.NSerialize(msg);\n            msgobj.head.dataSize = (uint)msgobj.content.Length;\n\n            session.Send(msgobj);\n        }\n\n        public void AddListener<TMsg>(uint cmd, Action<ISession, uint, TMsg> onMsg)\n        {\n            Debuger.Log(\"cmd:{0}, listener:{1}.{2}\", cmd, onMsg.Method.DeclaringType.Name, onMsg.Method.Name);\n\n            ListenerHelper helper = new ListenerHelper()\n            {\n                TMsg = typeof(TMsg),\n                onMsg0 = onMsg\n            };\n\n            m_listMsgListener.Add(cmd, helper);\n        }\n\n        public void AddListener<TMsg>(uint cmd, Action<ISession, ProtocolHead, TMsg> onMsg)\n        {\n            Debuger.Log(\"cmd:{0}, listener:{1}.{2}\", cmd, onMsg.Method.DeclaringType.Name, onMsg.Method.Name);\n\n            ListenerHelper helper = new ListenerHelper()\n            {\n                TMsg = typeof(TMsg),\n                onMsg1 = onMsg\n            };\n\n            m_listMsgListener.Add(cmd, helper);\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Server/RPCManager.cs",
    "content": "﻿using SGF.Codec;\nusing SGF.Extension;\nusing SGF.Network.Core.RPCLite;\nusing SGF.Network.General.Proto;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\n\nnamespace SGF.Network.General.Server\n{\n    public class RPCManager:RPCManagerBase\n    {\n\n\n        public void OnReceive(ISession session, RPCMessage msg)\n        {\n            HandleRPCMessage(session, msg);\n        }\n\n\n        //========================================================================\n        //RPC的协议处理方式\n        //========================================================================\n        private ISession m_currInvokingSession;\n        private string m_currInvokingName;\n\n        public void HandleRPCMessage(ISession session, RPCMessage rpcmsg)\n        {\n            RPCMethodHelper helper = GetMethodHelper(rpcmsg.name);\n            if (helper != null)\n            {\n                object[] args = new object[rpcmsg.raw_args.Count + 1];\n                var raw_args = rpcmsg.raw_args;\n                var paramInfo = helper.method.GetParameters();\n\n                args[0] = session;\n\n                if (args.Length == paramInfo.Length)\n                {\n                    for (int i = 0; i < raw_args.Count; i++)\n                    {\n                        if (raw_args[i].type == RPCArgType.PBObject)\n                        {\n                            args[i + 1] = PBSerializer.NDeserialize(raw_args[i].raw_value, paramInfo[i + 1].ParameterType);\n                        }\n                        else\n                        {\n                            args[i + 1] = raw_args[i].value;\n                        }\n                    }\n\n                    m_currInvokingName = rpcmsg.name;\n                    m_currInvokingSession = session;\n\n                    try\n                    {\n                        helper.method.Invoke(helper.listener, BindingFlags.NonPublic, null, args, null);\n                    }\n                    catch (Exception e)\n                    {\n                        Debuger.LogError(\"RPC调用出错：{0}\\n{1}\", e.Message, e.StackTrace);\n                    }\n                    m_currInvokingName = null;\n                    m_currInvokingSession = null;\n                }\n                else\n                {\n                    Debuger.LogWarning(\"参数数量不一致:{0},{1}<->{2}\", rpcmsg.name, args.Length, paramInfo.Length);\n                }\n\n            }\n            else\n            {\n                Debuger.LogWarning(\"RPC不存在:{0}\", rpcmsg.name);\n            }\n        }\n\n\n        public void Return(params object[] args)\n        {\n            var name = \"On\" + m_currInvokingName;\n\n\n            RPCMessage rpcmsg = new RPCMessage();\n            rpcmsg.name = name;\n            rpcmsg.args = args;\n            byte[] buffer = PBSerializer.NSerialize(rpcmsg);\n\n            NetMessage msg = new NetMessage();\n            msg.head = new ProtocolHead();\n            msg.head.dataSize = (uint)buffer.Length;\n            msg.content = buffer;\n            \n            m_currInvokingSession.Send(msg);\n        }\n\n\n        public void ReturnError(params object[] args)\n        {\n            var name = \"On\" + m_currInvokingName + \"Error\";\n\n\n            RPCMessage rpcmsg = new RPCMessage();\n            rpcmsg.name = name;\n            rpcmsg.args = args;\n            byte[] buffer = PBSerializer.NSerialize(rpcmsg);\n\n            NetMessage msg = new NetMessage();\n            msg.head = new ProtocolHead();\n            msg.head.dataSize = (uint)buffer.Length;\n            msg.content = buffer;\n\n            m_currInvokingSession.Send(msg);\n        }\n\n\n        public void Invoke(ISession session, string name, params object[] args)\n        {\n            Debuger.LogVerbose(\"->Session[{0}] {1}({2})\", session.Id, name, args.ToListString());\n\n            RPCMessage rpcmsg = new RPCMessage();\n            rpcmsg.name = name;\n            rpcmsg.args = args;\n            byte[] buffer = PBSerializer.NSerialize(rpcmsg);\n\n            NetMessage msg = new NetMessage();\n            msg.head = new ProtocolHead();\n            msg.head.dataSize = (uint)buffer.Length;\n            msg.content = buffer;\n            \n            session.Send(msg);\n        }\n\n\n\n        public void Invoke(ISession[] listSession, string name, params object[] args)\n        {\n            Debuger.Log(\"->Session<Cnt={0}> {1}({2})\", listSession.Length, name, args.ToListString());\n\n            RPCMessage rpcmsg = new RPCMessage();\n            rpcmsg.name = name;\n            rpcmsg.args = args;\n            byte[] buffer = PBSerializer.NSerialize(rpcmsg);\n\n            NetMessage msg = new NetMessage();\n            msg.head = new ProtocolHead();\n            msg.head.dataSize = (uint)buffer.Length;\n            msg.content = buffer;\n            \n            for (int i = 0; i < listSession.Length; i++)\n            {\n                listSession[i].Send(msg);\n            }\n        }\n\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/Network/General/Server/TcpGateway.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\nusing SGF.Network.Core;\nusing SGF.Utils;\n\n\nnamespace SGF.Network.General.Server\n{\n    public class TcpGateway:IGateway\n    {\n        public static int SessionActiveTimeout = 5;\n        private MapList<long, TcpSession> m_mapSession;\n        private bool m_IsRunning = false;\n        private ISessionListener m_listener;\n        private int m_port;\n        private bool m_waitReStart = false;\n\n        \n        private const int BACKLOG = 500;\n        private Socket m_socket = null;\n        private readonly SocketAsyncEventArgs m_saeAccept = null;\n\n        private SocketAsyncEventArgsPool m_saePool;\n\n        public TcpGateway(int port, ISessionListener listener)\n        {\n            Debuger.Log(\"port:{0}\", port);\n\n            m_saePool = new SocketAsyncEventArgsPool(NetDefine.PacketBufferSize, 10000);\n            m_saeAccept = new SocketAsyncEventArgs();\n            m_saeAccept.Completed += OnAcceptCompleted;\n            \n            m_port = port;\n            m_listener = listener;\n\n            m_mapSession = new MapList<long, TcpSession>();\n\n            Start();\n        }\n\n        public void Clean()\n        {\n            Debuger.Log();\n            m_mapSession.Clear();\n            Close();\n        }\n\n        public void Dump()\n        {\n            StringBuilder sb = new StringBuilder();\n\n            var dic = m_mapSession.AsDictionary();\n            var i = 0;\n            foreach (var pair in dic)\n            {\n                i++;\n                ISession session = pair.Value;\n                sb.AppendLine(\"\\t\" + i  + \".\"+ session.ToString());\n            }\n\n            Debuger.LogWarning(\"\\nGateway Sessions ({0}):\\n{1}\", m_mapSession.Count, sb);\n\n        }\n\n        private static long m_lastSessionId = 0;\n        private uint NewSessionID()\n        {\n            return (uint)Interlocked.Increment(ref m_lastSessionId);\n        }\n\n\n        public void Start()\n        {\n            Debuger.LogWarning(\"\");\n\n            m_waitReStart = false;\n            m_IsRunning = true;\n\n            if (m_socket == null)\n            {\n                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n                m_socket.Bind(new IPEndPoint(IPAddress.Any, m_port));\n                m_socket.Listen(BACKLOG);\n\n                AcceptAsync();\n            }\n        }\n\n        private void AcceptAsync()\n        {\n            if (m_socket == null)\n            {\n                return;\n            }\n\n            bool result = true;\n            try { result = m_socket.AcceptAsync(m_saeAccept); }\n            catch (Exception ex) { Debuger.LogError(ex.Message); }\n\n            if (!result) System.Threading.ThreadPool.QueueUserWorkItem(_ => OnAcceptCompleted(this, m_saeAccept));\n        }\n\n        private void OnAcceptCompleted(object sender, SocketAsyncEventArgs e)\n        {\n            Socket acceptSocket = null;\n            if (e.SocketError == SocketError.Success)\n            {\n                acceptSocket = e.AcceptSocket;\n            }\n            e.AcceptSocket = null;\n\n            if (acceptSocket != null)\n            {\n                var sid = NewSessionID();\n                var session = new TcpSession(sid, m_saePool, m_listener);\n                session.Active(acceptSocket);\n\n                lock (m_mapSession)\n                {\n                    m_mapSession.Add(session.Id, session);\n                }\n                \n            }\n\n            this.AcceptAsync();\n        }\n\n        \n\n        private void Close()\n        {\n            Debuger.LogWarning(\"\");\n\n            m_IsRunning = false;\n\n            if (m_socket != null)\n            {\n                try\n                {\n                    m_socket.Shutdown(SocketShutdown.Both);\n\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(e.Message + e.StackTrace);\n                }\n\n                m_socket.Close();\n                m_socket = null;\n            }\n        }\n\n        private void ReStart()\n        {\n            Debuger.LogWarning(\"\");\n            Close();\n            m_waitReStart = true;\n        }\n\n        public ISession GetSession(long sid)\n        {\n            ISession session = null;\n            lock (m_mapSession)\n            {\n                session = m_mapSession[sid];\n            }\n            return session;\n        }\n\n\n        //=================================================================================\n        //检查超时 \n        //=================================================================================\n\n        private int m_lastClearSessionTime = 0;\n        public void Tick()\n        {\n            if (m_IsRunning)\n            {\n                lock (m_mapSession)\n                {\n                    int current = (int)TimeUtils.GetTotalMillisecondsSince1970();\n\n                    if (current - m_lastClearSessionTime > SessionActiveTimeout * 1000 / 2)\n                    {\n                        m_lastClearSessionTime = current;\n                        ClearNoActiveSession();\n                    }\n\n                    var list = m_mapSession.AsList();\n                    int cnt = list.Count;\n                    for (int i = 0; i < cnt; i++)\n                    {\n                        list[i].Tick(current);\n                    }\n                }\n            }\n            else\n            {\n                if (m_waitReStart)\n                {\n                    Start();\n                }\n            }\n        }\n\n        private void ClearNoActiveSession()\n        {\n            var list = m_mapSession.AsList();\n            var dir = m_mapSession.AsDictionary();\n            int cnt = list.Count;\n\n            for (int i = cnt - 1; i >= 0; i--)\n            {\n                var session = list[i];\n                if (!session.IsActived)\n                {\n                    list.RemoveAt(i);\n                    dir.Remove(session.Id);\n                    session.Clean();\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Server/TcpSession.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing SGF.Network.Core;\nusing SGF.SEvent;\n\nnamespace SGF.Network.General.Server\n{\n    public class TcpSession:TcpConnectionBase, ISession\n    {\n        //==========================================================\n        //事件\n        //==========================================================\n\n        public Signal<ISession> onDisconnected { get; private set; }\n        public Signal<ISession, int> onSendError { get; private set; }\n        public Signal<ISession> onSendSuccess { get; private set; }\n        public Signal<ISession, int> onReceiveError { get; private set; }\n\n        //==========================================================\n        //公共成员变量\n        //==========================================================\n        public uint AuthToken { get; set; }\n\n        //==========================================================\n        //私有成员变量\n        //==========================================================\n        private ISessionListener m_listener;\n\n        public TcpSession(uint sid, SocketAsyncEventArgsPool pool, ISessionListener listener):base(pool)\n        {\n            LOG_TAG = \"TcpSession[\" + sid + \"]\";\n\n            this.Log();\n\n            onDisconnected = new Signal<ISession>();\n            onSendSuccess = new Signal<ISession>();\n            onSendError = new Signal<ISession, int>();\n            onReceiveError = new Signal<ISession, int>();\n            \n            this.Id = sid;\n            m_listener = listener;\n        }\n\n        public override string ToString()\n        {\n            return \"TcpSession[\" + Id + \",\" + RemoteEndPoint.Port + \"]\";\n        }\n\n\n        //======================================================================\n        //断开连接相关\n        //======================================================================\n        protected override void OnDisconnected()\n        {\n            base.OnDisconnected();\n            m_listener.OnDisconnected(this);\n            onDisconnected.Invoke(this);\n        }\n\n\n        //======================================================================\n        //发送数据\n        //======================================================================\n        protected override void OnSendError(int errcode, string info)\n        {\n\n            this.LogWarning(\"{0}:{1}\", errcode, info);\n            onSendError.Invoke(this, errcode);\n        }\n\n        protected override void OnSendSuccess()\n        {\n            onSendSuccess.Invoke(this);\n        }\n\n\n\n        //======================================================================\n        //接收数据\n        //======================================================================\n        protected override void OnReceiveError(int errcode, string info)\n        {\n            this.LogWarning(\"{0}:{1}\", errcode, info);\n            onReceiveError.Invoke(this, errcode);\n        }\n\n\n\n\n        public void Tick(int currentMS)\n        {\n            var msg = base.Receive();\n            while (msg != null)\n            {\n                m_listener.OnReceive(this, msg);\n                msg = base.Receive();\n            }\n        }\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Server/UdpGateway.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 网关类（服务器）\n * Gateway class (Server)\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\nusing SGF.Network.Core;\nusing SGF.Network.General.Proto;\nusing SGF.Utils;\n\nnamespace SGF.Network.General.Server\n{\n    public class UdpGateway:IGateway,ILogTag\n    {\n        public string LOG_TAG { get; protected set; }\n        public IPEndPoint LocalEndPoint { get; private set; }\n        public static int SessionActiveTimeout = 5;\n        private MapList<uint, UdpSession> m_mapSession;\n        private bool m_IsRunning = false;\n        private ISessionListener m_listener;\n        private int m_port;\n\n        private Socket m_socket = null;\n        private SocketAsyncEventArgs m_saeReceive = null;\n        private NetBufferWriter m_bufferReceive = null;\n        private SocketAsyncEventArgsPool m_pool;\n\n        public UdpGateway(int port, ISessionListener listener)\n        {\n            LOG_TAG = \"UdpGateway<\" + port + \">\";\n            this.Log(\"port:{0}\", port);\n\n            m_bufferReceive = new NetBufferWriter();\n            m_pool = new SocketAsyncEventArgsPool(NetDefine.PacketBufferSize, 10000);\n\n            m_port = port;\n            m_listener = listener;\n\n            m_mapSession = new MapList<uint, UdpSession>();\n\n            Start();\n        }\n\n        public void Clean()\n        {\n            this.Log();\n            m_mapSession.Clear();\n            Close();\n        }\n\n        private void CleanReceive()\n        {\n            this.Log();\n\n            if (m_saeReceive != null)\n            {\n                m_saeReceive.Completed -= OnReceiveCompleted;\n                m_pool.Release(m_saeReceive);\n                m_saeReceive = null;\n            }\n        }\n\n        public void Dump()\n        {\n            StringBuilder sb = new StringBuilder();\n\n            var dic = m_mapSession.AsDictionary();\n            var i = 0;\n            foreach (var pair in dic)\n            {\n                i++;\n                ISession session = pair.Value;\n                sb.AppendLine(\"\\t\" + i + \".\" + session.ToString());\n            }\n\n            Debuger.LogWarning(\"\\nGateway Sessions ({0}):\\n{1}\", m_mapSession.Count, sb);\n\n        }\n\n\n        private static long m_lastSessionId = 0;\n        private uint NewSessionID()\n        {\n            return (uint)Interlocked.Increment(ref m_lastSessionId);\n        }\n\n        public void Start()\n        {\n            this.LogWarning(\"\");\n\n            m_IsRunning = true;\n\n            if (m_socket == null)\n            {\n                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\n                m_socket.Bind(new IPEndPoint(IPAddress.Any, m_port));\n                LocalEndPoint = m_socket.LocalEndPoint as IPEndPoint;\n                m_port = LocalEndPoint.Port; ;\n\n                m_saeReceive = m_pool.Acquire();\n                m_saeReceive.Completed += OnReceiveCompleted;\n                m_saeReceive.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);\n\n                ReceiveAsync();\n            }\n        }\n\n        private void ReceiveAsync()\n        {\n            if (m_socket == null)\n            {\n                return;\n            }\n\n            bool result = true;\n            try { result = m_socket.ReceiveFromAsync(m_saeReceive); }\n            catch (Exception ex) { Debuger.LogError(ex.Message); }\n\n            if (!result)\n            {\n                System.Threading.ThreadPool.QueueUserWorkItem(_ => OnReceiveCompleted(this, m_saeReceive));\n            }\n        }\n\n        private void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)\n        {\n            this.Log(e.SocketError.ToString());\n\n            if (e.SocketError != SocketError.Success)\n            {\n                this.LogWarning(e.SocketError.ToString());\n            }\n            else\n            {\n                if (e.BytesTransferred == 0)\n                {\n                    this.LogWarning(\"收到的数据长度为0\");\n                }\n                else\n                {\n                    m_bufferReceive.Attach(e.Buffer, e.BytesTransferred);\n                    NetMessage msg = new NetMessage();\n                    if (msg.Deserialize(m_bufferReceive))\n                    {\n                        lock (m_mapSession)\n                        {\n                            UdpSession session = null;\n\n                            if (msg.head.sid == 0)\n                            {\n                                session = new UdpSession(NewSessionID(), m_pool, m_listener);\n                                m_mapSession.Add(session.Id, session);\n                            }\n                            else\n                            {\n                                session = m_mapSession[msg.head.sid];\n                                if (session == null)\n                                {\n                                    //对于UDP，可以重新分配SessionId\n                                    session = new UdpSession(NewSessionID(), m_pool, m_listener);\n                                    m_mapSession.Add(session.Id, session);\n                                }\n                            }\n\n\n                            if (session != null)\n                            {\n                                session.Active(m_socket, (IPEndPoint)e.RemoteEndPoint);\n                                session.DoReceiveInGateway(msg);\n                            }\n                            else\n                            {\n                                this.LogWarning(\"无效的包! sid:{0}\", msg.head.sid);\n                                //需要返回给客户端，Session无效了\n                                UdpSession.ReturnErrorMessage(m_socket, (IPEndPoint) e.RemoteEndPoint,\n                                    NetErrorCode.SessionExpire, \"Session Expired!\");\n                            }\n                        }\n\n                    }\n                    else\n                    {\n                        this.LogError(\"反序列化失败！\");\n                    }\n                    \n                }\n            }\n            \n            this.ReceiveAsync();\n        }\n\n\n\n        private void Close()\n        {\n            this.LogWarning(\"\");\n\n            m_IsRunning = false;\n\n            if (m_socket != null)\n            {\n                try\n                {\n                    m_socket.Shutdown(SocketShutdown.Both);\n\n                }\n                catch (Exception e)\n                {\n                    this.LogWarning(e.Message + e.StackTrace);\n                }\n\n                m_socket.Close();\n                m_socket = null;\n            }\n\n            CleanReceive();\n        }\n\n\n        //=================================================================================\n        //检查超时 \n        //=================================================================================\n\n        private int m_lastClearSessionTime = 0;\n        public void Tick()\n        {\n            if (m_IsRunning)\n            {\n                lock (m_mapSession)\n                {\n                    int current = (int)TimeUtils.GetTotalMillisecondsSince1970();\n\n                    if (current - m_lastClearSessionTime > SessionActiveTimeout * 1000 / 2)\n                    {\n                        m_lastClearSessionTime = current;\n                        ClearNoActiveSession();\n                    }\n\n                    var list = m_mapSession.AsList();\n                    int cnt = list.Count;\n                    for (int i = 0; i < cnt; i++)\n                    {\n                        list[i].Tick(current);\n                    }\n                }\n            }\n        }\n\n        private void ClearNoActiveSession()\n        {\n            var list = m_mapSession.AsList();\n            var dir = m_mapSession.AsDictionary();\n            int cnt = list.Count;\n\n            for (int i = cnt - 1; i >= 0; i--)\n            {\n                var session = list[i];\n                if (!session.IsActived)\n                {\n                    list.RemoveAt(i);\n                    dir.Remove(session.Id);\n                    session.Clean();\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/Server/UdpSession.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading;\nusing SGF.Codec;\nusing SGF.Network.Core;\nusing SGF.Network.General.Proto;\nusing SGF.SEvent;\n\nnamespace SGF.Network.General.Server\n{\n    public class UdpSession:ISession, ILogTag\n    {\n\n        public string LOG_TAG { get; protected set; }\n\n        //==========================================================\n        //事件\n        //==========================================================\n        public Signal<ISession, int> onSendError { get; private set; }\n        public Signal<ISession, int> onReceiveError { get; private set; }\n\n        //==========================================================\n        //公共成员变量\n        //==========================================================\n        public uint AuthToken { get; set; }\n        public uint Id { get; protected set; }\n        public IPEndPoint LocalEndPoint { get; private set; }\n        public IPEndPoint RemoteEndPoint { get; private set; }\n        public ushort Ping { get; set; }\n        public bool IsActived{get { return Thread.VolatileRead(ref this.m_actived) == 1; }}\n        private int m_actived = 0;\n\n\n        //==========================================================\n        //私有成员变量\n        //==========================================================\n        private Socket m_socket;\n        private SocketAsyncEventArgsPool m_pool;\n        private ISessionListener m_listener;\n\n        //发送相关\n        private SocketAsyncEventArgs m_saeSend = null;\n        private NetPacket m_currSendingPacket = null;\n        private Queue<NetPacket> m_queueSend;\n        private NetBufferWriter m_bufferSend;\n        private int m_sending = 0;\n\n        //接收相关\n        private Queue<NetMessage> m_queueReceive;\n\n\n        public UdpSession(uint sid, SocketAsyncEventArgsPool pool, ISessionListener listener)\n        {\n            LOG_TAG = \"UdpSession[\" + sid + \"]\";\n            this.Log();\n\n            onSendError = new Signal<ISession, int>();\n            onReceiveError = new Signal<ISession, int>();\n\n            m_pool = pool;\n\n            m_queueSend = new Queue<NetPacket>();\n            m_bufferSend = new NetBufferWriter(new byte[0]);\n            \n            m_queueReceive = new Queue<NetMessage>();\n\n            this.Id = sid;\n            m_listener = listener;\n        }\n\n        public override string ToString()\n        {\n            return \"UdpSession[\" + Id + \",\" + RemoteEndPoint.Port + \"]\";\n        }\n\n        public virtual void Clean()\n        {\n            this.Log();\n\n            m_socket = null;\n            m_actived = 0;\n\n            CleanSend();\n        }\n\n        private void CleanSend()\n        {\n            this.Log();\n\n            m_currSendingPacket = null;\n\n            if (m_saeSend != null)\n            {\n                m_saeSend.Completed -= OnSendCompleted;\n                m_pool.Release(m_saeSend);\n                m_saeSend = null;\n            }\n        }\n\n        //======================================================================\n        //连接与断开连接相关\n        //======================================================================\n        public void Active(Socket socket, IPEndPoint remoteEndPoint)\n        {\n            RemoteEndPoint = (IPEndPoint)remoteEndPoint;\n\n            if (Interlocked.CompareExchange(ref this.m_actived, 1, 0) == 0)\n            {\n                m_socket = socket;\n\n                LocalEndPoint = (IPEndPoint)socket.LocalEndPoint;\n\n                m_saeSend = m_pool.Acquire();\n                m_saeSend.Completed += OnSendCompleted;\n                m_saeSend.RemoteEndPoint = remoteEndPoint;\n\n                BeginSend();\n            }\n        }\n\n        //======================================================================\n        //发送数据\n        //======================================================================\n\n        public bool Send(NetMessage msg)\n        {\n            this.Log();\n\n            msg.head.sid = Id;\n\n            m_bufferSend.Attach(new byte[msg.Length], 0);\n            msg.Serialize(m_bufferSend);\n\n            NetPacket packet = new NetPacket(m_bufferSend.GetBytes());\n\n            lock (m_queueSend)\n            {\n                m_queueSend.Enqueue(packet);\n            }\n\n            if (m_sending == 0 && m_actived == 1)\n            {\n                if (m_currSendingPacket == null)\n                {\n                    lock (m_queueSend)\n                    {\n                        if (m_queueSend.Count > 0)\n                        {\n                            m_currSendingPacket = m_queueSend.Dequeue();\n                            SendInternal(m_saeSend);\n                        }\n                    }\n                }\n            }\n\n            return true;\n        }\n\n        protected void BeginSend()\n        {\n            TrySendNext();\n        }\n\n        private void TrySendNext()\n        {\n            this.Log();\n\n            if (m_sending == 0)\n            {\n                if (m_currSendingPacket == null)\n                {\n                    lock (m_queueSend)\n                    {\n                        if (m_queueSend.Count > 0)\n                        {\n                            m_currSendingPacket = m_queueSend.Dequeue();\n                            SendInternal(m_saeSend);\n                        }\n                    }\n                }\n            }\n        }\n\n        private void SendInternal(SocketAsyncEventArgs e)\n        {\n            this.Log(e.SocketError.ToString());\n\n            m_sending = 1;\n\n            var packet = m_currSendingPacket;\n\n            var length = Math.Min(packet.Bytes.Length - packet.SentSize, e.Buffer.Length);\n            var result = false;\n            try\n            {\n                Buffer.BlockCopy(packet.Bytes, packet.SentSize, e.Buffer, 0, length);\n                e.SetBuffer(0, length);\n                result = m_socket.SendToAsync(e);\n            }\n            catch (Exception ex)\n            {\n                this.LogWarning(\"发送数据出错：{0}\", ex.Message);\n            }\n\n            if (!result)\n            {\n                ThreadPool.QueueUserWorkItem(_ => OnSendCompleted(this, e));\n            }\n        }\n\n        private void OnSendCompleted(object sender, SocketAsyncEventArgs e)\n        {\n            this.Log(e.SocketError.ToString());\n\n            if (e.SocketError != SocketError.Success)\n            {\n                this.LogWarning(\"发送数据出错：{0}\", e.SocketError);\n                onSendError.Invoke(this, (int)NetErrorCode.UnkownError);\n                return;\n            }\n\n            var packed = m_currSendingPacket;\n            packed.SentSize += e.BytesTransferred;\n\n            //将PackedBufferSize的Buffer发送完\n            if (e.Offset + e.BytesTransferred < e.Count)\n            {\n                var result = true;\n                try\n                {\n                    e.SetBuffer(e.Offset + e.BytesTransferred, e.Count - e.BytesTransferred - e.Offset);\n                    result = m_socket.SendToAsync(e);\n                }\n                catch (Exception ex)\n                {\n                    this.LogWarning(\"发送数据出错：{0}\", ex.Message);\n                }\n\n                if (!result)\n                {\n                    ThreadPool.QueueUserWorkItem(_ => OnSendCompleted(this, e));\n                }\n            }\n            else\n            {\n\n                if (!packed.IsSent)\n                {\n                    //继续发当前Packet的下一个分组\n                    SendInternal(e);\n                }\n                else\n                {\n                    //一个Packet发送完成\n                    m_currSendingPacket = null;\n                    m_sending = 0;\n                    \n                    //继续发下一个Packet\n                    TrySendNext();\n                }\n            }\n        }\n\n\n\n\n\n        //======================================================================\n        //接收数据\n        //======================================================================\n\n        internal void DoReceiveInGateway(NetMessage msg)\n        {\n            lock (m_queueReceive)\n            {\n                m_queueReceive.Enqueue(msg);\n            }\n        }\n\n        public NetMessage Receive()\n        {\n            NetMessage msg = null;\n            lock (m_queueReceive)\n            {\n                if (m_queueReceive.Count > 0)\n                {\n                    msg = m_queueReceive.Dequeue();\n                    return msg;\n                }\n            }\n\n            return null;\n\n        }\n\n        public void Tick(int currentMS)\n        {\n            var msg = Receive();\n            while (msg != null)\n            {\n                m_listener.OnReceive(this, msg);\n                msg = Receive();\n            }\n        }\n\n\n\n        internal static void ReturnErrorMessage(Socket socket, IPEndPoint remoteEndPoint, NetErrorCode errcode, string errinfo = \"\")\n        {\n            NetErrorMessage msg = new NetErrorMessage();\n            msg.code = (int)errcode;\n            msg.info = errinfo;\n\n            NetMessage msgobj = new NetMessage();\n            msgobj.head.index = 0;\n            msgobj.head.cmd = 0;\n            msgobj.head.token = 0;\n            msgobj.head.sid = 0;\n            msgobj.content = PBSerializer.NSerialize(msg);\n            msgobj.head.dataSize = (uint)msgobj.content.Length;\n\n            NetBuffer bufferSend = new NetBuffer(new byte[msgobj.Length]);\n            msgobj.Serialize(bufferSend);\n            socket.SendTo(bufferSend.GetBytes(), remoteEndPoint);\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Network/General/TcpConnectionBase.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading;\nusing SGF.Network.Core;\nusing SGF.Network.General.Proto;\n\n\nnamespace SGF.Network.General\n{\n    public class TcpConnectionBase:ILogTag\n    {\n        public string LOG_TAG { get; protected set; }\n\n\n        //==========================================================\n        //公共成员变量\n        //==========================================================\n        public uint Id { get; protected set; }\n        public IPEndPoint LocalEndPoint { get; private set; }\n        public IPEndPoint RemoteEndPoint { get; private set; }\n        public bool IsActived { get { return Thread.VolatileRead(ref this.m_actived) == 1; } }\n        private int m_actived = 0;\n        public ushort Ping { get; set; }\n\n        //==========================================================\n        //私有成员变量\n        //==========================================================\n        private Socket m_socket;\n        private SocketAsyncEventArgsPool m_pool;\n\n        //发送相关\n        private SocketAsyncEventArgs m_saeSend = null;\n        private NetPacket m_currSendingPacket = null;\n        private Queue<NetPacket> m_queueSend;\n        private NetBufferWriter m_bufferSend;\n        private int m_sending = 0;\n\n        //接收相关\n        private SocketAsyncEventArgs m_saeReceive = null;\n        private Queue<NetMessage> m_queueReceive;\n        private NetBufferWriter m_bufferReceive;\n\n\n        //==========================================================\n        //构造与清理\n        //==========================================================\n        public TcpConnectionBase(SocketAsyncEventArgsPool pool = null)\n        {\n            LOG_TAG = \"TcpConnectionBase\";\n\n            m_pool = pool;\n            if (m_pool == null)\n            {\n                m_pool = new SocketAsyncEventArgsPool(NetDefine.PacketBufferSize, 0);\n            }\n\n            m_queueSend = new Queue<NetPacket>();\n            m_bufferSend = new NetBufferWriter(new byte[0]);\n\n            m_queueReceive = new Queue<NetMessage>();\n            m_bufferReceive = new NetBufferWriter(new byte[NetDefine.ReceiveBufferMinSize]);\n        }\n\n        public virtual void Clean()\n        {\n            this.Log();\n\n            m_actived = 0;\n\n            Close();\n        }\n\n\n        private void CleanSend()\n        {\n            this.Log();\n\n            m_currSendingPacket = null;\n\n            if (m_saeSend != null)\n            {\n                m_saeSend.Completed -= OnSendCompleted;\n                m_pool.Release(m_saeSend);\n                m_saeSend = null;\n            }\n        }\n\n        private void CleanReceive()\n        {\n            this.Log();\n\n            if (m_saeReceive != null)\n            {\n                m_saeReceive.Completed -= OnReceiveCompleted;\n                m_pool.Release(m_saeReceive);\n                m_saeReceive = null;\n            }\n        }\n\n\n        //======================================================================\n        //连接（对于Client和Server，以及UDP和TCP，连接的逻辑不同）与断开连接\n        //======================================================================\n\n        public void Active(Socket socket)\n        {\n            if (m_actived == 0)\n            {\n                m_socket = socket;\n\n                socket.NoDelay = true;\n                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);\n                socket.ReceiveBufferSize = NetDefine.SocketBufferSize;\n                socket.SendBufferSize = NetDefine.SocketBufferSize;\n\n                RemoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;\n                LocalEndPoint = (IPEndPoint)socket.LocalEndPoint;\n\n                m_saeSend = m_pool.Acquire();\n                m_saeSend.Completed += OnSendCompleted;\n\n                m_saeReceive = m_pool.Acquire();\n                m_saeReceive.Completed += OnReceiveCompleted;\n\n                m_actived = 1;\n\n                BeginSend();\n                BeginReceive();\n\n                \n            }\n        }\n        \n\n        public void Close()\n        {\n            this.Log();\n\n            if (m_socket != null)\n            {\n                try { m_socket.Shutdown(SocketShutdown.Both); }\n                catch (Exception ex) { this.LogWarning(ex.Message); }\n\n                m_socket.Close();\n                m_socket = null;\n            }\n\n            CleanSend();\n            CleanReceive();\n\n            if (Interlocked.CompareExchange(ref this.m_actived, 0, 1) == 1)\n            {\n                Disconnect();\n            }\n        }\n\n        private void Disconnect()\n        {\n            this.Log();\n\n            m_actived = 0;\n            m_sending = 0;\n\n            CleanSend();\n            CleanReceive();\n\n            var e = new SocketAsyncEventArgs();\n            e.Completed += OnDisconnectCompleted;\n\n            var result = false;\n            try\n            {\n                m_socket.Shutdown(SocketShutdown.Both);\n                result = m_socket.DisconnectAsync(e);\n            }\n            catch (Exception ex)\n            {\n                //this.LogError(ex.Message);\n            }\n\n            if (!result)\n            {\n                ThreadPool.QueueUserWorkItem(_ => OnDisconnectCompleted(this, e));\n            }\n\n        }\n\n\n        private void OnDisconnectCompleted(object sender, SocketAsyncEventArgs e)\n        {\n            this.Log(e.SocketError.ToString());\n\n            e.Completed -= OnDisconnectCompleted;\n            e.Dispose();\n\n            try { m_socket.Close(); }\n            catch (Exception ex) {  }\n\n            OnDisconnected();\n        }\n\n        protected virtual void OnDisconnected()\n        {\n            \n        }\n\n        //======================================================================\n        //发送数据\n        //======================================================================\n        public bool Send(NetMessage msg)\n        {\n            this.LogVerbose();\n\n            msg.head.sid = Id;\n\n            m_bufferSend.Attach(new byte[msg.Length], 0);\n            msg.Serialize(m_bufferSend);\n\n            NetPacket packet = new NetPacket(m_bufferSend.GetBytes());\n\n            lock (m_queueSend)\n            {\n                m_queueSend.Enqueue(packet);\n            }\n\n            if (m_sending == 0 && m_actived == 1)\n            {\n                lock (m_queueSend)\n                {\n                    if (m_currSendingPacket == null)\n                    {\n\n                        if (m_queueSend.Count > 0)\n                        {\n                            m_currSendingPacket = m_queueSend.Dequeue();\n                            SendInternal(m_saeSend);\n                        }\n\n                    }\n                }\n            }\n\n            return true;\n        }\n\n        protected void BeginSend()\n        {\n            TrySendNext();\n        }\n\n        private void TrySendNext()\n        {\n            this.LogVerbose();\n\n            if (m_sending == 0)\n            {\n                lock (m_queueSend)\n                {\n                    if (m_currSendingPacket == null)\n                    {\n\n                        if (m_queueSend.Count > 0)\n                        {\n                            m_currSendingPacket = m_queueSend.Dequeue();\n                            SendInternal(m_saeSend);\n                        }\n\n                    }\n                }\n            }\n        }\n\n        private void SendInternal(SocketAsyncEventArgs e)\n        {\n            this.LogVerbose(\"{0}\",e.SocketError);\n\n            m_sending = 1;\n\n            var packet = m_currSendingPacket;\n\n            var length = Math.Min(packet.Bytes.Length - packet.SentSize, e.Buffer.Length);\n            var result = false;\n            try\n            {\n                Buffer.BlockCopy(packet.Bytes, packet.SentSize, e.Buffer, 0, length);\n                e.SetBuffer(0, length);\n                result = m_socket.SendAsync(e);\n            }\n            catch (Exception ex)\n            {\n                this.LogError(\"发送数据出错：{0}\", ex.Message);\n            }\n\n            if (!result)\n            {\n                ThreadPool.QueueUserWorkItem(_ => OnSendCompleted(this, e));\n            }\n        }\n\n        private void OnSendCompleted(object sender, SocketAsyncEventArgs e)\n        {\n            this.LogVerbose(e.SocketError.ToString());\n\n            if (e.SocketError != SocketError.Success)\n            {\n                Disconnect();\n                OnSendError((int)NetErrorCode.UnkownError, e.SocketError.ToString());\n                return;\n            }\n\n            var packed = m_currSendingPacket;\n            packed.SentSize += e.BytesTransferred;\n\n            //将PackedBufferSize的Buffer发送完\n            if (e.Offset + e.BytesTransferred < e.Count)\n            {\n                var result = true;\n                try\n                {\n                    e.SetBuffer(e.Offset + e.BytesTransferred, e.Count - e.BytesTransferred - e.Offset);\n                    result = m_socket.SendAsync(e);\n                }\n                catch (Exception ex)\n                {\n                    this.LogError(\"发送数据出错：{0}\", ex.Message);\n                }\n\n                if (!result)\n                {\n                    ThreadPool.QueueUserWorkItem(_ => OnSendCompleted(this, e));\n                }\n            }\n            else\n            {\n\n                if (!packed.IsSent)\n                {\n                    //继续发当前Packet的下一个分组\n                    SendInternal(e);\n                }\n                else\n                {\n                    //一个Packet发送完成\n                    m_currSendingPacket = null;\n                    m_sending = 0;\n                    OnSendSuccess();\n\n                    //继续发下一个Packet\n                    TrySendNext();\n                }\n            }\n        }\n\n        protected virtual void OnSendError(int errcode, string info)\n        {\n            this.LogError(\"{0}:{1}\",errcode, info);\n        }\n\n        protected virtual void OnSendSuccess()\n        {\n            \n        }\n\n\n        //======================================================================\n        //接收数据\n        //======================================================================\n        protected void BeginReceive()\n        {\n            ReceiveInternal();\n        }\n\n        private void ReceiveInternal()\n        {\n            this.LogVerbose();\n\n            bool result = false;\n            try{result = m_socket.ReceiveAsync(m_saeReceive);}\n            catch (Exception ex){this.LogError(\"接收数据出错：{0}\", ex.Message);}\n\n            if (!result)\n            {\n                ThreadPool.QueueUserWorkItem(_ => OnReceiveCompleted(this, m_saeReceive));\n            }\n\n        }\n\n        private void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)\n        {\n            this.LogVerbose(e.SocketError.ToString());\n\n            if (e.SocketError != SocketError.Success)\n            {\n                Disconnect();\n                OnReceiveError((int)NetErrorCode.UnkownError, e.SocketError.ToString());\n                return;\n            }\n\n            if (e.BytesTransferred < 1)\n            {\n                Disconnect();\n                OnReceiveError((int)NetErrorCode.UnkownError, \"收到的字节为0\");\n                return;\n            }\n\n            if (m_bufferReceive.Capacity < m_bufferReceive.Length + e.BytesTransferred)\n            {\n                //扩容\n                m_bufferReceive.AdjustCapacity((m_bufferReceive.Length + e.BytesTransferred) * 2);\n            }\n\n            m_bufferReceive.SetPositionToLength();\n            m_bufferReceive.WriteBytes(e.Buffer, 0, e.BytesTransferred);\n\n            this.LogVerbose(\"Received Length:{0}\", m_bufferReceive.Length);\n\n            while (m_bufferReceive.Length > 0)\n            {\n                m_bufferReceive.Position = 0;\n\n                NetMessage msg = new NetMessage();\n                if (msg.Deserialize(m_bufferReceive))\n                {\n                    m_bufferReceive.Arrangement();\n                    lock (m_queueReceive)\n                    {\n                        m_queueReceive.Enqueue(msg);\n                    }\n                }\n                else\n                {\n                    this.LogVerbose(\"Cannot Deserialize One Message!\");\n                    break;\n                }\n            }\n\n\n            ReceiveInternal();\n        }\n\n        protected virtual void OnReceiveError(int errcode, string info)\n        {\n            this.LogError(\"{0}:{1}\", errcode, info);\n        }\n\n\n        /// <summary>\n        /// 主线程读取数据\n        /// </summary>\n        /// <returns></returns>\n        public NetMessage Receive()\n        {\n            NetMessage msg = null;\n            lock (m_queueReceive)\n            {\n                if(m_queueReceive.Count >0)\n                {\n                    msg = m_queueReceive.Dequeue();\n                    return msg;\n                }\n            }\n\n            return null;\n            \n        }\n\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/Utils/DnsUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * DnsUtils\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Net;\nusing SGF.Utils;\n\nnamespace SGF.Network\n{\n    public class DnsUtils\n    {\n        public const string TAG = \"DnsUtils\";\n\n        public static string[] GetHostByName(string hostNameOrAddress)\n        {\n            IPAddress ipaddr = null;\n            if (IPAddress.TryParse(hostNameOrAddress, out ipaddr))\n            {\n                return new string[1] {ipaddr.ToString()};\n            }\n\n\n\n            IPAddress[] ipAddresses = null;\n\n            try\n            {\n                ipAddresses = Dns.GetHostAddresses(hostNameOrAddress);\n            }\n            catch (Exception)\n            {\n\n            }\n\n            if (ipAddresses != null && ipAddresses.Length > 0)\n            {\n                string[] ipstrs = new string[ipAddresses.Length];\n                for (int i = 0; i < ipAddresses.Length; i++)\n                {\n                    ipstrs[i] = ipAddresses[i].ToString();\n                }\n                return ipstrs;\n            }\n\n            return new string[0];\n        }\n\n\n        public static IPAddress[] GetHostAddresses(string hostNameOrAddress)\n        {\n            string[] ipstrs = GetHostByName(hostNameOrAddress);\n            if (ipstrs == null || ipstrs.Length == 0)\n            {\n                return new IPAddress[0];\n            }\n            List<IPAddress> listIPAddrs = new List<IPAddress>();\n            for (int i = 0; i < ipstrs.Length; i++)\n            {\n                IPAddress ipAddress = null;\n                if (IPAddress.TryParse(ipstrs[i], out ipAddress))\n                {\n                    listIPAddrs.Add(ipAddress);\n                }\n            }\n            return listIPAddrs.ToArray();\n        }\n\n\n\n        public static string[] GetUrlWithIP(string url)\n        {\n            Debuger.Log(TAG, \"GetUrlWithIP() old url=\" + url);\n\n            string head, hostname, port, path;\n            UrlUtils.SplitUrl(url, out head, out hostname, out port, out path);\n\n\n            string[] ipstrs = GetHostByName(hostname);\n            if (ipstrs == null || ipstrs.Length == 0)\n            {\n                Debuger.Log(TAG, \"GetUrlWithIP() domain cannot be parse! new url=\" + url);\n                return new string[1] {url};\n            }\n\n            Debuger.Log(TAG, \"GetUrlWithIP() Can Parse Total \" + ipstrs.Length + \" url!\");\n            string[] urls = new string[ipstrs.Length];\n            for (int i = 0; i < ipstrs.Length; i++)\n            {\n                if (string.IsNullOrEmpty(port))\n                {\n                    urls[i] = head + ipstrs[i] + path;\n                }\n                else\n                {\n                    urls[i] = head + ipstrs[i] + \":\" + port + path;\n                }\n\n                Debuger.Log(TAG, \"GetUrlWithIP() new url[\" + (i + 1) + \"]=\" + urls[i]);\n            }\n\n            return urls;\n        }\n\n\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Network/Utils/IPUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * IPUtils\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading;\n\nnamespace SGF.Network\n{\n    public class IPUtils\n    {\n        public static bool IOS_IPv6_First = true;\n        //===========================================================\n\n        public static readonly IPAddress IP_Broadcast = new IPAddress(0xffffffffL);\n        public static IPEndPoint IPEP_Any = new IPEndPoint(IPAddress.Any, 0);\n        public static IPEndPoint IPEP_IPv6Any = new IPEndPoint(IPAddress.IPv6Any, 0);\n\n        #region 工具函数:IsBroadcast,IsFatalException,GetIPEndPointAny\n        public static bool IsBroadcast(IPAddress ip)\n        {\n            if (ip.AddressFamily == AddressFamily.InterNetworkV6)\n            {\n                return false;\n            }\n\n            return ip.Equals(IP_Broadcast);\n        }\n\n        public static bool IsFatalException(Exception exception)\n        {\n            if (exception == null)\n            {\n                return false;\n            }\n            return (((exception is OutOfMemoryException) ||\n                (exception is StackOverflowException)) ||\n                (exception is ThreadAbortException));\n        }\n\n        public static IPEndPoint GetIPEndPointAny(AddressFamily family, int port)\n        {\n            if (family == AddressFamily.InterNetwork)\n            {\n                if (port == 0)\n                {\n                    return IPEP_Any;\n                }\n\n                return new IPEndPoint(IPAddress.Any, port);\n            }\n            else if (family == AddressFamily.InterNetworkV6)\n            {\n                if (port == 0)\n                {\n                    return IPEP_IPv6Any;\n                }\n\n                return new IPEndPoint(IPAddress.IPv6Any, port);\n            }\n            return null;\n        }\n        #endregion\n\n        #region 工具函数:获取远程主机的地址\n        public static IPEndPoint GetHostEndPoint(string host, int port)\n        {\n            IPAddress address = null;\n            if (IPAddress.TryParse(host, out address))\n            {\n#if TestIPv6\n                Debuger.Log(\"UdpSocket.GetHostEndPoint() TestIPv6: 如果已经是IP了，则封装成IPv6格式\");\n                //已经是一个IP了。在外网下不应该出现IP的情况\n                if (!address.IsIPv6LinkLocal && !address.IsIPv6SiteLocal)\n                {\n                    string tmp = \"64:ff9b::\" + address.ToString();\n                    IPAddress addr_v6 = null;\n                    if (IPAddress.TryParse(tmp, out addr_v6))\n                    {\n                        return new IPEndPoint(addr_v6, port);\n                    }\n                    else\n                    {\n                        Debuger.LogError(\"UdpSocket.GetHostEndPoint() TestIPv6，封装IPv6失败:\" + tmp);\n                    }\n                }\n\n#endif\n                return new IPEndPoint(address, port);\n            }\n            else\n            {\n                //如果不是IP，就当作域名来处理\n                IPAddress[] ips = Dns.GetHostAddresses(host);\n                //如果是IPv6环境，则会返回IPv6的地址，否则会返回IPv4的地址。\n\n                if (Debuger.EnableLog)\n                {\n                    Debuger.Log(\"UdpSocket.GetHostEndPoint() Dns GetHostAddresses:\");\n                    for (int i = 0; i < ips.Length; i++)\n                    {\n                        Debuger.Log(\"[\" + i + \"] \" + ips[i] + \", \" + ips[i].AddressFamily);\n                    }\n                }\n\n\n                List<IPAddress> listIPv4 = new List<IPAddress>();\n                List<IPAddress> listIPv6 = new List<IPAddress>();\n\n                for (int i = 0; i < ips.Length; i++)\n                {\n                    if (ips[i].AddressFamily == AddressFamily.InterNetwork)\n                    {\n                        listIPv4.Add(ips[i]);\n                    }\n                    else\n                    {\n                        listIPv6.Add(ips[i]);\n                    }\n                }\n\n\n#if UNITY_ANDROID\n\n                if (listIPv4.Count > 0)\n                {\n                    return new IPEndPoint(listIPv4[0], port);\n                }\n\n                if (listIPv6.Count > 0)\n                {\n                    return new IPEndPoint(listIPv6[0], port);\n                }\n\n#else\n                //加一个静态变量开关，方便以后用Lua设置\n                if (IOS_IPv6_First)\n                {\n                    //IPv6优先\n                    if (listIPv6.Count > 0)\n                    {\n                        return new IPEndPoint(listIPv6[0], port);\n                    }\n\n                    if (listIPv4.Count > 0)\n                    {\n                        return new IPEndPoint(listIPv4[0], port);\n                    }\n                }\n                else\n                {\n                    //IPv4优先\n                    if (listIPv4.Count > 0)\n                    {\n                        return new IPEndPoint(listIPv4[0], port);\n                    }\n\n                    if (listIPv6.Count > 0)\n                    {\n                        return new IPEndPoint(listIPv6[0], port);\n                    }\n                }\n\n#endif\n\n            }\n\n            return null;\n        }\n        #endregion\n\n\n        public static string SelfIP\n        {\n            get\n            {\n                string hostName = Dns.GetHostName();//本机名   \n                //System.Net.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//会警告GetHostByName()已过期，我运行时且只返回了一个IPv4的地址   \n                IPAddress[] addressList = Dns.GetHostAddresses(\"127.0.0.1\");//会返回所有地址，包括IPv4和IPv6  \n\n                return addressList[0].ToString();\n            }\n        }\n\n        public static string SelfIP2\n        {\n            get\n            {\n                string hostname = Dns.GetHostName();//得到本机名   \n                IPHostEntry localhost = Dns.GetHostEntry(hostname);\n                IPAddress localaddr = localhost.AddressList[0];\n                return localaddr.ToString();\n            }\n\n        }\n\n\n\n        public static Int64 IPStr2Int(string ip)\n        {\n            char[] separator = new char[] { '.' };\n            string[] items = ip.Split(separator);\n            return Int64.Parse(items[0]) << 24\n                   | Int64.Parse(items[1]) << 16\n                   | Int64.Parse(items[2]) << 8\n                   | Int64.Parse(items[3]);\n        }\n\n        public static string IPInt2Str(Int64 ipInt)\n        {\n            StringBuilder sb = new StringBuilder();\n            sb.Append((ipInt >> 24) & 0xFF).Append(\".\");\n            sb.Append((ipInt >> 16) & 0xFF).Append(\".\");\n            sb.Append((ipInt >> 8) & 0xFF).Append(\".\");\n            sb.Append(ipInt & 0xFF);\n            return sb.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFCore/Network/Utils/NetUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * NetUtils\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Net;\nusing System.Net.NetworkInformation;\nusing System.Net.Sockets;\n\nnamespace SGF.Network\n{\n    public class NetUtils\n    {\n        public static bool GetIsNetworkAvailable()\n        {\n            return NetworkInterface.GetIsNetworkAvailable();\n        }\n\n        public static int GetAvaliablePort()\n        {\n            int port = 0;\n            try\n            {\n                var s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\n                s.Bind(new IPEndPoint(IPAddress.Any, 0));\n                port = (s.LocalEndPoint as IPEndPoint).Port;\n                s.Close();\n            }\n            catch (Exception e)\n            {\n            }\n\n            return port;\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// 有关程序集的一般信息由以下\n// 控制。更改这些特性值可修改\n// 与程序集关联的信息。\n[assembly: AssemblyTitle(\"SGFCore\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"HP Inc.\")]\n[assembly: AssemblyProduct(\"SGFCore\")]\n[assembly: AssemblyCopyright(\"Copyright © HP Inc. 2017\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// 将 ComVisible 设置为 false 会使此程序集中的类型\n//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型\n//请将此类型的 ComVisible 特性设置为 true。\n[assembly: ComVisible(false)]\n\n// 如果此项目向 COM 公开，则下列 GUID 用于类型库的 ID\n[assembly: Guid(\"eeb72dfc-0fa5-44de-b75a-586f69377aa6\")]\n\n// 程序集的版本信息由下列四个值组成: \n//\n//      主版本\n//      次版本\n//      生成号\n//      修订号\n//\n// 可以指定所有值，也可以使用以下所示的 \"*\" 预置版本号和修订号\n// 方法是按如下所示使用“*”: :\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "SGFCore/SGFCore.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{EEB72DFC-0FA5-44DE-B75A-586F69377AA6}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>SGF</RootNamespace>\n    <AssemblyName>SGFCore</AssemblyName>\n    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>\n    <TargetFrameworkProfile />\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>..\\Libs\\</OutputPath>\n    <DefineConstants>TRACE;DEBUG;ENABLE_LOG</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>0</WarningLevel>\n    <Prefer32Bit>false</Prefer32Bit>\n    <DocumentationFile>\n    </DocumentationFile>\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>..\\Libs\\</OutputPath>\n    <DefineConstants>TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>0</WarningLevel>\n    <Prefer32Bit>false</Prefer32Bit>\n    <DocumentationFile>\n    </DocumentationFile>\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n  </PropertyGroup>\n  <PropertyGroup>\n    <StartupObject />\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"protobuf-net, Version=2.0.0.668, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\Common\\protobuf-net.dll</HintPath>\n    </Reference>\n    <Reference Include=\"SGFDebuger, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\SGFDebuger.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"Class1.cs\" />\n    <Compile Include=\"Codec\\MiniJSON.cs\" />\n    <Compile Include=\"Codec\\PBSerializer.cs\" />\n    <Compile Include=\"Codec\\SGFEncoding.cs\" />\n    <Compile Include=\"Event\\Signal.cs\" />\n    <Compile Include=\"MvvmLite\\MvvmBinding.cs\" />\n    <Compile Include=\"MvvmLite\\MvvmCommand.cs\" />\n    <Compile Include=\"MvvmLite\\MvvmManager.cs\" />\n    <Compile Include=\"MvvmLite\\MvvmModel.cs\" />\n    <Compile Include=\"MvvmLite\\MvvmViewModel.cs\" />\n    <Compile Include=\"Network\\General\\Client\\RPCManager.cs\" />\n    <Compile Include=\"Network\\General\\Server\\RPCManager.cs\" />\n    <Compile Include=\"Timers\\Timer.cs\" />\n    <Compile Include=\"Utils\\DictionarySafe.cs\" />\n    <Compile Include=\"Extension\\CollectionExtensions.cs\" />\n    <Compile Include=\"Extension\\ObjectExtensions.cs\" />\n    <Compile Include=\"Extension\\StreamExtension.cs\" />\n    <Compile Include=\"Extension\\StringExtensions.cs\" />\n    <Compile Include=\"G3Lite\\IndexTypes.cs\" />\n    <Compile Include=\"G3Lite\\MathUtil.cs\" />\n    <Compile Include=\"G3Lite\\Matrix3.cs\" />\n    <Compile Include=\"G3Lite\\Quaternion.cs\" />\n    <Compile Include=\"G3Lite\\Vector2.cs\" />\n    <Compile Include=\"G3Lite\\Vector3.cs\" />\n    <Compile Include=\"G3Lite\\Vector4.cs\" />\n    <Compile Include=\"IPCWork\\IPCConfig.cs\" />\n    <Compile Include=\"IPCWork\\IPCManager.cs\" />\n    <Compile Include=\"IPCWork\\IPCMessage.cs\" />\n    <Compile Include=\"Marshals\\MarshalArray.cs\" />\n    <Compile Include=\"Marshals\\MarshalList.cs\" />\n    <Compile Include=\"MathLite\\SGFRandom.cs\" />\n    <Compile Include=\"Module\\GeneralModule.cs\" />\n    <Compile Include=\"Module\\IModuleActivator.cs\" />\n    <Compile Include=\"Module\\ModuleBase.cs\" />\n    <Compile Include=\"Module\\ModuleManager.cs\" />\n    <Compile Include=\"Module\\NativeModuleActivator.cs\" />\n    <Compile Include=\"Network\\Core\\KCP\\kcp.cs\" />\n    <Compile Include=\"Network\\Core\\KCP\\KCPSocket.cs\" />\n    <Compile Include=\"Network\\Core\\KCP\\switch_queue.cs\" />\n    <Compile Include=\"Network\\Core\\NetBuffer.cs\" />\n    <Compile Include=\"Network\\Core\\NetErrorCode.cs\" />\n    <Compile Include=\"Network\\Core\\RPCLite\\RPCManagerBase.cs\" />\n    <Compile Include=\"Network\\Core\\RPCLite\\RPCMessage.cs\" />\n    <Compile Include=\"Network\\Core\\SocketAsyncEventArgsPool.cs\" />\n    <Compile Include=\"Network\\Core\\UdpSocket.cs\" />\n    <Compile Include=\"Network\\Debuger\\NetDebuger.cs\" />\n    <Compile Include=\"Network\\Debuger\\NetDebugFile.cs\" />\n    <Compile Include=\"Network\\Debuger\\net_debuger.cs\" />\n    <Compile Include=\"Network\\FSPLite\\Client\\FSPClient.cs\" />\n    <Compile Include=\"Network\\FSPLite\\Client\\FSPFrameController.cs\" />\n    <Compile Include=\"Network\\FSPLite\\Client\\FSPManager.cs\" />\n    <Compile Include=\"Network\\FSPLite\\FSPBasicCmd.cs\" />\n    <Compile Include=\"Network\\FSPLite\\FSPGameEndReason.cs\" />\n    <Compile Include=\"Network\\FSPLite\\FSPGameState.cs\" />\n    <Compile Include=\"Network\\FSPLite\\FSPLiteData.cs\" />\n    <Compile Include=\"Network\\FSPLite\\Server\\FSPGame.cs\" />\n    <Compile Include=\"Network\\FSPLite\\Server\\FSPGateway.cs\" />\n    <Compile Include=\"Network\\FSPLite\\Server\\FSPManager.cs\" />\n    <Compile Include=\"Network\\FSPLite\\Server\\FSPPlayer.cs\" />\n    <Compile Include=\"Network\\FSPLite\\Server\\FSPSession.cs\" />\n    <Compile Include=\"Network\\General\\Client\\IConnection.cs\" />\n    <Compile Include=\"Network\\General\\Client\\KcpConnection.cs\" />\n    <Compile Include=\"Network\\General\\Client\\NetManager.cs\" />\n    <Compile Include=\"Network\\General\\Client\\TcpConnection.cs\" />\n    <Compile Include=\"Network\\General\\Client\\UdpConnection.cs\" />\n    <Compile Include=\"Network\\General\\ConnectionType.cs\" />\n    <Compile Include=\"Network\\General\\NetDefine.cs\" />\n    <Compile Include=\"Network\\General\\NetPacket.cs\" />\n    <Compile Include=\"Network\\General\\Proto\\NetErrorProto.cs\" />\n    <Compile Include=\"Network\\General\\Proto\\NetMessage.cs\" />\n    <Compile Include=\"Network\\General\\Proto\\ProfilerTestProto.cs\" />\n    <Compile Include=\"Network\\General\\Proto\\ProtocolHead.cs\" />\n    <Compile Include=\"Network\\General\\Server\\KcpGateway.cs\" />\n    <Compile Include=\"Network\\General\\Server\\IGateway.cs\" />\n    <Compile Include=\"Network\\General\\Server\\ISession.cs\" />\n    <Compile Include=\"Network\\General\\Server\\KcpSession.cs\" />\n    <Compile Include=\"Network\\General\\Server\\NetManager.cs\" />\n    <Compile Include=\"Network\\General\\Server\\TcpGateway.cs\" />\n    <Compile Include=\"Network\\General\\Server\\TcpSession.cs\" />\n    <Compile Include=\"Network\\General\\Server\\UdpGateway.cs\" />\n    <Compile Include=\"Network\\General\\Server\\UdpSession.cs\" />\n    <Compile Include=\"Network\\General\\TcpConnectionBase.cs\" />\n    <Compile Include=\"Network\\Utils\\DnsUtils.cs\" />\n    <Compile Include=\"Network\\Utils\\IPUtils.cs\" />\n    <Compile Include=\"Network\\Utils\\NetUtils.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Server\\MainLoop.cs\" />\n    <Compile Include=\"Server\\ServerConfig.cs\" />\n    <Compile Include=\"Server\\ServerManager.cs\" />\n    <Compile Include=\"Server\\ServerModule.cs\" />\n    <Compile Include=\"Threading\\ThreadPool.cs\" />\n    <Compile Include=\"Utils\\SGFTime.cs\" />\n    <Compile Include=\"Utils\\AppPrefs.cs\" />\n    <Compile Include=\"Utils\\CmdlineUtils.cs\" />\n    <Compile Include=\"Utils\\ConsoleInput.cs\" />\n    <Compile Include=\"Utils\\FileUtils.cs\" />\n    <Compile Include=\"Utils\\FPSUtils.cs\" />\n    <Compile Include=\"Utils\\MapList.cs\" />\n    <Compile Include=\"Utils\\ObjectDumpUtils.cs\" />\n    <Compile Include=\"Utils\\PathUtils.cs\" />\n    <Compile Include=\"Utils\\Singleton.cs\" />\n    <Compile Include=\"Utils\\StringUtils.cs\" />\n    <Compile Include=\"Utils\\ThrowHelper.cs\" />\n    <Compile Include=\"Utils\\TimeUtils.cs\" />\n    <Compile Include=\"Utils\\URLUtils.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"App.config\" />\n  </ItemGroup>\n  <ItemGroup />\n  <ItemGroup>\n    <Content Include=\"Network\\Core\\KCP\\LICENSE.txt\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <PropertyGroup>\n    <PostBuildEvent>$(ProjectDir)..\\Libs\\PublishLibrary.bat $(TargetName)</PostBuildEvent>\n  </PropertyGroup>\n</Project>"
  },
  {
    "path": "SGFCore/SGFCore.csproj.user",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <PropertyGroup>\n    <ProjectView>ProjectFiles</ProjectView>\n  </PropertyGroup>\n</Project>"
  },
  {
    "path": "SGFCore/Server/MainLoop.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 服务器（模块）管理器\n * Server (module) manager\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing SGF.Utils;\nusing System.Threading;\n\nnamespace SGF.Server\n{\n    public class MainLoop\n    {\n        public static void Run()\n        {\n            Debuger.Log();\n            \n            while (true)\n            {\n                ServerManager.Instance.Tick();\n                ConsoleInput.Tick();\n                Thread.Sleep(1);\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Server/ServerConfig.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 服务器（模块）管理器\n * Server (module) manager\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing MiniJSON.Safe;\nusing SGF.Utils;\n\nnamespace SGF.Server\n{\n    public class ServerModuleInfo\n    {\n        public int id;\n        public string name;\n        public string assembly;\n        public string ip;\n        public int port;\n        public bool auto;\n    }\n\n    public class ServerConfig\n    {\n        public static string Namespace = \"SGF.Server\";\n        internal readonly static string DefaultPath = \"./ServerConfig.json\";\n\n        private readonly static MapList<int, ServerModuleInfo> MapServerModuleInfo = new MapList<int, ServerModuleInfo>();\n\n        public static void Load(string path = null)\n        {\n            MapServerModuleInfo.Clear();\n            if (string.IsNullOrEmpty(path))\n            {\n                path = DefaultPath;\n            }\n            ReadConfig(path);\n        }\n\n        public static ServerModuleInfo GetServerModuleInfo(int id)\n        {\n            if (MapServerModuleInfo.Count == 0)\n            {\n                ReadConfig(DefaultPath);\n            }\n\n            return MapServerModuleInfo[id];\n        }\n\n        public static void SetServerModuleInfo(ServerModuleInfo info)\n        {\n            MapServerModuleInfo[info.id] = info;\n        }\n\n        public static ServerModuleInfo[] GetServerModuleInfoList()\n        {\n            return MapServerModuleInfo.ToArray();\n        }\n\n        private static void ReadConfig(string path)\n        {\n            Debuger.Log();\n            string jsonStr = FileUtils.ReadString(path);\n            List<object> obj = null;\n            try\n            {\n                obj = Json.Deserialize(jsonStr) as List<object>;\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(\"文件加载失败：{0}\", path);\n                return;\n            }\n            \n            for (int i = 0; i < obj.Count; i++)\n            {\n                var infoJson = obj[i] as Dictionary<string, object>;\n                ServerModuleInfo info = new ServerModuleInfo();\n                info.id = (int)infoJson[\"id\"];\n                info.name = (string)infoJson[\"name\"];\n                info.assembly = (string)infoJson[\"assembly\"];\n                info.ip = (string)infoJson[\"ip\"];\n                info.port = (int)infoJson[\"port\"];\n                info.auto = (bool)infoJson[\"auto\"];\n                MapServerModuleInfo.Add(info.id, info);\n            }\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Server/ServerManager.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 服务器（模块）管理器\n * Server (module) manager\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing SGF.Utils;\n\n\nnamespace SGF.Server\n{\n    public class ModuleMessageHandlerAttribute : Attribute\n    {\n\n    }\n\n    public class ServerManager:Singleton<ServerManager>\n    {\n        class MessageObject\n        {\n            public int target;\n            public string msg;\n            public object[] args;\n        }\n\n        private MapList<int, ServerModule> m_mapModule = new MapList<int, ServerModule>();\n        private Dictionary<int, List<MessageObject>> m_mapCacheMessage = new Dictionary<int, List<MessageObject>>();\n        private Queue<MessageObject> m_queueMessage = new Queue<MessageObject>();\n\n        public void Init(string _namespace)\n        {\n            ServerConfig.Namespace = _namespace;\n        }\n\n        public void StartAutoServer()\n        {\n            ServerConfig.Load();\n\n            var list = ServerConfig.GetServerModuleInfoList();\n            for (int i = 0; i < list.Length; i++)\n            {\n                if (list[i].auto)\n                {\n                    StartServer(list[i]);\n                }\n            }\n        }\n\n        public void StartServer(int id)\n        {\n            Debuger.Log(id);\n\n            ServerModuleInfo info = ServerConfig.GetServerModuleInfo(id);\n\n            StartServer(info);\n        }\n\n        public bool StartServer(ServerModuleInfo info)\n        {\n            string fullName = ServerConfig.Namespace + \".\" + info.name + \".\" + info.name;\n            Debuger.Log(fullName);\n\n            try\n            {\n                Type type = Type.GetType(fullName + \",\" + info.assembly);\n                \n                var module = Activator.CreateInstance(type) as ServerModule;\n\n                if (module != null)\n                {\n                    module.Create(info);\n                    m_mapModule.Add(info.id, module);\n\n                    module.Start();\n\n                    ServerConfig.SetServerModuleInfo(info);\n\n                    //处理缓存的消息\n                    if (m_mapCacheMessage.ContainsKey(info.id))\n                    {\n                        List<MessageObject> list = m_mapCacheMessage[info.id];\n                        for (int i = 0; i < list.Count; i++)\n                        {\n                            MessageObject msgobj = list[i];\n                            module.HandleMessage(msgobj.msg, msgobj.args);\n                        }\n                        m_mapCacheMessage.Remove(info.id);\n                    }\n\n                    return true;\n                }\n            }\n            catch (Exception e)\n            {\n                m_mapModule.Remove(info.id);\n                Debuger.LogError(\"ServerModule[{0}] Create Or Start Error:{1}\", info.name,\n                    e.Message + \"\\n\" + e.StackTrace);\n            }\n            return false;\n        }\n\n        public void StopServer(int id)\n        {\n            Debuger.Log(id);\n            var moudule = m_mapModule[id];\n            if (moudule != null)\n            {\n                moudule.Stop();\n                moudule.Release();\n                m_mapModule.Remove(id);\n            }\n        }\n\n        public void StopAllServer()\n        {\n            Debuger.Log();\n            var list = m_mapModule.AsList();\n            int cnt = list.Count;\n            for (int i = 0; i < cnt; i++)\n            {\n                list[i].Stop();\n                list[i].Release();\n            }\n            m_mapModule.Clear();\n        }\n\n        public void Tick()\n        {\n            //Post 消息\n            //不管消息 来自哪个线程，都应该由主线程处理@Slicol\n            lock (m_queueMessage)\n            {\n                while (m_queueMessage.Count > 0)\n                {\n                    var obj = m_queueMessage.Dequeue();\n                    var m = GetModule(obj.target);\n                    if (m != null)\n                    {\n                        m.HandleMessage(obj.msg, obj.args);\n                    }\n                    else\n                    {\n                        Debuger.LogWarning(\"消息被丢弃! target:{0}, msg:{1}\", obj.target, obj.msg);\n                    }\n                }\n            }\n\n\n\n            var list = m_mapModule.AsList();\n            int cnt = list.Count;\n\n            for (int i = 0; i < cnt; i++)\n            {\n                list[i].Tick();\n            }\n        }\n\n        public bool HasModule(int id)\n        {\n            return m_mapModule.ContainsKey(id);\n        }\n\n        public ServerModule GetModule(int id)\n        {\n            ServerModule module = m_mapModule[id];\n            return module;\n        }\n\n        //============================================================================\n        //消息机制\n        //============================================================================\n\n        public void SendMessage(int target, string msg, params object[] args)\n        {\n            ServerModule module = GetModule(target);\n            if (module != null)\n            {\n                module.HandleMessage(msg, args);\n            }\n            else\n            {\n                var list = GetCacheMessageList(target);\n                MessageObject obj = new MessageObject();\n                obj.msg = msg;\n                obj.args = args;\n                obj.target = target;\n                list.Add(obj);\n\n            }\n        }\n\n        public void PostMessage(int target, string msg, params object[] args)\n        {\n            System.Threading.ThreadPool.QueueUserWorkItem(_ => PostMessageInternal(target, msg, args));\n        }\n\n        private void PostMessageInternal(int target, string msg, object[] args)\n        {\n            MessageObject obj = new MessageObject();\n            obj.msg = msg;\n            obj.args = args;\n            obj.target = target;\n\n            lock (m_queueMessage)\n            {\n                m_queueMessage.Enqueue(obj);\n            }\n        }\n\n        \n\n        private List<MessageObject> GetCacheMessageList(int target)\n        {\n            List<MessageObject> list = null;\n            if (!m_mapCacheMessage.TryGetValue(target, out list))\n            {\n                list = new List<MessageObject>();\n                m_mapCacheMessage.Add(target, list);\n            }\n\n            return list;\n        }\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Server/ServerModule.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 服务器（模块）管理器\n * Server (module) manager\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System.Reflection;\n\nnamespace SGF.Server\n{\n    public class ServerModule:ILogTag\n    {\n        private ServerModuleInfo m_info;\n        private object m_msgHandler;\n\n        public int id { get { return m_info.id; } }\n        public int port { get { return m_info.port; } }\n\n\n        internal void Create(ServerModuleInfo info)\n        {\n            m_info = info;\n            m_msgHandler = this;\n\n            LOG_TAG = this.GetType().Name + \"[\" + info.id + \",\" + info.port + \"]\";\n            this.Log();\n        }\n\n        internal void Release()\n        {\n            this.Log();\n        }\n\n        public virtual void Start()\n        {\n            this.Log();\n        }\n\n        public virtual void Stop()\n        {\n            this.Log();\n        }\n\n        public virtual void Tick()\n        {\n            \n        }\n\n        public void BindModuleMessageHandler(object handler)\n        {\n            m_msgHandler = handler == null ? this : handler;\n        }\n\n        /// <summary>\n        /// 当模块收到消息后，对消息进行一些处理\n        /// </summary>\n        /// <param name=\"msg\"></param>\n        /// <param name=\"args\"></param>\n        internal void HandleMessage(string msg, object[] args)\n        {\n            this.Log(\"msg:{0}, args:{1}\", msg, args);\n\n            var mi = m_msgHandler.GetType().GetMethod(msg, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);\n            if (mi != null)\n            {\n                mi.Invoke(m_msgHandler, BindingFlags.NonPublic, null, args, null);\n            }\n            else\n            {\n                OnModuleMessage(msg, args);\n            }\n\n        }\n\n        /// <summary>\n        /// 由派生类去实现，用于处理消息\n        /// </summary>\n        /// <param name=\"msg\"></param>\n        /// <param name=\"args\"></param>\n        protected virtual void OnModuleMessage(string msg, object[] args)\n        {\n            this.Log(\"msg:{0}, args{1}\", msg, args);\n\n        }\n\n\n        public string LOG_TAG { get; private set; }\n    }\n}"
  },
  {
    "path": "SGFCore/Threading/ThreadPool.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Threading;\n\nnamespace SGF.Threading\n{\n    public class ThreadPool\n    {\n        class ThreadTaskState\n        {\n            public object[] args;\n            public Delegate func;\n        }\n\n        public static int maxThreads = 8;\n        private static int numThreads = 0;\n        private static List<ThreadTaskState> ms_listFuncOnMainThread = new List<ThreadTaskState>();\n        private static List<ThreadTaskState> ms_currentInvokingFuncs = new List<ThreadTaskState>();\n        private static Delegate ms_funcThreadWorker;\n\n        public static void QueueOnMainThread(Delegate func, params object[] args)\n        {\n            lock (ms_listFuncOnMainThread)\n            {\n                var state = new ThreadTaskState() { args = args, func = func };\n                ms_listFuncOnMainThread.Add(state);\n            }\n        }\n\n        public static Thread QueueUserWorkItem(Delegate func, params object[] args)\n        {\n            if (ms_funcThreadWorker == null)\n            {\n                ms_funcThreadWorker = (WaitCallback)ThreadWorker;\n            }\n\n            while (numThreads >= maxThreads)\n            {\n                Thread.Sleep(1);\n            }\n\n            Interlocked.Increment(ref numThreads);\n            try\n            {\n                //如果线程不够了，就直接执行\n                var state = new ThreadTaskState() { args = args, func = func };\n                System.Threading.ThreadPool.QueueUserWorkItem((WaitCallback)(ms_funcThreadWorker), state);\n\n            }\n            catch (Exception e)\n            {\n                ((Action<object[]>)func)(args);\n                Interlocked.Decrement(ref numThreads);\n            }\n            finally\n            {\n\n            }\n\n            return null;\n        }\n\n        private static void ThreadWorker(object obj)\n        {\n            try\n            {\n                ThreadTaskState state = obj as ThreadTaskState;\n\n                ((Action<object[]>)state.func)(state.args);\n            }\n            catch\n            {\n            }\n            finally\n            {\n                Interlocked.Decrement(ref numThreads);\n            }\n\n        }\n\n        public static void TickOnMainThread()\n        {\n            lock (ms_listFuncOnMainThread)\n            {\n                ms_currentInvokingFuncs.Clear();\n                ms_currentInvokingFuncs.AddRange(ms_listFuncOnMainThread);\n                ms_listFuncOnMainThread.Clear();\n            }\n            foreach (var state in ms_currentInvokingFuncs)\n            {\n                try\n                {\n                    ((Action<object[]>)state.func)(state.args);\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogWarning(e.Message);\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Timers/Timer.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\n\nnamespace SGF.Timers\n{\n    public delegate void ElapsedEventHandler(object sender, ElapsedEventArgs e);\n\n    public class ElapsedEventArgs : EventArgs\n    {\n        private DateTime signalTime;\n        public DateTime SignalTime { get { return this.signalTime; } }\n\n        internal ElapsedEventArgs()\n        {\n            signalTime = DateTime.Now;\n        }\n    }\n\n    public class Timer:IDisposable\n    {\n        //=========================================================================\n        #region ////Timer Manager////\n        private static List<Timer> m_timers = new List<Timer>();\n        private static long m_lastTicks = 0;\n        private static void AddTimer(Timer timer)\n        {\n            if(!m_timers.Contains(timer))\n            {\n                m_timers.Add(timer);\n            }\n        }\n\n        private static void RemoveTimer(Timer timer)\n        {\n            try\n            {\n                m_timers.Remove(timer);\n            }\n            catch { }\n        }\n\n        public static void Tick()\n        {\n            var now = DateTime.Now.Ticks;\n            var dt = now - m_lastTicks;\n            m_lastTicks = now;\n            Tick(GetMillisecondsFromTicks(dt));\n        }\n\n\n        public static void Tick(double dt)\n        {\n            var timers = m_timers.ToArray();\n            for(int i =0;i < timers.Length; ++i)\n            {\n                timers[i].TickInternal(dt);\n            }\n        }\n\n\n        public static double GetMillisecondsFromTicks(long ticks)\n        {\n            return ticks / 10000.0f;\n        }\n\n        #endregion\n        //=========================================================================\n\n        private bool m_disposed = false;\n        private double m_elapsed = 0;\n        private double m_interval;\n        private int m_count;\n\n        private bool m_enabled;\n        private bool m_autoReset = false;\n\n        public ElapsedEventHandler onIntervalElapsed;\n        \n        public Timer()\n        {\n            m_interval = 100;\n            m_enabled = false;\n            m_autoReset = true;\n        }\n\n        public Timer(double interval)\n        {\n            if (interval <= 0)\n                interval = 0;\n\n            double roundedInterval = Math.Ceiling(interval);\n            if (roundedInterval > Int32.MaxValue || roundedInterval <= 0)\n            {\n                roundedInterval = 0;\n            }\n\n            this.m_interval = (int)roundedInterval;\n        }\n\n        ~Timer()\n        {\n            Dispose();\n        }\n\n        public void Dispose()\n        {\n            if (m_disposed) return;\n            m_disposed = true;\n\n            Close();\n        }\n\n\n        public void Close()\n        {\n            m_enabled = false;\n            RemoveTimer(this);\n        }\n\n\n\n        public bool AutoReset\n        {\n            get\n            {\n                return this.m_autoReset;\n            }\n\n            set\n            {\n                if (this.m_autoReset != value)\n                {\n                    this.m_autoReset = value;\n                    if(value)\n                    {\n                        Enabled = true;\n                    }\n                }\n            }\n        }\n\n\n        public bool Enabled\n        {\n            get\n            {\n                return m_enabled;\n            }\n\n            set\n            {\n                if (m_enabled != value)\n                {\n                    m_enabled = value;\n\n                    if (!value)\n                    {\n                        RemoveTimer(this);\n                    }\n                    else\n                    {\n                        AddTimer(this);\n                    }\n                }\n            }\n        }\n\n        public double Interval\n        {\n            get\n            {\n                return this.m_interval;\n            }\n\n            set\n            {\n                m_interval = value;\n            }\n        }\n\n\n        public event ElapsedEventHandler Elapsed\n        {\n            add\n            {\n                onIntervalElapsed += value;\n            }\n            remove\n            {\n                onIntervalElapsed -= value;\n            }\n        }\n\n\n        public void Start()\n        {\n            Enabled = true;\n        }\n\n        public void Stop()\n        {\n            Enabled = false;\n        }\n\n        internal void TickInternal(double dt)\n        {\n            m_elapsed += dt;\n            if(m_elapsed >= m_interval)\n            {\n                m_elapsed -= m_interval;\n\n                if (!this.m_autoReset)\n                {\n                    Enabled = false;\n                }\n\n                try\n                {\n                    ElapsedEventHandler intervalElapsed = this.onIntervalElapsed;\n                    if (intervalElapsed != null)\n                    {\n                        ElapsedEventArgs elapsedEventArgs = new ElapsedEventArgs();\n                        intervalElapsed(this, elapsedEventArgs);\n                    }\n                }\n                catch\n                {\n\n                }\n            }\n        }\n\n\n    }\n}\n\n\n"
  },
  {
    "path": "SGFCore/Utils/AppPrefs.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing MiniJSON.Safe;\n\nnamespace SGF.Utils\n{\n    public static class AppPrefs\n    {\n        private static string m_path;\n        private static JsonObject m_jobj = new JsonObject();\n\n        public static void Init(string path)\n        {\n            m_path = path;\n            var str = FileUtils.ReadString(m_path);\n            if (!string.IsNullOrEmpty(str))\n            {\n                try\n                {\n                    m_jobj = Json.Deserialize(str) as JsonObject;\n                }\n                catch (Exception e)\n                {\n                    \n                }\n            }\n\n            if(m_jobj == null) m_jobj = new JsonObject();\n        }\n        \n        //\n        public static float GetFloat(string key, float defaultValue = 0)\n        {\n            var obj = m_jobj[GetKey(key)];\n            if (obj == null) return defaultValue;\n            return (float)Convert.ToDouble(obj);\n        }\n\n        public static int GetInt(string key, int defaultValue = 0)\n        {\n            var obj = m_jobj[GetKey(key)];\n            if (obj == null) return defaultValue;\n            return (int)Convert.ToInt32(obj);\n        }\n\n        public static string GetString(string key, string defaultValue = \"\")\n        {\n            var obj = m_jobj[GetKey(key)];\n            if (obj == null) return defaultValue;\n            return (string)obj;\n            \n        }\n\n        //\n        public static bool HasKey(string key)\n        {\n            return m_jobj.ContainsKey(GetKey(key));\n        }\n\n        //\n        public static void SetFloat(string key, float value)\n        {\n            m_jobj[GetKey(key)] = value;\n        }\n\n        //\n        public static void SetInt(string key, int value)\n        {\n            m_jobj[GetKey(key)] = value;\n        }\n\n        //\n        public static void SetString(string key, string value)\n        {\n            m_jobj[GetKey(key)] = value;\n        }\n\n        public static void DeleteAll()\n        {\n            m_jobj.Clear();\n        }\n\n        //\n        public static void DeleteKey(string key)\n        {\n            if (m_jobj.ContainsKey(GetKey(key)))\n            {\n                m_jobj.Remove(GetKey(key));\n            }\n        }\n\n        public static void Save()\n        {\n            var str = Json.Serialize(m_jobj);\n            FileUtils.SaveFile(m_path, str);\n        }\n\n        private static string GetKey(string key)\n        {\n            return key;\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Utils/CmdlineUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing SGF.Extension;\n\nnamespace SGF.Utils\n{\n    public class CmdlineUtils\n    {\n        public static string GetArgValue(string[] args, string name)\n        {\n            for (int i = 0; i < args.Length; i++)\n            {\n                var token = args[i];\n                if (token.ToLower() == name)\n                {\n                    if (i < args.Length - 1)\n                    {\n                        return args[i + 1];\n                    }\n                }\n            }\n            return \"\";\n        }\n\n        public static bool HasArg(string[] args, string name)\n        {\n            for (int i = 0; i < args.Length; i++)\n            {\n                var token = args[i];\n                if (token.ToLower() == name)\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n\n\n        public static int GetArgInt(string[] args, string name)\n        {\n            return GetArgValue(args, name).ToInt();\n        }\n\n        public static float GetArgFloat(string[] args, string name)\n        {\n            return GetArgValue(args, name).ToFloat();\n        }\n\n        public static bool GetArgBool(string[] args, string name)\n        {\n            return GetArgValue(args, name) == \"true\";\n        }\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Utils/ConsoleInput.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 通过事件的方式监听来自控制台的输入\n * Monitor input from the console by way of events\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing SGF.SEvent;\n\nnamespace SGF.Utils\n{\n\n\n    public class ConsoleInput\n    {\n        enum InputState\n        {\n            Idle = 0,\n            Inputing = 1\n        }\n        public readonly static Signal<string> onInputLine = new Signal<string>();\n        public readonly static Signal<ConsoleKey> onInputKey = new Signal<ConsoleKey>();\n\n        private static InputState ms_InputState = InputState.Idle;\n        private static string ms_InputBuffer = \"\";\n\n        public static void Tick()\n        {\n            if (Console.KeyAvailable)\n            {\n                ConsoleKeyInfo info = Console.ReadKey();\n\n                if (ms_InputState == InputState.Inputing)\n                {\n                    if (info.Key == ConsoleKey.Enter)\n                    {\n                        ms_InputState = InputState.Idle;\n                        Console.WriteLine();//输入框消失\n                        onInputLine.Invoke(ms_InputBuffer);\n                    }\n                    else if (info.Key == ConsoleKey.Escape)\n                    {\n                        ms_InputState = InputState.Idle;\n                        Console.WriteLine();//输入框消失\n                    }\n                    else if (info.Key >= ConsoleKey.A && info.Key <= ConsoleKey.Z)\n                    {\n                        ms_InputBuffer += info.KeyChar;\n                    }\n                    else if (info.Key >= ConsoleKey.D0 && info.Key <= ConsoleKey.D9)\n                    {\n                        ms_InputBuffer += info.KeyChar;\n                    }\n                    else \n                    {\n                        ms_InputBuffer += info.KeyChar;\n                    }\n                }\n                else if(ms_InputState == InputState.Idle)\n                {\n                    onInputKey.Invoke(info.Key);\n                    \n                    if (info.Key == ConsoleKey.Enter)\n                    {\n                        ms_InputState = InputState.Inputing;\n                        ms_InputBuffer = \"\";\n                        //显示一个输入框\n                        Console.Write(\"Input:\");\n                    }\n                }\n            }\n        }\n\n\n\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Utils/DictionarySafe.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 封装Dictionary以提供简捷而安全的使用方式\n * Encapsulate Dictionary to provide simple and safe use\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\n\nnamespace SGF.Utils\n{ \n    public class DictionarySafe<TKey, TValue> : Dictionary<TKey, TValue> \n    {\n        public new TValue this[TKey key]\n        {\n            set { base[key] = value; }\n            get\n            {\n                TValue value = default(TValue);\n                TryGetValue(key, out value);\n                return value;\n            }\n        }\n\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/Utils/FPSUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace SGF.Utils\n{\n    public static class FPSUtils\n    {\n        public class FPSStatInfo\n        {\n            public string tag;\n            public long beginTime;\n            internal uint beginFrame;\n            public long timeLength;\n            public uint frameCount;\n            \n        }\n\n        private static uint m_frameIndex = 0;\n        private static Stack<FPSStatInfo> m_stack = new Stack<FPSStatInfo>();\n        private static List<FPSStatInfo> m_listResult = new List<FPSStatInfo>();\n\n        /// <summary>\n        /// 不支持嵌套\n        /// </summary>\n        /// <param name=\"tag\"></param>\n        public static void Begin(string tag)\n        {\n            FPSStatInfo info = new FPSStatInfo();\n            info.tag = tag;\n            info.beginFrame = m_frameIndex;\n            info.beginTime = DateTime.Now.Ticks;\n            m_stack.Push(info);\n        }\n\n        public static void End()\n        {\n            if (m_stack.Count > 0)\n            {\n                var info = m_stack.Pop();\n                info.timeLength = DateTime.Now.Ticks - info.beginTime;\n                info.frameCount = m_frameIndex - info.beginFrame;\n                m_listResult.Add(info);\n            }\n            else\n            {\n                Debuger.LogError(\"Begin与End没有成对调用！\");\n            }\n        }\n\n        public static void Update()\n        {\n            ++m_frameIndex;\n        }\n\n        public static float GetAverageFPS(string tag)\n        {\n            long totalTime = 0;\n            uint totalFrame = 0;\n            for (int i = 0; i < m_listResult.Count; i++)\n            {\n                var info = m_listResult[i];\n                if (info.tag == tag)\n                {\n                    totalTime += info.timeLength;\n                    totalTime += info.frameCount;\n                }\n            }\n            \n            return (float)(totalFrame / TimeUtils.GetSecondsFromTicks(totalTime));\n        }\n\n        public static FPSStatInfo[] GetFPSStatInfos()\n        {\n            return m_listResult.ToArray();\n        }\n\n        public static string GetDumpString(bool cluster = false)\n        {\n            StringBuilder sb = new StringBuilder();\n            \n            if (cluster)\n            {\n                Dictionary<string, long[]> mapFPS = new Dictionary<string, long[]>();\n                for (int i = 0; i < m_listResult.Count; i++)\n                {\n                    var info = m_listResult[i];\n                    long[] tmp = null;\n                    if (!mapFPS.TryGetValue(info.tag, out tmp))\n                    {\n                        tmp = new long[2];\n                        mapFPS.Add(info.tag, tmp);\n                    }\n\n                    tmp[0] += info.timeLength;\n                    tmp[1] += info.frameCount;\n                }\n\n                sb.AppendFormat(\"{0,2}. {1,5} {2}\\n\", \"#\", \"FPS\", \"Tag\");\n                int j = 0;\n                foreach (var pair in mapFPS)\n                {\n                    var tag = pair.Key;\n                    float fps = (float)(pair.Value[1] / TimeUtils.GetSecondsFromTicks(pair.Value[0]));\n                    sb.AppendFormat(\"{0,2}. {1,5} {2}\\n\", j, fps, tag);\n                    j++;\n                }\n                sb.AppendFormat(\"-----------------------------\\n\");\n            }\n            else\n            {\n                sb.AppendFormat(\"{0,2}. {1,5} {2}\\n\", \"#\", \"FPS\", \"Tag\");\n                for (int i = 0; i < m_listResult.Count; i++)\n                {\n                    var info = m_listResult[i];\n                    float fps = (float)(info.frameCount / TimeUtils.GetSecondsFromTicks(info.timeLength));\n                    sb.AppendFormat(\"{0,2}. {1,5} {2}\\n\", i, fps, info.tag);\n                }\n                sb.AppendFormat(\"-----------------------------\\n\");\n            }\n\n            return sb.ToString();\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Utils/FileUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * FileUtils\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing SGF.Marshals;\n\n\nnamespace SGF.Utils\n{\n    public class FileUtils\n    {\n        public static byte[] ReadFile(string fullpath, int readsize = 0)\n        {\n            byte[] buffer = null;\n            if (File.Exists(fullpath))\n            {\n                FileStream fs = null;\n                try\n                {\n                    fs = new FileStream(fullpath, FileMode.Open, FileAccess.Read);\n                    if (readsize == 0 || readsize >= fs.Length)\n                    {\n                        buffer = new byte[fs.Length];\n                    }\n                    else\n                    {\n                        buffer = new byte[readsize];\n                    }\n                    fs.Read(buffer, 0, buffer.Length);\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogError(\"ReadFile() Path:{0}, Error:{1}\", fullpath, e.Message);\n                }\n                finally\n                {\n                    if (fs != null)\n                    {\n                        fs.Close();\n                    }\n                }\n            }\n            else\n            {\n                Debuger.LogError(\"ReadFile() File is Not Exist: {0}\", fullpath);\n            }\n            return buffer;\n        }\n\n\n        public static string[] ReadFileLines(string fullpath)\n        {\n            List<string> listLines = new List<string>();\n            if (File.Exists(fullpath))\n            {\n                StreamReader fs = null;\n                \n                try\n                {\n                    fs = new StreamReader(fullpath);\n                    while (fs.Peek() > 0)\n                    {\n                        listLines.Add(fs.ReadLine());\n                    }\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogError(\"ReadFileLines() Path:{0}, Error:{1}\", fullpath, e.Message);\n                }\n                finally\n                {\n                    if (fs != null)\n                    {\n                        fs.Close();\n                    }\n                }\n            }\n            else\n            {\n                Debuger.LogError(\"ReadFileLines() File is Not Exist: {0}\", fullpath);\n            }\n            return listLines.ToArray();\n        }\n\n\n        public static string ReadString(string fullpath)\n        {\n            byte[] buffer = ReadFile(fullpath);\n            if (buffer != null)\n            {\n                return Encoding.UTF8.GetString(buffer);\n            }\n            return \"\";\n        }\n\n\n        public static string ReadStringASCII(string fullpath)\n        {\n            byte[] buffer = ReadFile(fullpath);\n            if (buffer != null)\n            {\n                return Encoding.ASCII.GetString(buffer);\n            }\n            return \"\";\n        }\n\n        public static int SaveFile(string fullpath, byte[] content)\n        {\n            if (content == null)\n            {\n                content = new byte[0];\n            }\n\n            string dir = PathUtils.GetParentDir(fullpath);\n\n            if (!Directory.Exists(dir))\n            {\n                try\n                {\n                    Directory.CreateDirectory(dir);\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogError(\"SaveFile() CreateDirectory Error! Dir:{0}, Error:{1}\", dir, e.Message);\n                    return -1;\n                }\n\n            }\n\n            FileStream fs = null;\n            try\n            {\n                fs = new FileStream(fullpath, FileMode.Create, FileAccess.Write);\n                fs.Write(content, 0, content.Length);\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(\"SaveFile() Path:{0}, Error:{1}\", fullpath, e.Message);\n                fs.Close();\n                return -1;\n            }\n\n            fs.Close();\n            return content.Length;\n        }\n\n\n\n        public static int SaveFile(string fullpath, string content)\n        {\n            byte[] buffer = Encoding.UTF8.GetBytes(content);\n            return SaveFile(fullpath, buffer);\n        }\n\n        public static List<string> GetFileFullNames(string dir, SearchOption option, string searchPattern,\n            string[] listIgnoredSuffix = null)\n        {\n            List<string> result = new List<string>();\n            var list = GetFiles(dir, option, searchPattern, listIgnoredSuffix);\n            for (int i = 0; i < list.Count; i++)\n            {\n                result.Add(list[i].FullName);\n            }\n            return result;\n        }\n\n        public static List<string> GetFileNames(string dir, SearchOption option, string searchPattern,\n            string[] listIgnoredSuffix = null)\n        {\n            List<string> result = new List<string>();\n            var list = GetFiles(dir, option, searchPattern, listIgnoredSuffix);\n            for (int i = 0; i < list.Count; i++)\n            {\n                result.Add(list[i].Name);\n            }\n            return result;\n        }\n\n        public static List<FileInfo> GetFiles(string dir, SearchOption option, string searchPattern, string[] listIgnoredSuffix = null)\n        {\n            List<FileInfo> result = new List<FileInfo>();\n\n            if (Directory.Exists(dir))\n            {\n                DirectoryInfo directory = new DirectoryInfo(dir);\n                FileInfo[] files = directory.GetFiles(searchPattern, option);\n\n                int len = files.Length;\n                for (int i = 0; i < len; i++)\n                {\n                    FileInfo f = files[i];\n                    bool ignored = false;\n                    if (listIgnoredSuffix != null)\n                    {\n                        int lenIgnored = listIgnoredSuffix.Length;\n                        for (int j = 0; j < lenIgnored; j++)\n                        {\n                            if (f.FullName.EndsWith(listIgnoredSuffix[j]))\n                            {\n                                ignored = true;\n                                break;\n                            }\n                        }\n                    }\n\n                    if (!ignored)\n                    {\n                        result.Add(f);\n                    }\n                }\n            }\n\n            return result;\n        }\n\n\n        public static void EnsureDirectory(string dirPath)\n        {\n            dirPath = dirPath.Replace('\\\\', '/');\n            var tokens = dirPath.Split('/');\n\n            string dstTempPath = \"\";\n            for (int i = 0; i < tokens.Length; i++)\n            {\n                dstTempPath += tokens[i] + \"/\";\n                if (!Directory.Exists(dstTempPath))\n                {\n                    Directory.CreateDirectory(dstTempPath);\n                }\n            }\n        }\n\n        public static void EnsureFileDirectory(string filePath)\n        {\n            filePath = filePath.Replace('\\\\', '/');\n            var tokens = filePath.Split('/');\n\n            string dstTempPath = \"\";\n            for (int i = 0; i < tokens.Length - 1; i++)\n            {\n                dstTempPath += tokens[i] + \"/\";\n                if (!Directory.Exists(dstTempPath))\n                {\n                    Directory.CreateDirectory(dstTempPath);\n                }\n            }\n        }\n\n\n\n        public static bool Copy(string srcPath, string dstPath)\n        {\n            if (!File.Exists(srcPath))\n            {\n                return false;\n            }\n\n            EnsureFileDirectory(dstPath);\n            \n            try\n            {\n                File.Copy(srcPath, dstPath);\n                return true;\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(e.Message);\n            }\n\n            return false;\n        }\n    }\n}\n\n"
  },
  {
    "path": "SGFCore/Utils/MapList.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 将Dictionary与List封装在一起，以满足既需要快速遍历，又需要快速按Key存取的需求\n * Wrap the Dictionary and List together to meet the need for fast traversal and fast key access\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\n\nnamespace SGF.Utils\n{\n    public class MapList<TKey, TValue>\n    {\n        private Dictionary<TKey, TValue> m_map;\n        private List<TValue> m_list;\n\n        public MapList(int capacity)\n        {\n            m_map = new Dictionary<TKey, TValue>(capacity);\n            m_list = new List<TValue>(capacity);\n        }\n\n        public MapList()\n        {\n            m_map = new Dictionary<TKey, TValue>();\n            m_list = new List<TValue>();\n        }\n\n        public List<TValue> AsList()\n        {\n            return m_list;\n        }\n\n        public Dictionary<TKey, TValue> AsDictionary()\n        {\n            return m_map;\n        }\n\n        public List<TValue> ToList()\n        {\n            return m_list.ToList();\n        }\n\n        public TValue[] ToArray()\n        {\n            return m_list.ToArray();\n        }\n\n        public new TValue this[TKey indexKey]\n        {\n            set\n            {\n                if (m_map.ContainsKey(indexKey))\n                {\n                    TValue v = m_map[indexKey];\n                    m_map[indexKey] = value;\n                    m_list.Remove(v);\n                    m_list.Add(value);\n                }\n                else\n                {\n                    m_map.Add(indexKey, value);\n                    m_list.Add(value);\n                }\n\n            }\n            get\n            {\n                TValue value = default(TValue);\n                m_map.TryGetValue(indexKey, out value);\n                return value;\n                \n            }\n        }\n\n        public bool Add(TKey key, TValue value)\n        {\n            if (m_map.ContainsKey(key))\n            {\n                return false;\n            }\n            m_map.Add(key, value);\n            m_list.Add(value);\n            return true;\n        }\n\n        public bool Remove(TKey key)\n        {\n            if (m_map.ContainsKey(key))\n            {\n                TValue v = m_map[key];\n                m_list.Remove(v);\n                return m_map.Remove(key);\n            }\n            return false;\n        }\n\n        public bool RemoveAt(int index, TKey key)\n        {\n            m_list.RemoveAt(index);\n            return m_map.Remove(key);\n        }\n\n\n\n        public void Clear()\n        {\n            m_map.Clear();\n            m_list.Clear();\n        }\n\n        public int Count\n        {\n            get { return m_list.Count; }\n        }\n        public bool ContainsKey(TKey key)\n        {\n            return m_map.ContainsKey(key);\n        }\n\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/Utils/ObjectDumpUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System.Collections;\nusing System.Text;\n\nnamespace SGF.Utils\n{\n    public class ObjectDumpUtils\n    {\n        public static void Dump(string name, object obj, StringBuilder result, string prefix = \"\")\n        {\n            if (obj == null)\n            {\n                return;\n            }\n\n\n            var type = obj.GetType();\n            if (type == typeof(int) ||\n                type == typeof(uint) ||\n                type == typeof(short) ||\n                type == typeof(ushort) ||\n                type == typeof(long) ||\n                type == typeof(ulong) ||\n                type == typeof(byte) ||\n                type == typeof(float) ||\n                type == typeof(double) ||\n                type == typeof(string) ||\n                type == typeof(bool)\n            )\n            {\n                result.AppendFormat(\"{0}{1}:{2}\\n\", prefix, name, obj);\n                return;\n            }\n\n            result.AppendFormat(\"{0}{1}:\\n\", prefix, name);\n\n            if (obj is IList)\n            {\n                var list = obj as IList;\n                for (int i = 0; i < list.Count; i++)\n                {\n                    var tmp = list[i];\n                    Dump(\"[\" + i + \"]\", tmp, result, prefix + \"    \");\n                }\n                return;\n            }\n\n            var fields = type.GetFields();\n            for (int i = 0; i < fields.Length; i++)\n            {\n                var fi = fields[i];\n                var f = fi.GetValue(obj);\n\n                if (fi.Name == \"MaxValue\" || fi.Name == \"MinValue\")\n                {\n                    continue;\n                }\n\n                Dump(fi.Name, f, result, prefix + \"    \");\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Utils/PathUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * PathUtils\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\n\nnamespace SGF.Utils\n{\n    public class PathUtils\n    {\n        public static readonly string[] PathHeadDefine = { \"jar://\", \"jar:file:///\", \"file:///\", \"http://\", \"https://\" };\n\n        public static bool IsSureDir(string path)\n        {\n            int i = path.LastIndexOf(\"/\");\n            if (i >= 0)\n            {\n                return true;\n            }\n            i = path.LastIndexOf(\"\\\\\");\n            if (i >= 0)\n            {\n                return true;\n            }\n            return false;\n        }\n\n        public static bool IsFullPath(string path)\n        {\n            int i = path.IndexOf(\":/\");\n            if (i >= 0)\n            {\n                return true;\n            }\n\n            i = path.IndexOf(\":\\\\\");\n            if (i >= 0)\n            {\n                return true;\n            }\n\n            return false;\n        }\n\n\n        public static string GetFileName(string path)\n        {\n            string parent = \"\", child = \"\";\n            SplitPath(path, ref parent, ref child, true);\n            return child;\n        }\n\n        public static string GetParentDir(string path)\n        {\n            string parent = \"\", child = \"\";\n            SplitPath(path, ref parent, ref child, true);\n            return parent;\n        }\n\n        public static string SplitPath(string path, ref string parent, ref string child, bool bSplitExt = false)\n        {\n            string ext = \"\";\n            string head = SplitPath(path, ref parent, ref child, ref ext);\n            if (bSplitExt)\n            {\n                return head;\n            }\n            if (!string.IsNullOrEmpty(ext))\n            {\n                child = child + \".\" + ext;\n            }\n            return head;\n        }\n\n        public static string SplitPath(string path, ref string parent, ref string child, ref string ext)\n        {\n            string head = GetPathHead(path);\n\n            int index = path.LastIndexOf(\"/\");\n            int index2 = path.LastIndexOf(\"\\\\\");\n            index = System.Math.Max(index, index2);\n\n            if (index == head.Length - 1)\n            {\n                parent = \"\";\n                child = path;\n            }\n            else\n            {\n                parent = path.Substring(0, index);\n                child = path.Substring(index + 1);\n            }\n\n            index = child.LastIndexOf(\".\");\n            if (index >= 0)\n            {\n                ext = child.Substring(index + 1);\n                child = child.Substring(0, index);\n\n            }\n\n            return head;\n        }\n\n        public static string GetPathHead(string path)\n        {\n            for (int i = 0; i < PathHeadDefine.Length; i++)\n            {\n                if (path.StartsWith(PathHeadDefine[i]))\n                {\n                    return PathHeadDefine[i];\n                }\n            }\n\n            return \"\";\n        }\n\n\n\n\n\n\n    }\n\n\n\n}\n"
  },
  {
    "path": "SGFCore/Utils/SGFTime.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * 类似Unity里的Time类。\n * 需要在App启动时，进行初始化。\n * Similar to the Time class in Unity. \n * It needs to be initialized when the app starts.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\n\nnamespace SGF.Time\n{\n    public class SGFTime\n    {\n        public static DateTime DateTimeAppStart = new DateTime(1970, 1, 1, 8, 0, 0);\n\n        public static float GetTimeSinceStartup()\n        {\n            DateTime nowtime = DateTime.Now.ToLocalTime();\n            return (float)(nowtime.Subtract(DateTimeAppStart).TotalSeconds);\n        }\n\n\n    }\n}"
  },
  {
    "path": "SGFCore/Utils/Singleton.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Singleton\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nnamespace SGF.Utils\n{\n    public abstract class Singleton<T> where T : Singleton<T>, new()\n    {\n        private static T ms_instance = default(T);\n\n        public static T Instance\n        {\n            get\n            {\n                if (ms_instance == null)\n                {\n                    ms_instance = new T();\n                    ms_instance.InitSingleton();\n                }\n                return ms_instance;\n            }\n        }\n\n        protected virtual void InitSingleton()\n        {\n            \n        }\n    }\n\n    //**********************************************************************\n\n}\n"
  },
  {
    "path": "SGFCore/Utils/StringUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections;\nusing System.Text;\n\nnamespace SGF.Utils\n{\n    public static class StringUtils\n    {\n        private static StringBuilder ms_temp = new StringBuilder();\n\n        public static string ToString(Array target)\n        {\n            ms_temp.Length = 0;\n            ms_temp.Append(\"[\");\n            if (target.Length > 0)\n            {\n                ms_temp.Append(target.GetValue(0));\n            }\n\n            for (int i = 1; i < target.Length; i++)\n            {\n                ms_temp.Append(\",\");\n                ms_temp.Append(target.GetValue(i));\n            }\n            ms_temp.Append(\"]\");\n            return ms_temp.ToString();\n        }\n\n        public static string ToString(IList target)\n        {\n            ms_temp.Length = 0;\n            ms_temp.Append(\"[\");\n            if (target.Count > 0)\n            {\n                ms_temp.Append(target[0]);\n            }\n\n            for (int i = 1; i < target.Count; i++)\n            {\n                ms_temp.Append(\",\");\n                ms_temp.Append(target[i]);\n            }\n            ms_temp.Append(\"]\");\n            return ms_temp.ToString();\n        }\n\n    }\n}"
  },
  {
    "path": "SGFCore/Utils/ThrowHelper.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.Serialization;\nusing System.Security;\n\nnamespace SGF.Utils\n{\n    internal enum ExceptionArgument\n    {\n        obj,\n        dictionary,\n        dictionaryCreationThreshold,\n        array,\n        info,\n        key,\n        collection,\n        list,\n        match,\n        converter,\n        queue,\n        stack,\n        capacity,\n        index,\n        startIndex,\n        value,\n        count,\n        arrayIndex,\n        name,\n        mode,\n    }\n\n    internal enum ExceptionResource\n    {\n        Argument_ImplementIComparable,\n        Argument_InvalidType,\n        Argument_InvalidArgumentForComparison,\n        Argument_InvalidRegistryKeyPermissionCheck,\n        ArgumentOutOfRange_NeedNonNegNum,\n        Arg_ArrayPlusOffTooSmall,\n        Arg_NonZeroLowerBound,\n        Arg_RankMultiDimNotSupported,\n        Arg_RegKeyDelHive,\n        Arg_RegKeyStrLenBug,\n        Arg_RegSetStrArrNull,\n        Arg_RegSetMismatchedKind,\n        Arg_RegSubKeyAbsent,\n        Arg_RegSubKeyValueAbsent,\n        Argument_AddingDuplicate,\n        Serialization_InvalidOnDeser,\n        Serialization_MissingKeyValuePairs,\n        Serialization_NullKey,\n        Argument_InvalidArrayType,\n        NotSupported_KeyCollectionSet,\n        NotSupported_ValueCollectionSet,\n        ArgumentOutOfRange_SmallCapacity,\n        ArgumentOutOfRange_Index,\n        Argument_InvalidOffLen,\n        Argument_ItemNotExist,\n        ArgumentOutOfRange_Count,\n        ArgumentOutOfRange_InvalidThreshold,\n        ArgumentOutOfRange_ListInsert,\n        NotSupported_ReadOnlyCollection,\n        InvalidOperation_CannotRemoveFromStackOrQueue,\n        InvalidOperation_EmptyQueue,\n        InvalidOperation_EnumOpCantHappen,\n        InvalidOperation_EnumFailedVersion,\n        InvalidOperation_EmptyStack,\n        ArgumentOutOfRange_BiggerThanCollection,\n        InvalidOperation_EnumNotStarted,\n        InvalidOperation_EnumEnded,\n        NotSupported_SortedListNestedWrite,\n        InvalidOperation_NoValue,\n        InvalidOperation_RegRemoveSubKey,\n        Security_RegistryPermission,\n        UnauthorizedAccess_RegistryNoWrite,\n        ObjectDisposed_RegKeyClosed,\n        NotSupported_InComparableType,\n    }\n\n    internal static class ThrowHelper\n    {\n        [MethodImpl(MethodImplOptions.NoInlining)]\n        internal static void ThrowArgumentOutOfRangeException()\n        {\n            ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);\n        }\n\n        internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType)\n        {\n            throw new ArgumentException(\"WrongKeyTypeArgumentException\");\n        }\n\n        internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType)\n        {\n            throw new ArgumentException(\"WrongValueTypeArgumentException\");\n        }\n\n        internal static void ThrowKeyNotFoundException()\n        {\n            throw new KeyNotFoundException();\n        }\n\n        internal static void ThrowArgumentException(ExceptionResource resource)\n        {\n            throw new ArgumentException(\"ArgumentException:\" + ThrowHelper.GetResourceName(resource));\n        }\n\n        internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument)\n        {\n            throw new ArgumentException(\"ArgumentException:\" + (ThrowHelper.GetResourceName(resource)), ThrowHelper.GetArgumentName(argument));\n        }\n\n        internal static void ThrowArgumentNullException(ExceptionArgument argument)\n        {\n            throw new ArgumentNullException(ThrowHelper.GetArgumentName(argument));\n        }\n\n        internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument)\n        {\n            throw new ArgumentOutOfRangeException(ThrowHelper.GetArgumentName(argument));\n        }\n\n        internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)\n        {\n            throw new ArgumentOutOfRangeException(ThrowHelper.GetArgumentName(argument), (ThrowHelper.GetResourceName(resource)));\n        }\n\n        internal static void ThrowInvalidOperationException(ExceptionResource resource)\n        {\n            throw new InvalidOperationException((ThrowHelper.GetResourceName(resource)));\n        }\n\n        internal static void ThrowSerializationException(ExceptionResource resource)\n        {\n            throw new SerializationException((ThrowHelper.GetResourceName(resource)));\n        }\n\n        internal static void ThrowSecurityException(ExceptionResource resource)\n        {\n            throw new SecurityException((ThrowHelper.GetResourceName(resource)));\n        }\n\n        internal static void ThrowNotSupportedException(ExceptionResource resource)\n        {\n            throw new NotSupportedException((ThrowHelper.GetResourceName(resource)));\n        }\n\n        internal static void ThrowUnauthorizedAccessException(ExceptionResource resource)\n        {\n            throw new UnauthorizedAccessException((ThrowHelper.GetResourceName(resource)));\n        }\n\n        internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource)\n        {\n            throw new ObjectDisposedException(objectName, (ThrowHelper.GetResourceName(resource)));\n        }\n\n        internal static string GetArgumentName(ExceptionArgument argument)\n        {\n            switch (argument)\n            {\n                case ExceptionArgument.obj:\n                    return \"obj\";\n                case ExceptionArgument.dictionary:\n                    return \"dictionary\";\n                case ExceptionArgument.dictionaryCreationThreshold:\n                    return \"dictionaryCreationThreshold\";\n                case ExceptionArgument.array:\n                    return \"array\";\n                case ExceptionArgument.info:\n                    return \"info\";\n                case ExceptionArgument.key:\n                    return \"key\";\n                case ExceptionArgument.collection:\n                    return \"collection\";\n                case ExceptionArgument.list:\n                    return \"list\";\n                case ExceptionArgument.match:\n                    return \"match\";\n                case ExceptionArgument.converter:\n                    return \"converter\";\n                case ExceptionArgument.queue:\n                    return \"queue\";\n                case ExceptionArgument.stack:\n                    return \"stack\";\n                case ExceptionArgument.capacity:\n                    return \"capacity\";\n                case ExceptionArgument.index:\n                    return \"index\";\n                case ExceptionArgument.startIndex:\n                    return \"startIndex\";\n                case ExceptionArgument.value:\n                    return \"value\";\n                case ExceptionArgument.count:\n                    return \"count\";\n                case ExceptionArgument.arrayIndex:\n                    return \"arrayIndex\";\n                case ExceptionArgument.name:\n                    return \"name\";\n                case ExceptionArgument.mode:\n                    return \"mode\";\n                default:\n                    return string.Empty;\n            }\n        }\n\n        internal static string GetResourceName(ExceptionResource resource)\n        {\n            switch (resource)\n            {\n                case ExceptionResource.Argument_ImplementIComparable:\n                    return \"Argument_ImplementIComparable\";\n                case ExceptionResource.Argument_InvalidType:\n                    return \"Argument_InvalidType\";\n                case ExceptionResource.Argument_InvalidArgumentForComparison:\n                    return \"Argument_InvalidArgumentForComparison\";\n                case ExceptionResource.Argument_InvalidRegistryKeyPermissionCheck:\n                    return \"Argument_InvalidRegistryKeyPermissionCheck\";\n                case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum:\n                    return \"ArgumentOutOfRange_NeedNonNegNum\";\n                case ExceptionResource.Arg_ArrayPlusOffTooSmall:\n                    return \"Arg_ArrayPlusOffTooSmall\";\n                case ExceptionResource.Arg_NonZeroLowerBound:\n                    return \"Arg_NonZeroLowerBound\";\n                case ExceptionResource.Arg_RankMultiDimNotSupported:\n                    return \"Arg_RankMultiDimNotSupported\";\n                case ExceptionResource.Arg_RegKeyDelHive:\n                    return \"Arg_RegKeyDelHive\";\n                case ExceptionResource.Arg_RegKeyStrLenBug:\n                    return \"Arg_RegKeyStrLenBug\";\n                case ExceptionResource.Arg_RegSetStrArrNull:\n                    return \"Arg_RegSetStrArrNull\";\n                case ExceptionResource.Arg_RegSetMismatchedKind:\n                    return \"Arg_RegSetMismatchedKind\";\n                case ExceptionResource.Arg_RegSubKeyAbsent:\n                    return \"Arg_RegSubKeyAbsent\";\n                case ExceptionResource.Arg_RegSubKeyValueAbsent:\n                    return \"Arg_RegSubKeyValueAbsent\";\n                case ExceptionResource.Argument_AddingDuplicate:\n                    return \"Argument_AddingDuplicate\";\n                case ExceptionResource.Serialization_InvalidOnDeser:\n                    return \"Serialization_InvalidOnDeser\";\n                case ExceptionResource.Serialization_MissingKeyValuePairs:\n                    return \"Serialization_MissingKeyValuePairs\";\n                case ExceptionResource.Serialization_NullKey:\n                    return \"Serialization_NullKey\";\n                case ExceptionResource.Argument_InvalidArrayType:\n                    return \"Argument_InvalidArrayType\";\n                case ExceptionResource.NotSupported_KeyCollectionSet:\n                    return \"NotSupported_KeyCollectionSet\";\n                case ExceptionResource.NotSupported_ValueCollectionSet:\n                    return \"NotSupported_ValueCollectionSet\";\n                case ExceptionResource.ArgumentOutOfRange_SmallCapacity:\n                    return \"ArgumentOutOfRange_SmallCapacity\";\n                case ExceptionResource.ArgumentOutOfRange_Index:\n                    return \"ArgumentOutOfRange_Index\";\n                case ExceptionResource.Argument_InvalidOffLen:\n                    return \"Argument_InvalidOffLen\";\n                case ExceptionResource.Argument_ItemNotExist:\n                    return \"Argument_ItemNotExist\";\n                case ExceptionResource.ArgumentOutOfRange_Count:\n                    return \"ArgumentOutOfRange_Count\";\n                case ExceptionResource.ArgumentOutOfRange_InvalidThreshold:\n                    return \"ArgumentOutOfRange_InvalidThreshold\";\n                case ExceptionResource.ArgumentOutOfRange_ListInsert:\n                    return \"ArgumentOutOfRange_ListInsert\";\n                case ExceptionResource.NotSupported_ReadOnlyCollection:\n                    return \"NotSupported_ReadOnlyCollection\";\n                case ExceptionResource.InvalidOperation_CannotRemoveFromStackOrQueue:\n                    return \"InvalidOperation_CannotRemoveFromStackOrQueue\";\n                case ExceptionResource.InvalidOperation_EmptyQueue:\n                    return \"InvalidOperation_EmptyQueue\";\n                case ExceptionResource.InvalidOperation_EnumOpCantHappen:\n                    return \"InvalidOperation_EnumOpCantHappen\";\n                case ExceptionResource.InvalidOperation_EnumFailedVersion:\n                    return \"InvalidOperation_EnumFailedVersion\";\n                case ExceptionResource.InvalidOperation_EmptyStack:\n                    return \"InvalidOperation_EmptyStack\";\n                case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection:\n                    return \"ArgumentOutOfRange_BiggerThanCollection\";\n                case ExceptionResource.InvalidOperation_EnumNotStarted:\n                    return \"InvalidOperation_EnumNotStarted\";\n                case ExceptionResource.InvalidOperation_EnumEnded:\n                    return \"InvalidOperation_EnumEnded\";\n                case ExceptionResource.NotSupported_SortedListNestedWrite:\n                    return \"NotSupported_SortedListNestedWrite\";\n                case ExceptionResource.InvalidOperation_NoValue:\n                    return \"InvalidOperation_NoValue\";\n                case ExceptionResource.InvalidOperation_RegRemoveSubKey:\n                    return \"InvalidOperation_RegRemoveSubKey\";\n                case ExceptionResource.Security_RegistryPermission:\n                    return \"Security_RegistryPermission\";\n                case ExceptionResource.UnauthorizedAccess_RegistryNoWrite:\n                    return \"UnauthorizedAccess_RegistryNoWrite\";\n                case ExceptionResource.ObjectDisposed_RegKeyClosed:\n                    return \"ObjectDisposed_RegKeyClosed\";\n                case ExceptionResource.NotSupported_InComparableType:\n                    return \"NotSupported_InComparableType\";\n                default:\n                    return string.Empty;\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFCore/Utils/TimeUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * TimeUtils\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\n\n\nnamespace SGF.Utils\n{\n\n\tpublic class TimeUtils\n\t{\n     \n\n\t\treadonly static DateTime DateTime_1970_01_01_08_00_00 = new DateTime(1970, 1, 1, 8, 0, 0);\n\n\t\t//自 1970 年 1 月 1 日午夜 12:00:00 经过的毫秒数\n\t\tpublic static double GetTotalMillisecondsSince1970()\n\t\t{\n\t\t\tDateTime nowtime = DateTime.Now.ToLocalTime();\n\t\t\treturn nowtime.Subtract(DateTime_1970_01_01_08_00_00).TotalMilliseconds;\n\t\t}\n\n\t\tpublic static double GetTotalSecondsSince1970()\n\t\t{\n\t\t\tDateTime nowtime = DateTime.Now.ToLocalTime();\n\t\t\treturn nowtime.Subtract(DateTime_1970_01_01_08_00_00).TotalSeconds;\n\t\t}\n\n\n\t\tpublic static TimeSpan GetTimeSpanSince1970()\n\t\t{\n\t\t\treturn DateTime.Now.Subtract(DateTime_1970_01_01_08_00_00);\n\t\t}\n\n\t\tpublic static string FormatShowTime(ulong timeInSec)\n\t\t{\n\t\t\tstring _text = \"\";\n\t\t\tulong showTime;\n\t\t\tif ((timeInSec / (ulong)86400) > 0)\n\t\t\t{\n\t\t\t\tshowTime = timeInSec / (ulong)86400;\n\t\t\t\t_text = showTime.ToString() + \"天\";\n\t\t\t}\n\t\t\telse if ((timeInSec / (ulong)3600) > 0)\n\t\t\t{\n\t\t\t\tshowTime = timeInSec / (ulong)3600;\n\t\t\t\t_text = showTime.ToString() + \"小时\";\n\t\t\t}\n\t\t\telse if ((timeInSec / (ulong)60) > 0)\n\t\t\t{\n\t\t\t\tshowTime = timeInSec / (ulong)60;\n\t\t\t\t_text = showTime.ToString() + \"分钟\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// 对1分钟进行特殊处理, 30秒 和 1分30秒 均为1分钟\n\t\t\t\t_text = \"1分钟\";\n\t\t\t}\n\t\t\treturn _text;\n\t\t}\n\n\n\n\n\t\t//--------------------------------------------------------------------------------\n\t\tpublic const uint OnDaySecond = 24 * 60 * 60;\n\t\tpublic const uint OnHourSecond = 60 * 60;\n\n\n\t\tpublic static string GetTimeString(string format, long seconds)\n\t\t{\n\t\t\tstring label = format;\n\t\t\tint ms = (int)(seconds * 1000);\n\t\t\tint s = (int)seconds;\n\t\t\tint m = s / 60;\n\t\t\tint h = m / 60;\n\t\t\tint d = h / 24;\n\n\t\t\tstring t = \"\";\n\t\t\t//处理天\n\t\t\tif (label.IndexOf(\"%dd\") >= 0)\n\t\t\t{\n\t\t\t\tt = d >= 10 ? d.ToString() : (\"0\" + d.ToString());\n\t\t\t\tlabel = label.Replace(\"%dd\", t);\n\t\t\t\th = h % 24;\n\t\t\t}\n\t\t\telse if (label.IndexOf(\"%d\") >= 0)\n\t\t\t{\n\t\t\t\tlabel = label.Replace(\"%d\", d.ToString());\n\t\t\t\th = h % 24;\n\t\t\t}\n\n\t\t\t//处理小时\n\t\t\tif (label.IndexOf(\"%hh\") >= 0)\n\t\t\t{\n\t\t\t\tt = h >= 10 ? h.ToString() : (\"0\" + h.ToString());\n\t\t\t\tlabel = label.Replace(\"%hh\", t);\n\t\t\t\tm = m % 60;\n\t\t\t}\n\t\t\telse if (label.IndexOf(\"%h\") >= 0)\n\t\t\t{\n\t\t\t\tlabel = label.Replace(\"%h\", h.ToString());\n\t\t\t\tm = m % 60;\n\t\t\t}\n\n\t\t\t//处理分\n\t\t\tif (label.IndexOf(\"%mm\") >= 0)\n\t\t\t{\n\t\t\t\tt = m >= 10 ? m.ToString() : (\"0\" + m.ToString());\n\t\t\t\tlabel = label.Replace(\"%mm\", t);\n\t\t\t\ts = s % 60;\n\t\t\t}\n\t\t\telse if (label.IndexOf(\"%m\") >= 0)\n\t\t\t{\n\t\t\t\tlabel = label.Replace(\"%m\", m.ToString());\n\t\t\t\ts = s % 60;\n\t\t\t}\n\n\t\t\t//处理秒\n\t\t\tif (label.IndexOf(\"%ss\") >= 0)\n\t\t\t{\n\t\t\t\tt = s >= 10 ? s.ToString() : (\"0\" + s.ToString());\n\t\t\t\tlabel = label.Replace(\"%ss\", t);\n\t\t\t\tms = ms % 1000;\n\t\t\t}\n\t\t\telse if (label.IndexOf(\"%s\") >= 0)\n\t\t\t{\n\t\t\t\tlabel = label.Replace(\"%s\", s.ToString());\n\t\t\t\tms = ms % 1000;\n\t\t\t}\n\n\t\t\t//处理毫秒\n\t\t\tif (label.IndexOf(\"ms\") >= 0)\n\t\t\t{\n\t\t\t\tt = ms.ToString();\n\t\t\t\tlabel = label.Replace(\"%ms\", t);\n\t\t\t}\n\n\t\t\treturn label;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// 如果不显示天, 显示hh就会显示所有小时, 但是又怕有地方需要这样, 因此这里新开一下\n\t\t/// </summary>\n\t\t/// <param name=\"format\"></param>\n\t\t/// <param name=\"seconds\"></param>\n\t\t/// <returns></returns>\n\t\tpublic static string GetTimeStringV2(string format, long seconds)\n\t\t{\n\t\t\tstring label = format;\n\t\t\tint ms = (int)(seconds * 1000);\n\t\t\tint s = (int)seconds;\n\t\t\tint m = s / 60;\n\t\t\tint h = m / 60;\n\t\t\tint d = h / 24;\n\n\t\t\tstring t = \"\";\n\t\t\t//处理天\n\t\t\tif (label.IndexOf(\"%dd\") >= 0)\n\t\t\t{\n\t\t\t\tt = d >= 10 ? d.ToString() : (\"0\" + d.ToString());\n\t\t\t\tlabel = label.Replace(\"%dd\", t);\n\t\t\t}\n\t\t\telse if (label.IndexOf(\"%d\") >= 0)\n\t\t\t{\n\t\t\t\tlabel = label.Replace(\"%d\", d.ToString());\n\t\t\t}\n\t\t\th = h % 24;\n\n\t\t\t//处理小时\n\t\t\tif (label.IndexOf(\"%hh\") >= 0)\n\t\t\t{\n\t\t\t\tt = h >= 10 ? h.ToString() : (\"0\" + h.ToString());\n\t\t\t\tlabel = label.Replace(\"%hh\", t);\n\t\t\t}\n\t\t\telse if (label.IndexOf(\"%h\") >= 0)\n\t\t\t{\n\t\t\t\tlabel = label.Replace(\"%h\", h.ToString());\n\t\t\t}\n\t\t\tm = m % 60;\n\n\t\t\t//处理分\n\t\t\tif (label.IndexOf(\"%mm\") >= 0)\n\t\t\t{\n\t\t\t\tt = m >= 10 ? m.ToString() : (\"0\" + m.ToString());\n\t\t\t\tlabel = label.Replace(\"%mm\", t);\n\t\t\t}\n\t\t\telse if (label.IndexOf(\"%m\") >= 0)\n\t\t\t{\n\t\t\t\tlabel = label.Replace(\"%m\", m.ToString());\n\t\t\t}\n\t\t\ts = s % 60;\n\n\t\t\t//处理秒\n\t\t\tif (label.IndexOf(\"%ss\") >= 0)\n\t\t\t{\n\t\t\t\tt = s >= 10 ? s.ToString() : (\"0\" + s.ToString());\n\t\t\t\tlabel = label.Replace(\"%ss\", t);\n\t\t\t}\n\t\t\telse if (label.IndexOf(\"%s\") >= 0)\n\t\t\t{\n\t\t\t\tlabel = label.Replace(\"%s\", s.ToString());\n\t\t\t}\n\t\t\tms = ms % 1000;\n\n\t\t\t//处理毫秒\n\t\t\tif (label.IndexOf(\"ms\") >= 0)\n\t\t\t{\n\t\t\t\tt = ms.ToString();\n\t\t\t\tlabel = label.Replace(\"%ms\", t);\n\t\t\t}\n\n\t\t\treturn label;\n\t\t}\n\n\n\n\n\t\tpublic static DateTime GetLocalTime(uint timeStamp)\n\t\t{\n\t\t\tDateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));\n\t\t\tlong lTime = long.Parse(timeStamp + \"0000000\");\n\t\t\tTimeSpan toNow = new TimeSpan(lTime);\n\t\t\tDateTime dtResult = dtStart.Add(toNow);\n\t\t\treturn dtResult;\n\t\t}\n\n\n\t\tprivate static uint DAY_PER_YEAR = 365;\n\t\tprivate static uint DAY_PER_MONTH = 30;\n\t\tprivate static uint DAY_PER_WEEK = 7;\n\t\tpublic static string DateStringFromNow(DateTime dt)\n\t\t{\n\t\t\tTimeSpan span = DateTime.Now - dt;\n\n\t\t\tdouble year = (span.TotalDays / DAY_PER_YEAR);\n\t\t\tdouble month = (span.TotalDays / DAY_PER_MONTH);\n\t\t\tdouble week = (span.TotalDays / DAY_PER_WEEK);\n\n\t\t\tif (year > 1)\n\t\t\t{\n\t\t\t\treturn string.Format(\"{0}年前\", (int)System.Math.Floor(year));\n\t\t\t}\n\t\t\telse if (month > 1)\n\t\t\t{\n\t\t\t\treturn string.Format(\"{0}个月前\", (int)System.Math.Floor(month));\n\t\t\t}\n\t\t\telse if (week > 1)\n\t\t\t{\n\t\t\t\treturn string.Format(\"{0}周前\", (int)System.Math.Floor(week));\n\t\t\t}\n\t\t\telse if (span.TotalDays > 1)\n\t\t\t{\n\t\t\t\treturn string.Format(\"{0}天前\", (int)System.Math.Floor(span.TotalDays));\n\t\t\t}\n\t\t\telse if (span.TotalHours > 1)\n\t\t\t{\n\t\t\t\treturn string.Format(\"{0}小时前\", (int)System.Math.Floor(span.TotalHours));\n\t\t\t}\n\t\t\telse if (span.TotalMinutes > 1)\n\t\t\t{\n\t\t\t\treturn string.Format(\"{0}分钟前\", (int)System.Math.Floor(span.TotalMinutes));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn\n\t\t\t\t\t//string.Format(\"{0}秒前\", (int)Math.Floor(span.TotalSeconds));\n\t\t\t\t\t\"刚才\";\n\t\t\t}\n\t\t}\n\n\n\t    public static double GetMillisecondsFromTicks(long ticks)\n\t    {\n\t        return ticks / 10000.0f;\n\t    }\n\n\t    public static double GetSecondsFromTicks(long ticks)\n\t    {\n\t        return (ticks / 10000.0f)/1000.0f;\n\t    }\n\n    }\n}\n"
  },
  {
    "path": "SGFCore/Utils/URLUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * UrlUtils\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nnamespace SGF.Utils\n{\n    public class UrlUtils\n    {\n        public const string TAG = \"UrlUtils\";\n        public static readonly string[] UrlHeadDefine = { \"http://\", \"https://\" };\n\n        //已经单元测试通过\n        public static void SplitUrl(string url, out string head, out string host, out string port, out string path)\n        {\n            int a = url.IndexOf(\"://\");\n\n            if (a >= 0)\n            {\n                head = url.Substring(0, a + 3);\n                url = url.Substring(a + 3);\n            }\n            else\n            {\n                head = \"\";\n            }\n\n            a = url.IndexOf(\"/\");\n            if (a >= 0)\n            {\n                host = url.Substring(0, a);\n                path = url.Substring(a);\n            }\n            else\n            {\n                host = url;\n                path = \"\";\n            }\n\n            a = host.LastIndexOf(\":\");\n            if (a >= 0)\n            {\n                port = host.Substring(a + 1);\n                host = host.Substring(0, a);\n            }\n            else\n            {\n                port = \"\";\n            }\n\n            Debuger.Log(\"URLUtils\", \"SplitUrl() head=\" + head +\n                \", host=\" + host + \", port=\" + port + \", path=\" + path);\n        }\n    }\n}\n"
  },
  {
    "path": "SGFCoreTest/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// 有关程序集的一般信息由以下\n// 控制。更改这些特性值可修改\n// 与程序集关联的信息。\n[assembly: AssemblyTitle(\"SGFCoreTest\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"\")]\n[assembly: AssemblyProduct(\"SGFCoreTest\")]\n[assembly: AssemblyCopyright(\"Copyright ©  2018\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n//将 ComVisible 设置为 false 将使此程序集中的类型\n//对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型，\n//请将此类型的 ComVisible 特性设置为 true。\n[assembly: ComVisible(false)]\n\n// 如果此项目向 COM 公开，则下列 GUID 用于类型库的 ID\n[assembly: Guid(\"429de438-82f6-4e6a-a6d1-9d5b3010c893\")]\n\n// 程序集的版本信息由下列四个值组成: \n//\n//      主版本\n//      次版本\n//      生成号\n//      修订号\n//\n//可以指定所有这些值，也可以使用“生成号”和“修订号”的默认值，\n// 方法是按如下所示使用“*”: :\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "SGFCoreTest/SGFCoreTest.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{429DE438-82F6-4E6A-A6D1-9D5B3010C893}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>SGFCoreTest</RootNamespace>\n    <AssemblyName>SGFCoreTest</AssemblyName>\n    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\n    <ReferencePath>$(ProgramFiles)\\Common Files\\microsoft shared\\VSTT\\$(VisualStudioVersion)\\UITestExtensionPackages</ReferencePath>\n    <IsCodedUITest>False</IsCodedUITest>\n    <TestProjectType>UnitTest</TestProjectType>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>bin\\Debug\\</OutputPath>\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>bin\\Release\\</OutputPath>\n    <DefineConstants>TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\">\n      <RequiredTargetFramework>3.5</RequiredTargetFramework>\n    </Reference>\n  </ItemGroup>\n  <Choose>\n    <When Condition=\"('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'\">\n      <ItemGroup>\n        <Reference Include=\"Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\" />\n      </ItemGroup>\n    </When>\n    <Otherwise>\n      <ItemGroup>\n        <Reference Include=\"Microsoft.VisualStudio.QualityTools.UnitTestFramework\">\n          <Private>False</Private>\n        </Reference>\n      </ItemGroup>\n    </Otherwise>\n  </Choose>\n  <ItemGroup>\n    <Compile Include=\"TestMarshalArray.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"TestMarshalList.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\SGFCore\\SGFCore.csproj\">\n      <Project>{eeb72dfc-0fa5-44de-b75a-586f69377aa6}</Project>\n      <Name>SGFCore</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <Choose>\n    <When Condition=\"'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'\">\n      <ItemGroup>\n        <Reference Include=\"Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\n          <Private>False</Private>\n        </Reference>\n        <Reference Include=\"Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\n          <Private>False</Private>\n        </Reference>\n        <Reference Include=\"Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\n          <Private>False</Private>\n        </Reference>\n        <Reference Include=\"Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\n          <Private>False</Private>\n        </Reference>\n      </ItemGroup>\n    </When>\n  </Choose>\n  <Import Project=\"$(VSToolsPath)\\TeamTest\\Microsoft.TestTools.targets\" Condition=\"Exists('$(VSToolsPath)\\TeamTest\\Microsoft.TestTools.targets')\" />\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "SGFCoreTest/TestMarshalArray.cs",
    "content": "﻿using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing SGF.G3Lite;\nusing SGF.Marshals;\n\nnamespace SGFCoreTest\n{\n    [TestClass]\n    public class TestMarshalArray\n    {\n        [TestCleanup]\n        public void Cleanup()\n        {\n            MarshalArrayBase.Cleanup();\n        }\n\n\n        [TestMethod]\n        public void TestSetterGetterInt()\n        {\n            int count = 100;\n            MarshalArray<int> list = new MarshalArray<int>(count);\n            Assert.AreEqual(list.Length, count);\n\n            for (int i = 0; i < count; i++)\n            {\n                list[i] = i;\n            }\n\n            Assert.AreEqual(list.Length, count);\n            for (int i = 0; i < count; i++)\n            {\n                Assert.AreEqual(list[i], i);\n            }\n        }\n\n\n        [TestMethod]\n        public void TestSetterGetterFloat()\n        {\n            int count = 100;\n            MarshalArray<float> list = new MarshalArray<float>(count);\n            Assert.AreEqual(list.Length, count);\n\n            for (int i = 0; i < count; i++)\n            {\n                list[i] = i;\n            }\n\n            Assert.AreEqual(list.Length, count);\n            for (int i = 0; i < count; i++)\n            {\n                Assert.AreEqual(list[i], i);\n            }\n        }\n\n        [TestMethod]\n        public void TestSetterGetterVector()\n        {\n            int count = 100;\n            MarshalArray<Vector3> list = new MarshalArray<Vector3>(count);\n            Assert.AreEqual(list.Length, count);\n\n            for (int i = 0; i < count; i++)\n            {\n                list[i] = new Vector3(i, i, i);\n            }\n\n            Assert.AreEqual(list.Length, count);\n            for (int i = 0; i < count; i++)\n            {\n                Assert.AreEqual(list[i], new Vector3(i, i, i));\n            }\n        }\n\n        [TestMethod]\n        public void TestIndexOf()\n        {\n            int count = 100;\n            MarshalArray<Vector3> list = new MarshalArray<Vector3>(count);\n            Assert.AreEqual(list.Length, count);\n\n            for (int i = 0; i < count; i++)\n            {\n                list[i] = new Vector3(i, i, i);\n            }\n\n            int result = -1;\n\n            result = MarshalArrayBase.IndexOf(list, new Vector3(5, 5, 5), 0, list.Length);\n            Assert.AreEqual(result, 5);\n\n            result = MarshalArrayBase.IndexOf(list, new Vector3(5, 5, 5), 5, list.Length);\n            Assert.AreEqual(result, 5);\n\n            result = MarshalArrayBase.IndexOf(list, new Vector3(5, 5, 5), 6, list.Length);\n            Assert.AreEqual(result, -1);\n\n            result = MarshalArrayBase.IndexOf(list, new Vector3(5, 5, 5), 5, 1);\n            Assert.AreEqual(result, 5);\n\n            result = MarshalArrayBase.IndexOf(list, new Vector3(5, 5, 5), 5, 0);\n            Assert.AreEqual(result, -1);\n\n            result = MarshalArrayBase.IndexOf(list, new Vector3(5, 5, 5), 0, 6);\n            Assert.AreEqual(result, 5);\n\n            result = MarshalArrayBase.IndexOf(list, new Vector3(5, 5, 5), 0, 3);\n            Assert.AreEqual(result, -1);\n        }\n\n\n        [TestMethod]\n        public void TestLastIndexOf()\n        {\n            int count = 100;\n            MarshalArray<Vector3> list = new MarshalArray<Vector3>(count);\n            Assert.AreEqual(list.Length, count);\n\n            for (int i = 0; i < count; i++)\n            {\n                list[i] = new Vector3(i, i, i);\n            }\n\n            int result = -1;\n\n            result = MarshalArrayBase.LastIndexOf(list, new Vector3(5, 5, 5), 0, list.Length);\n            Assert.AreEqual(result, -1);\n\n            result = MarshalArrayBase.LastIndexOf(list, new Vector3(5, 5, 5), 5, list.Length);\n            Assert.AreEqual(result, 5);\n\n            result = MarshalArrayBase.LastIndexOf(list, new Vector3(5, 5, 5), 6, list.Length);\n            Assert.AreEqual(result, 5);\n\n            result = MarshalArrayBase.LastIndexOf(list, new Vector3(5, 5, 5), 5, 1);\n            Assert.AreEqual(result, 5);\n\n            result = MarshalArrayBase.LastIndexOf(list, new Vector3(5, 5, 5), 5, 0);\n            Assert.AreEqual(result, -1);\n\n            result = MarshalArrayBase.LastIndexOf(list, new Vector3(5, 5, 5), 0, 6);\n            Assert.AreEqual(result, -1);\n\n            result = MarshalArrayBase.LastIndexOf(list, new Vector3(5, 5, 5), 0, 3);\n            Assert.AreEqual(result, -1);\n        }\n\n        [TestMethod]\n        public void TestCopyMarshal2Marshal()\n        {\n            int count = 100;\n            MarshalArray<Vector3> list = new MarshalArray<Vector3>(count);\n            Assert.AreEqual(list.Length, count);\n\n            for (int i = 0; i < count; i++)\n            {\n                list[i] = new Vector3(i, i, i);\n            }\n\n            MarshalArray<Vector3> list2 = new MarshalArray<Vector3>(count);\n            MarshalArrayBase.Copy(list, 0, list2, 0, count);\n            Assert.AreEqual(list2.Length, count);\n            for (int i = 0; i < count; i++)\n            {\n                Assert.AreEqual(list2[i], new Vector3(i, i, i));\n            }\n\n\n            MarshalArray<Vector3> list3 = new MarshalArray<Vector3>(10);\n            MarshalArrayBase.Copy(list2, 10, list3, 5, 10);\n            Assert.AreEqual(list3[5], new Vector3(10, 10, 10));\n            Assert.AreEqual(list3[9], new Vector3(14, 14, 14));\n        }\n\n        [TestMethod]\n        public void TestCopyManaged2Marshal()\n        {\n            int count = 100;\n            MarshalArray<Vector3> list = new MarshalArray<Vector3>(count);\n            Assert.AreEqual(list.Length, count);\n\n            for (int i = 0; i < count; i++)\n            {\n                list[i] = new Vector3(i, i, i);\n            }\n\n\n            Vector3[] list2 = new Vector3[count];\n            MarshalArrayBase.Copy(list, 0, list2, 0, count);\n            Assert.AreEqual(list2.Length, count);\n            for (int i = 0; i < count; i++)\n            {\n                Assert.AreEqual(list2[i], new Vector3(i, i, i));\n            }\n\n\n            MarshalArray<Vector3> list3 = new MarshalArray<Vector3>(10);\n            MarshalArrayBase.Copy(list2, 10, list3, 5, 10);\n            Assert.AreEqual(list3[5], new Vector3(10, 10, 10));\n            Assert.AreEqual(list3[9], new Vector3(14, 14, 14));\n        }\n\n        [TestMethod]\n        public void TestCopyIntPtr2IntPtr()\n        {\n            int count = 100;\n            MarshalArray<Vector3> list = new MarshalArray<Vector3>(count);\n            Assert.AreEqual(list.Length, count);\n\n            for (int i = 0; i < count; i++)\n            {\n                list[i] = new Vector3(i, i, i);\n            }\n\n\n            MarshalArray<Vector3> list2 = new MarshalArray<Vector3>(count);\n            MarshalArrayBase.CopyBytes(list.Ptr, list.ElementSize, list2.Ptr, 0, list.ByteLength);\n            Assert.AreEqual(list2.Length, count);\n            for (int i = 0; i < count - 1; i++)\n            {\n                Assert.AreEqual(list2[i], new Vector3(i + 1, i + 1, i + 1));\n            }\n        }\n\n\n        [TestMethod]\n        public void TestForEach()\n        {\n            int count = 100;\n            MarshalArray<Vector3> list = new MarshalArray<Vector3>(count);\n            Assert.AreEqual(list.Length, count);\n\n            for (int i = 0; i < count; i++)\n            {\n                list[i] = new Vector3(i, i, i);\n            }\n\n            int j = 0;\n            foreach (var vector3 in list)\n            {\n                Assert.AreEqual(vector3, new Vector3(j, j, j));\n                j++;\n            }\n\n        }\n    }\n}\n"
  },
  {
    "path": "SGFCoreTest/TestMarshalList.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing SGF.Marshals;\n\nnamespace SGFCoreTest\n{\n    [TestClass]\n    public class TestMarshalList\n    {\n        [TestCleanup]\n        public void Cleanup()\n        {\n            MarshalArrayBase.Cleanup();\n        }\n\n\n        [TestMethod]\n        public void TestAdd()\n        {\n            MarshalList<int> list = new MarshalList<int>();\n            Assert.AreEqual(list.Capacity, 4);\n            Assert.AreEqual(list.Count, 0);\n\n            for (int i = 0; i < 10; i++)\n            {\n                list.Add(i);\n            }\n            Assert.AreEqual(list.Count, 10);\n            Assert.AreEqual(list.Capacity, 16);\n\n            for (int i = 0; i < 10; i++)\n            {\n                Assert.AreEqual(list[i], i);\n            }\n        }\n\n        [TestMethod]\n        public void TestAddRange()\n        {\n            MarshalList<int> list = new MarshalList<int>();\n            for (int i = 0; i < 100; i++)\n            {\n                list.Add(i);\n            }\n\n            MarshalList<int> list2 = new MarshalList<int>();\n            list2.AddRange(list);\n            Assert.AreEqual(list2.Count, 100);\n            for (int i = 0; i < 100; i++)\n            {\n                Assert.AreEqual(list2[i], i);\n            }\n\n            list2.AddRange(list);\n            Assert.AreEqual(list2.Count, 200);\n            for (int i = 100; i < 200; i++)\n            {\n                Assert.AreEqual(list2[i], i - 100);\n            }\n\n            list2.AddRange(list2);\n            Assert.AreEqual(list2.Count, 400);\n            for (int i = 200; i < 300; i++)\n            {\n                Assert.AreEqual(list2[i], i - 200);\n            }\n\n            int[] list3 = new int[100];\n            for (int i = 0; i < 100; i++)\n            {\n                list3[i] = 10000 + i;\n            }\n            list.AddRange(list3);\n            for (int i = 100; i < 200; i++)\n            {\n                Assert.AreEqual(list[i], 10000 + i - 100);\n            }\n\n\n            List<int> list4 = new List<int>();\n            list4.AddRange(list3);\n            list.AddRange(list4);\n            for (int i = 200; i < 300; i++)\n            {\n                Assert.AreEqual(list[i], 10000 + i - 200);\n            }\n\n        }\n\n        [TestMethod]\n        public void TestInsert()\n        {\n            MarshalList<int> list = new MarshalList<int>();\n            for (int i = 0; i < 100; i++)\n            {\n                list.Add(i);\n            }\n\n            list.Insert(100, 10001);\n            list.Insert(100, 10002);\n            Assert.AreEqual(list.Count, 102);\n            Assert.AreEqual(list[100], 10002);\n            Assert.AreEqual(list[101], 10001);\n\n            list.Insert(0, 10003);\n            Assert.AreEqual(list[0], 10003);\n            Assert.AreEqual(list[1], 0);\n            Assert.AreEqual(list[2], 1);\n            Assert.AreEqual(list[99], 98);\n            Assert.AreEqual(list[102], 10001);\n        }\n\n        [TestMethod]\n        public void TestRemove()\n        {\n            MarshalList<int> list = new MarshalList<int>();\n            for (int i = 0; i < 100; i++)\n            {\n                list.Add(i);\n            }\n\n            Assert.AreEqual(list.Remove(2), true);\n            Assert.AreEqual(list.Count, 99);\n            Assert.AreEqual(list[2], 3);\n\n            Assert.AreEqual(list.Remove(2), false);\n\n            list.RemoveAt(0);\n            Assert.AreEqual(list[0], 1);\n            list.RemoveAt(97);\n            Assert.AreEqual(list.Count, 97);\n\n            list.RemoveRange(0, 96);\n            Assert.AreEqual(list.Count, 1);\n            Assert.AreEqual(list[0], 98);\n        }\n\n        [TestMethod]\n        public void TestContains()\n        {\n            MarshalList<int> list = new MarshalList<int>();\n            for (int i = 0; i < 100; i++)\n            {\n                list.Add(i);\n            }\n\n            Assert.AreEqual(list.Contains(5), true);\n            Assert.AreEqual(list.Contains(500), false);\n        }\n\n        [TestMethod]\n        public void TestCopyToManagedArray()\n        {\n            MarshalList<int> list = new MarshalList<int>();\n            for (int i = 0; i < 100; i++)\n            {\n                list.Add(i);\n            }\n\n            int[] list1 = new int[100];\n            list.CopyTo((Array)list1, 0);\n            for (int i = 0; i < 100; i++)\n            {\n                Assert.AreEqual(list1[i], i);\n            }\n        }\n\n\n        [TestMethod]\n        public void TestForEach()\n        {\n            MarshalList<int> list = new MarshalList<int>();\n            for (int i = 0; i < 100; i++)\n            {\n                list.Add(i);\n            }\n\n            int j = 0;\n            foreach (var i in list)\n            {\n                Assert.AreEqual(i, j);\n                ++j;\n            }\n        }\n\n        [TestMethod]\n        public void TestGetRange()\n        {\n            MarshalList<int> list = new MarshalList<int>();\n            for (int i = 0; i < 100; i++)\n            {\n                list.Add(i);\n            }\n\n            var list1 = list.GetRange(50, 50);\n            Assert.AreEqual(list1.Count, 50);\n            for (int i = 0; i < 50; i++)\n            {\n                Assert.AreEqual(list1[i], i + 50);\n            }\n\n        }\n\n\n\n\n\n    }\n}\n"
  },
  {
    "path": "SGFDebuger/Debuger.cs",
    "content": "﻿////////////////////////////////////////////////////////////////////\n//                            _ooOoo_                             //\n//                           o8888888o                            //\n//                           88\" . \"88                            //\n//                           (| ^_^ |)                            //\n//                           O\\  =  /O                            //\n//                        ____/`---'\\____                         //\n//                      .'  \\\\|     |//  `.                       //\n//                     /  \\\\|||  :  |||//  \\                      //\n//                    /  _||||| -:- |||||-  \\                     //\n//                    |   | \\\\\\  -  /// |   |                     //\n//                    | \\_|  ''\\---/''  |   |                     //\n//                    \\  .-\\__  `-`  ___/-. /                     //\n//                  ___`. .'  /--.--\\  `. . ___                   //\n//                .\"\" '<  `.___\\_<|>_/___.'  >'\"\".                //\n//              | | :  `- \\`.;`\\ _ /`;.`/ - ` : | |               //\n//              \\  \\ `-.   \\_ __\\ /__ _/   .-` /  /               //\n//        ========`-.____`-.___\\_____/___.-`____.-'========       //\n//                             `=---='                            //\n//        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^      //\n//            佛祖保佑       无BUG        不修改                   //\n////////////////////////////////////////////////////////////////////\n/*\n * 描述：\n * 作者：slicol\n*/\nusing System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\n\nnamespace SGF\n{\n    public interface IDebugerConsole\n    {\n        void Log(string msg, object context = null);\n        void LogWarning(string msg, object context = null);\n        void LogError(string msg, object context = null);\n    }\n\n    public class UnityDebugerConsole : IDebugerConsole\n    {\n        private object[] m_tmpArgs = new[] { \"\" };\n        private MethodInfo m_miLog;\n        private MethodInfo m_miLogWarning;\n        private MethodInfo m_miLogError;\n\n        public UnityDebugerConsole()\n        {\n            Type type = Type.GetType(\"UnityEngine.Debug, UnityEngine\");\n            m_miLog = type.GetMethod(\"Log\", new Type[] { typeof(object) });\n            m_miLogWarning = type.GetMethod(\"LogWarning\", new Type[] { typeof(object) });\n            m_miLogError = type.GetMethod(\"LogError\", new Type[] { typeof(object) });\n\n        }\n\n        public void Log(string msg, object context = null)\n        {\n            m_tmpArgs[0] = msg;\n            m_miLog.Invoke(null, m_tmpArgs);\n        }\n\n        public void LogWarning(string msg, object context = null)\n        {\n            m_tmpArgs[0] = msg;\n            m_miLogWarning.Invoke(null, m_tmpArgs);\n        }\n\n        public void LogError(string msg, object context = null)\n        {\n            m_tmpArgs[0] = msg;\n            m_miLogError.Invoke(null, m_tmpArgs);\n        }\n    }\n\n    public class SystemColorConsole : IDebugerConsole\n    {\n        public void Log(string msg, object context = null)\n        {\n            Console.WriteLine(msg);\n        }\n\n        public void LogWarning(string msg, object context = null)\n        {\n            var old = Console.ForegroundColor;\n            Console.ForegroundColor = ConsoleColor.Yellow;\n            Console.WriteLine(msg);\n            Console.ForegroundColor = old;\n        }\n\n        public void LogError(string msg, object context = null)\n        {\n            var old = Console.ForegroundColor;\n            Console.ForegroundColor = ConsoleColor.Red;\n            Console.WriteLine(msg);\n            Console.ForegroundColor = old;\n\n        }\n    }\n\n\n    public interface ILogTag\n    {\n        string LOG_TAG { get; }\n    }\n\n    public static class Debuger\n    {\n        public static bool EnableLog = true;\n        public static bool EnableLogVerbose = false;\n        public static bool EnableTime = true;\n        public static bool EnableDate = false;\n        public static bool EnableSave = false;\n        public static bool EnableStack = false;\n        public static bool EnableErrorStack = true;\n        public static string LogFileDir = \"\";\n        public static string LogFileName = \"\";\n        public static string Prefix = \"> \";\n        public static StreamWriter LogFileWriter = null;\n        private static IDebugerConsole m_console;\n\n        public static void Init(string logFileDir = null, IDebugerConsole console = null)\n        {\n            LogFileDir = logFileDir;\n            m_console = console;\n            if (string.IsNullOrEmpty(LogFileDir))\n            {\n                string path = System.AppDomain.CurrentDomain.BaseDirectory;\n                LogFileDir = path + \"/DebugerLog/\";\n            }\n        }\n\n        public static void Internal_Log(string msg, object context = null)\n        {\n            if (m_console != null)\n            {\n                m_console.Log(msg, context);\n            }\n            else\n            {\n                Console.WriteLine(msg);\n            }\n        }\n\n        public static void Internal_LogWarning(string msg, object context = null)\n        {\n            if (m_console != null)\n            {\n                m_console.LogWarning(msg, context);\n            }\n            else\n            {\n                Console.WriteLine(msg);\n            }\n        }\n\n        public static void Internal_LogError(string msg, object context = null)\n        {\n            if (m_console != null)\n            {\n                m_console.LogError(msg, context);\n            }\n            else\n            {\n                Console.WriteLine(msg);\n            }\n        }\n\n\n        #region ////Log(...)////\n\n        //----------------------------------------------------------------------\n        //Log\n        //----------------------------------------------------------------------\n\n        public static void Log(string message = \"\")\n        {\n            if (!Debuger.EnableLog)\n            {\n                return;\n            }\n\n            message = GetLogText(GetLogCaller(true), message);\n            Internal_Log(Prefix + message);\n            LogToFile(\"[I]\" + message);\n        }\n\n        public static void Log(object message)\n        {\n            if (!Debuger.EnableLog)\n            {\n                return;\n            }\n\n            message = GetLogText(GetLogCaller(true), message.ToString());\n            Internal_Log(Prefix + message);\n            LogToFile(\"[I]\" + message);\n        }\n\n        public static void Log(string format, params object[] args)\n        {\n            if (!Debuger.EnableLog)\n            {\n                return;\n            }\n\n            string message = GetLogText(GetLogCaller(true), string.Format(format, args));\n            Internal_Log(Prefix + message);\n            LogToFile(\"[I]\" + message);\n        }\n\n        public static void Log(this ILogTag obj, string message = \"\")\n        {\n            if (!Debuger.EnableLog)\n            {\n                return;\n            }\n\n            message = GetLogText(GetLogTag(obj), GetLogCaller(), message);\n            Internal_Log(Prefix + message);\n            LogToFile(\"[I]\" + message);\n\n        }\n\n        public static void Log(this ILogTag obj, string format, params object[] args)\n        {\n            if (!Debuger.EnableLog)\n            {\n                return;\n            }\n\n            string message = GetLogText(GetLogTag(obj), GetLogCaller(), string.Format(format, args));\n            Internal_Log(Prefix + message);\n            LogToFile(\"[I]\" + message);\n        }\n\n        //----------------------------------------------------------------------\n        //LogVerbose\n        //----------------------------------------------------------------------\n        [Conditional(\"ENABLE_LOG\")]\n        public static void LogVerbose(string message = \"\")\n        {\n            if (!EnableLog || !EnableLogVerbose)\n            {\n                return;\n            }\n\n            message = GetLogText(GetLogCaller(true), message);\n            Internal_Log(Prefix + message);\n            LogToFile(\"[I]\" + message);\n        }\n\n        [Conditional(\"ENABLE_LOG\")]\n        public static void LogVerbose(object message)\n        {\n            if (!EnableLog || !EnableLogVerbose)\n            {\n                return;\n            }\n\n            message = GetLogText(GetLogCaller(true), message.ToString());\n            Internal_Log(Prefix + message);\n            LogToFile(\"[I]\" + message);\n        }\n\n        [Conditional(\"ENABLE_LOG\")]\n        public static void LogVerbose(string format, params object[] args)\n        {\n            if (!EnableLog || !EnableLogVerbose)\n            {\n                return;\n            }\n\n            string message = GetLogText(GetLogCaller(true), string.Format(format, args));\n            Internal_Log(Prefix + message);\n            LogToFile(\"[I]\" + message);\n        }\n\n\n\n        [Conditional(\"ENABLE_LOG\")]\n        public static void LogVerbose(this ILogTag obj, string message = \"\")\n        {\n            if (!EnableLog || !EnableLogVerbose)\n            {\n                return;\n            }\n\n            message = GetLogText(GetLogTag(obj), GetLogCaller(), message);\n            Internal_Log(Prefix + message);\n            LogToFile(\"[I]\" + message);\n\n        }\n\n        [Conditional(\"ENABLE_LOG\")]\n        public static void LogVerbose(this ILogTag obj, string format, params object[] args)\n        {\n            if (!EnableLog || !EnableLogVerbose)\n            {\n                return;\n            }\n\n            string message = GetLogText(GetLogTag(obj), GetLogCaller(), string.Format(format, args));\n            Internal_Log(Prefix + message);\n            LogToFile(\"[I]\" + message);\n        }\n\n        //----------------------------------------------------------------------\n        //LogWarning\n        //----------------------------------------------------------------------\n\n        public static void LogWarning(string message)\n        {\n            message = GetLogText(GetLogCaller(true), message);\n            Internal_LogWarning(Prefix + message);\n            LogToFile(\"[W]\" + message);\n        }\n\n        public static void LogWarning(object message)\n        {\n            message = GetLogText(GetLogCaller(true), message.ToString());\n            Internal_LogWarning(Prefix + message);\n            LogToFile(\"[W]\" + message);\n        }\n\n        public static void LogWarning(string format, params object[] args)\n        {\n            string message = GetLogText(GetLogCaller(true), string.Format(format, args));\n            Internal_LogWarning(Prefix + message);\n            LogToFile(\"[W]\" + message);\n        }\n\n\n        public static void LogWarning(this ILogTag obj, string message)\n        {\n            message = GetLogText(GetLogTag(obj), GetLogCaller(), message);\n            Internal_LogWarning(Prefix + message);\n            LogToFile(\"[W]\" + message);\n        }\n\n\n        public static void LogWarning(this ILogTag obj, string format, params object[] args)\n        {\n            string message = GetLogText(GetLogTag(obj), GetLogCaller(), string.Format(format, args));\n            Internal_LogWarning(Prefix + message);\n            LogToFile(\"[W]\" + message);\n        }\n\n        //----------------------------------------------------------------------\n        //LogWarning\n        //----------------------------------------------------------------------\n\n        public static void LogError(string message)\n        {\n            message = GetLogText(GetLogCaller(true), message);\n            Internal_LogError(Prefix + message);\n            LogToFile(\"[E]\" + message, EnableErrorStack);\n        }\n\n        public static void LogError(object message)\n        {\n            message = GetLogText(GetLogCaller(true), message.ToString());\n            Internal_LogError(Prefix + message);\n            LogToFile(\"[E]\" + message, EnableErrorStack);\n        }\n\n\n        public static void LogError(string format, params object[] args)\n        {\n            string message = GetLogText(GetLogCaller(true), string.Format(format, args));\n            Internal_LogError(Prefix + message);\n            LogToFile(\"[E]\" + message, EnableErrorStack);\n        }\n\n\n        public static void LogError(this ILogTag obj, string message)\n        {\n            message = GetLogText(GetLogTag(obj), GetLogCaller(), message);\n            Internal_LogError(Prefix + message);\n            LogToFile(\"[E]\" + message, EnableErrorStack);\n        }\n\n\n        public static void LogError(this ILogTag obj, string format, params object[] args)\n        {\n            string message = GetLogText(GetLogTag(obj), GetLogCaller(), string.Format(format, args));\n            Internal_LogError(Prefix + message);\n            LogToFile(\"[E]\" + message, EnableErrorStack);\n        }\n        #endregion\n\n        //----------------------------------------------------------------------\n        //工具函数\n        //----------------------------------------------------------------------\n\n        private static string GetLogText(string tag, string methodName, string message)\n        {\n            string str = \"\";\n            if (Debuger.EnableDate)\n            {\n                DateTime now = DateTime.Now;\n                str = now.ToString(\"yyyy-MM-dd HH:mm:ss.fff\") + \" \";\n            }\n            else if (Debuger.EnableTime)\n            {\n                DateTime now = DateTime.Now;\n                str = now.ToString(\"HH:mm:ss.fff\") + \" \";\n            }\n\n            str = str + tag + \"::\" + methodName + \"() \" + message;\n            return str;\n        }\n\n        private static string GetLogText(string caller, string message)\n        {\n            string str = \"\";\n            if (Debuger.EnableDate)\n            {\n                DateTime now = DateTime.Now;\n                str = now.ToString(\"yyyy-MM-dd HH:mm:ss.fff\") + \" \";\n            }\n            else if (Debuger.EnableTime)\n            {\n                DateTime now = DateTime.Now;\n                str = now.ToString(\"HH:mm:ss.fff\") + \" \";\n            }\n\n            str = str + caller + \"() \" + message;\n            return str;\n        }\n\n\n        private static string GetLogTag(ILogTag obj)\n        {\n            return obj.LOG_TAG;\n            /*\n            ILogTag tag = obj as ILogTag;\n            if (tag != null)\n            {\n                return tag.LOG_TAG;\n            }\n            return obj.GetType().Name;\n            */\n        }\n\n        private static Assembly ms_Assembly;\n        private static string GetLogCaller(bool bIncludeClassName = false)\n        {\n            StackTrace st = new StackTrace(2, false);\n            if (st != null)\n            {\n                if (null == ms_Assembly)\n                {\n                    ms_Assembly = typeof(Debuger).Assembly;\n                }\n\n                int currStackFrameIndex = 0;\n                while (currStackFrameIndex < st.FrameCount)\n                {\n                    StackFrame oneSf = st.GetFrame(currStackFrameIndex);\n                    MethodBase oneMethod = oneSf.GetMethod();\n\n                    if (oneMethod.Module.Assembly != ms_Assembly)\n                    {\n                        if (bIncludeClassName)\n                        {\n                            return oneMethod.DeclaringType.Name + \"::\" + oneMethod.Name;\n                        }\n                        else\n                        {\n                            return oneMethod.Name;\n                        }\n                    }\n\n                    currStackFrameIndex++;\n                }\n\n            }\n\n            return \"\";\n        }\n\n\n        //----------------------------------------------------------------------\n        public static string CheckLogFileDir()\n        {\n            if (string.IsNullOrEmpty(LogFileDir))\n            {\n                Internal_LogError(\"Debuger::CheckLogFileDir() LogFileDir is NULL!\");\n                return \"\";\n            }\n\n            try\n            {\n                if (!Directory.Exists(LogFileDir))\n                {\n                    Directory.CreateDirectory(LogFileDir);\n                }\n            }\n            catch (Exception e)\n            {\n                Internal_LogError(\"Debuger::CheckLogFileDir() \" + e.Message + e.StackTrace);\n                return \"\";\n            }\n\n            return LogFileDir;\n        }\n\n\n\n        public static string GenLogFileName()\n        {\n            DateTime now = DateTime.Now;\n            string filename = now.GetDateTimeFormats('s')[0].ToString();//2005-11-05T14:06:25\n            filename = filename.Replace(\"-\", \"_\");\n            filename = filename.Replace(\":\", \"_\");\n            filename = filename.Replace(\" \", \"\");\n            filename += \".log\";\n\n            return filename;\n        }\n\n\n\n        private static void LogToFile(string message, bool EnableStack = false)\n        {\n            if (!EnableSave)\n            {\n                return;\n            }\n\n            if (LogFileWriter == null)\n            {\n                LogFileName = GenLogFileName();\n                LogFileDir = CheckLogFileDir();\n                if (string.IsNullOrEmpty(LogFileDir))\n                {\n                    return;\n                }\n\n                string fullpath = LogFileDir + LogFileName;\n                try\n                {\n                    LogFileWriter = File.AppendText(fullpath);\n                    LogFileWriter.AutoFlush = true;\n                }\n                catch (Exception e)\n                {\n                    LogFileWriter = null;\n                    Internal_LogError(\"Debuger::LogToFile() \" + e.Message + e.StackTrace);\n                    return;\n                }\n            }\n\n            if (LogFileWriter != null)\n            {\n                try\n                {\n                    LogFileWriter.WriteLine(message);\n                    if ((EnableStack || Debuger.EnableStack))\n                    {\n                        StackTrace st = new StackTrace(2, false);\n                        LogFileWriter.WriteLine(st.ToString());\n                    }\n                }\n                catch (Exception)\n                {\n                    return;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFDebuger/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// 有关程序集的一般信息由以下\n// 控制。更改这些特性值可修改\n// 与程序集关联的信息。\n[assembly: AssemblyTitle(\"Debuger\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"Microsoft\")]\n[assembly: AssemblyProduct(\"Debuger\")]\n[assembly: AssemblyCopyright(\"Copyright © Microsoft 2017\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n//将 ComVisible 设置为 false 将使此程序集中的类型\n//对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型，\n//请将此类型的 ComVisible 特性设置为 true。\n[assembly: ComVisible(false)]\n\n// 如果此项目向 COM 公开，则下列 GUID 用于类型库的 ID\n[assembly: Guid(\"dc1d8b0a-9c8c-4911-aafe-d7d958ec4044\")]\n\n// 程序集的版本信息由下列四个值组成: \n//\n//      主版本\n//      次版本\n//      生成号\n//      修订号\n//\n//可以指定所有这些值，也可以使用“生成号”和“修订号”的默认值，\n// 方法是按如下所示使用“*”: :\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "SGFDebuger/SGFDebuger.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{DC1D8B0A-9C8C-4911-AAFE-D7D958EC4044}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>SGF.Debuger</RootNamespace>\n    <AssemblyName>SGFDebuger</AssemblyName>\n    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <TargetFrameworkProfile />\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>..\\Libs\\</OutputPath>\n    <DefineConstants>TRACE;DEBUG;ENABLE_LOG;ENABLE_LOG_LOOP</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>..\\Libs\\</OutputPath>\n    <DefineConstants>TRACE;ENABLE_LOG;ENABLE_LOG_LOOP</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"Debuger.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <PropertyGroup>\n    <PostBuildEvent>$(ProjectDir)..\\Libs\\PublishLibrary.bat $(TargetName)\n</PostBuildEvent>\n  </PropertyGroup>\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "SGFServerLite/App.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <startup> \n        \n    <supportedRuntime version=\"v2.0.50727\"/></startup>\n</configuration>\n"
  },
  {
    "path": "SGFServerLite/GameServer/GameServer.cs",
    "content": "﻿using SGF.IPCWork;\nusing SGF.Network.General;\nusing SGF.Network.General.Server;\nusing SGF.Server;\n\n\nnamespace SGFServerDemo.GameServer\n{\n    public class GameServer:ServerModule\n    {\n        private NetManager m_net;\n        private IPCManager m_ipc;\n\n        public override void Start()\n        {\n            base.Start();\n\n            m_net = new NetManager();\n            m_net.Init(ConnectionType.RUDP, 2939);\n\n            m_ipc = new IPCManager();\n            m_ipc.Init(id);\n\n        }\n\n\n        public override void Tick()\n        {\n            m_net.Tick();\n            m_ipc.Tick();\n        }\n\n\n \n    }\n}"
  },
  {
    "path": "SGFServerLite/Program.cs",
    "content": "﻿using System;\nusing SGF;\nusing SGF.Server;\nusing SGF.Time;\nusing SGFServerDemo.ZoneServer;\n\nnamespace SGFServerDemo\n{\n    class Program\n    {\n        public const int SVR_ZONE = 1;\n        public const int SVR_GAME = 1;\n\n        static void Main(string[] args)\n        {\n            InitDebuger();\n\n            SGFTime.DateTimeAppStart = DateTime.Now;\n\n            ServerManager.Instance.StartServer(SVR_ZONE);\n            ServerManager.Instance.StartServer(SVR_GAME);\n\n            MainLoop.Run();\n\n            ServerManager.Instance.StopAllServer();\n            Console.WriteLine(\"GameOver\");\n            Console.ReadKey();\n        }\n\n        private static void InitDebuger()\n        {\n            Debuger.Init(AppDomain.CurrentDomain.BaseDirectory + \"/ServerLog/\");\n            Debuger.EnableLog = false;\n            Debuger.EnableSave = true;\n            Debuger.Log();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFServerLite/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// 有关程序集的一般信息由以下\n// 控制。更改这些特性值可修改\n// 与程序集关联的信息。\n[assembly: AssemblyTitle(\"SGFServerLite\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"HP Inc.\")]\n[assembly: AssemblyProduct(\"SGFServerLite\")]\n[assembly: AssemblyCopyright(\"Copyright © HP Inc. 2017\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// 将 ComVisible 设置为 false 会使此程序集中的类型\n//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型\n//请将此类型的 ComVisible 特性设置为 true。\n[assembly: ComVisible(false)]\n\n// 如果此项目向 COM 公开，则下列 GUID 用于类型库的 ID\n[assembly: Guid(\"d1acc88b-2b6e-43e5-8314-dd64c2f25aa7\")]\n\n// 程序集的版本信息由下列四个值组成: \n//\n//      主版本\n//      次版本\n//      生成号\n//      修订号\n//\n// 可以指定所有值，也可以使用以下所示的 \"*\" 预置版本号和修订号\n// 方法是按如下所示使用“*”: :\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "SGFServerLite/SGFServerDemo.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{D1ACC88B-2B6E-43E5-8314-DD64C2F25AA7}</ProjectGuid>\n    <OutputType>Exe</OutputType>\n    <RootNamespace>SGFServerDemo</RootNamespace>\n    <AssemblyName>SGFServerDemo</AssemblyName>\n    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>\n    <TargetFrameworkProfile />\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>..\\Apps\\</OutputPath>\n    <DefineConstants>TRACE;DEBUG;ENABLE_LOG</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>..\\Apps\\</OutputPath>\n    <DefineConstants>TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"protobuf-net, Version=2.0.0.668, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\Common\\protobuf-net.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"GameServer\\GameServer.cs\" />\n    <Compile Include=\"Program.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"ZoneServer\\Room\\Room.cs\" />\n    <Compile Include=\"ZoneServer\\Room\\RoomManager.cs\" />\n    <Compile Include=\"ZoneServer\\Online\\OnlineManager.cs\" />\n    <Compile Include=\"ZoneServer\\ServerContext.cs\" />\n    <Compile Include=\"ZoneServer\\ZoneServer.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"App.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Folder Include=\"Data\\\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\SGFAppCommon\\SGFAppCommon.csproj\">\n      <Project>{a1bf1b00-7cdf-4a48-8d33-98645e5df606}</Project>\n      <Name>SGFAppCommon</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\SGFCore\\SGFCore.csproj\">\n      <Project>{eeb72dfc-0fa5-44de-b75a-586f69377aa6}</Project>\n      <Name>SGFCore</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\SGFDebuger\\SGFDebuger.csproj\">\n      <Project>{dc1d8b0a-9c8c-4911-aafe-d7d958ec4044}</Project>\n      <Name>SGFDebuger</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "SGFServerLite/ZoneServer/Online/OnlineManager.cs",
    "content": "﻿using System.Diagnostics;\nusing System.Text;\nusing SGF;\nusing SGF.Network.Core;\nusing SGF.Network.Core.RPCLite;\nusing SGF.Network.General.Proto;\nusing SGF.Network.General.Server;\nusing SGF.Time;\nusing SGF.Utils;\nusing SGFAppDemo.Common.Data;\nusing SGFAppDemo.Common.Proto;\n\nnamespace SGFServerDemo.ZoneServer\n{\n    /// <summary>\n    /// 因为只是一个Demo，所以不需要注册，谁先Login，谁先占用UserName\n    /// 如果玩家掉线后，有别的玩家使用该UserName登录，则UserName会被别的玩家占用\n    /// </summary>\n    public class OnlineManager:Singleton<OnlineManager>\n    {\n\n\n        private MapList<uint, UserData> m_mapUserData;\n        \n        \n        private NetManager m_net;\n        private uint m_lastCheckTimeoutStamp;\n\n        public void Init(ServerContext context)\n        {\n            m_net = context.net;\n            m_net.SetAuthCmd(ProtoCmd.LoginReq);\n            m_net.AddListener<LoginReq>(ProtoCmd.LoginReq, OnLoginRequest);\n            m_net.AddListener<HeartBeatReq>(ProtoCmd.HeartBeatReq, OnHeartBeatRequest);\n\n            m_net.Rpc.RegisterListener(this);\n            m_mapUserData = new MapList<uint, UserData>();\n        }\n\n        public void Dump()\n        {\n  \n            StringBuilder sb = new StringBuilder();\n            UserData[] list = m_mapUserData.ToArray();\n            for (int i = 0; i < list.Length; i++)\n            {\n                sb.AppendLine(\"\\t\" + list[i].ToString());\n            }\n\n            Debuger.LogWarning(\"\\nUser ({0}):\\n{1}\", m_mapUserData.Count, sb);\n            \n        }\n\n\n\n        private void OnLoginRequest(ISession session, ProtocolHead head, LoginReq req)\n        {\n            Debuger.Log(\"session:{0}, index:{1}, name:{2}\", session.Id, head.index, req.name);\n            bool success = false;\n\n            UserData ud = GetUserData(req.name);\n            if (ud == null)\n            {\n                //正常登录\n                //这里简单地使用SessionId作为UserId\n                ud = CreateUserData(session.Id, req.name);\n                ud.svrdata.online = true;\n                ud.svrdata.lastHeartBeatTime = (uint)TimeUtils.GetTotalSecondsSince1970();\n                //session.SetAuth(ud.id);\n                session.AuthToken = ud.id;\n                success = true;\n            }\n            else\n            {\n                if (req.id == ud.id)\n                {\n                    //重新登录\n                    ud.svrdata.online = true;\n                    ud.svrdata.lastHeartBeatTime = (uint)TimeUtils.GetTotalSecondsSince1970();\n                    //session.SetAuth(ud.id);\n                    session.AuthToken = ud.id;\n                    success = true;\n\n                }\n                else\n                {\n                    //正常登录，但是尝试占用已有的名字\n                    if (!ud.svrdata.online)\n                    {\n                        //如果该名字已经离线，则可以占用\n                        ud.svrdata.online = true;\n                        ud.svrdata.lastHeartBeatTime = (uint)TimeUtils.GetTotalSecondsSince1970();\n                        //session.SetAuth(ud.id);\n                        session.AuthToken = ud.id;\n                        success = true;\n                    }\n                }\n            }\n\n            if (success)\n            {\n                LoginRsp rsp = new LoginRsp();\n                rsp.ret = ReturnCode.Success;\n                rsp.userdata = ud;\n\n                m_net.Send(session, head, ProtoCmd.LoginRsp, rsp);\n                \n            }\n            else\n            {\n                LoginRsp rsp = new LoginRsp();\n                rsp.ret = new ReturnCode(1, \"名字已经被占用了！\");\n                m_net.Send(session, head, ProtoCmd.LoginRsp, rsp);\n            }\n        }\n\n\n\n        private void OnHeartBeatRequest(ISession session, ProtocolHead head, HeartBeatReq req)\n        {\n            UserData ud = GetUserData(session.Id);\n            if (ud != null)\n            {\n                ud.svrdata.lastHeartBeatTime = (uint)TimeUtils.GetTotalSecondsSince1970();\n\n                session.Ping = req.ping;\n                HeartBeatRsp rsp = new HeartBeatRsp();\n                rsp.ret = ReturnCode.Success;\n                rsp.timestamp = req.timestamp;\n                m_net.Send(session, head, ProtoCmd.HeartBeatRsp, rsp);\n            }\n            else\n            {\n                Debuger.LogWarning(\"找不到Session 对应的UserData! session:{0}\", session);\n            }\n            \n        }\n\n\n        [RPCRequest]\n        private void Logout(ISession session)\n        {\n            \n            OnlineManager.Instance.ReleaseUserData(session.Id);\n            m_net.Rpc.Return();\n        }\n\n        public UserData CreateUserData(uint id, string name)\n        {\n            UserData data = new UserData();\n            data.name = name;\n            data.id = id;\n            data.pwd = \"\";\n            m_mapUserData.Add(id, data);\n            return data;\n        }\n\n        public void ReleaseUserData(uint id)\n        {\n            m_mapUserData.Remove(id);\n        }\n\n        public UserData GetUserData(string name)\n        {\n            int cnt = m_mapUserData.Count;\n            var list = m_mapUserData.AsList();\n            for (int i = 0; i < cnt; i++)\n            {\n                if (list[i].name == name)\n                {\n                    return list[i];\n                }\n            }\n\n            return null;\n        }\n\n        public UserData GetUserData(uint id)\n        {\n            return m_mapUserData[id];\n        }\n    }\n}"
  },
  {
    "path": "SGFServerLite/ZoneServer/Room/Room.cs",
    "content": "﻿using System.Collections.Generic;\nusing System.Text;\nusing SGF.Extension;\nusing SGF.Network.FSPLite;\nusing SGF.Network.General.Server;\nusing SGF.Utils;\nusing SGFAppDemo.Common.Data;\n\n\nnamespace SGFServerDemo.ZoneServer\n{\n    public class Room\n    {\n        private static uint ms_lastRid = 0;\n        public static uint NewRoomID()\n        {\n            return ++ms_lastRid;\n        }\n\n        private RoomData m_data;\n        public RoomData data{get { return m_data; }}\n\n\n        private DictionarySafe<uint, ISession> m_mapSession;\n\n        public override string ToString()\n        {\n            return string.Format(\"<data:{0}, sessions:{1}>\",m_data, m_mapSession.ToListString());\n        }\n\n        public string DumpString(string prefix = \"\")\n        {\n            StringBuilder sb = new StringBuilder();\n            sb.AppendFormat(\"<id:{0}, name:{1}, owner:{2}, players_count:{3}>\\n\", \n                m_data.id, m_data.name, m_data.owner, m_data.players.Count);\n\n            sb.AppendLine(prefix + \"\\tPlayerList:\");\n            for (int i = 0; i < m_data.players.Count; i++)\n            {\n                sb.AppendLine(prefix + \"\\t\" + m_data.players[i].ToString());\n            }\n\n            sb.AppendLine(prefix + \"\\tSessionList:\");\n            foreach (var session in m_mapSession)\n            {\n                sb.AppendLine(prefix + \"\\t\" + session.Value.ToString());\n            }\n\n            return sb.ToString();\n        }\n\n        public void Create(uint userId, string userName, ISession session, string roomName)\n        {\n            m_mapSession = new DictionarySafe<uint, ISession>();\n\n            m_data = new RoomData();\n            m_data.id = NewRoomID();\n            m_data.name = roomName;\n            m_data.owner = userId;\n            AddPlayer(userId, userName, session);\n        }\n\n        public void AddPlayer(uint userId, string userName, ISession session)\n        {\n            PlayerData data = GetPlayerInfoByUserId(userId);\n            if (data == null)\n            {\n                data = new PlayerData();\n                m_data.players.Add(data);\n                data.id = (uint)m_data.players.Count;\n                data.sid = session.Id;\n            }\n            data.isReady = false;\n            data.userId = userId;\n            data.name = userName;\n\n            m_mapSession[userId] = session;\n        }\n\n\n        public void RemovePlayer(uint userId)\n        {\n            int i = GetPlayerIndexByUserId(userId);\n            if (i >= 0)\n            {\n                m_data.players.RemoveAt(i);\n            }\n\n            m_mapSession.Remove(userId);\n            \n            if (userId == m_data.owner)\n            {\n                if (m_data.players.Count > 0)\n                {\n                    m_data.owner = m_data.players[0].userId;\n                }\n            }\n        }\n\n        public int GetPlayerCount()\n        {\n            return m_data.players.Count;\n        }\n        \n\n\n        private int GetPlayerIndexByUserId(uint userId)\n        {\n            for (int i = 0; i < m_data.players.Count; i++)\n            {\n                if (m_data.players[i].userId == userId)\n                {\n                    return i;\n                }\n            }\n            return -1;\n        }\n\n\n        private PlayerData GetPlayerInfoByUserId(uint userId)\n        {\n            for (int i = 0; i < m_data.players.Count; i++)\n            {\n                if (m_data.players[i].userId == userId)\n                {\n                    return m_data.players[i];\n                }\n            }\n            return null;\n        }\n\n        public ISession[] GetSessionList()\n        {\n            List<ISession> list = new List<ISession>();\n            for (int i = 0; i < m_data.players.Count; i++)\n            {\n                uint userId = m_data.players[i].userId;\n                list.Add(m_mapSession[userId]);\n            }\n\n            return list.ToArray();\n        }\n\n        public bool CanStartGame()\n        {\n            if (m_data.players.Count > 1 && IsAllReady())\n            {\n                return true;\n            }\n            return false;\n        }\n\n        public bool IsAllReady()\n        {\n            bool isAllReady = true;\n            for (int i = 0; i < m_data.players.Count; i++)\n            {\n                if (!m_data.players[i].isReady)\n                {\n                    isAllReady = false;\n                    break;\n                }\n            }\n            return isAllReady;\n        }\n\n\n        public void SetReady(uint userId, bool value)\n        {\n            var info = GetPlayerInfoByUserId(userId);\n            if (info != null)\n            {\n                info.isReady = value;\n            }\n\n        }\n\n\n        public FSPParam GetGameStartParam()\n        {\n            FSPParam param = new FSPParam();\n            return param;\n        }\n\n    }\n}"
  },
  {
    "path": "SGFServerLite/ZoneServer/Room/RoomManager.cs",
    "content": "﻿using System.Collections.Generic;\nusing System.Text;\nusing SGF;\nusing SGF.Network.Core.RPCLite;\nusing SGF.Network.FSPLite;\nusing SGF.Network.General.Server;\nusing SGF.Utils;\nusing SGFAppDemo.Common.Data;\nusing SGF.Utils;\n\n\nnamespace SGFServerDemo.ZoneServer\n{\n    public class RoomManager:Singleton<RoomManager>\n    {\n        private NetManager m_net;\n        private List<Room> m_listRoom = new List<Room>();\n\n        public void Init(ServerContext context)\n        {\n            m_net = context.net;\n            //m_net.RegisterRPCListener(this);\n            m_net.Rpc.RegisterListener(this);\n        }\n\n        public void Dump()\n        {\n            \n            StringBuilder sb = new StringBuilder();\n            Room[] list = m_listRoom.ToArray();\n            for (int i = 0; i < list.Length; i++)\n            {\n                sb.AppendLine(\"\\t\" + list[i].DumpString(\"\\t\"));\n            }\n\n            Debuger.LogWarning(\"\\nRooms ({0}):\\n{1}\", m_listRoom.Count, sb);\n            \n        }\n\n        [RPCRequest]\n        private void GetRoomList(ISession session)\n        {\n            \n            List<RoomData> list = new List<RoomData>();\n            for (int i = 0; i < m_listRoom.Count; i++)\n            {\n                list.Add(m_listRoom[i].data);\n            }\n            RoomListData data = new RoomListData();\n            data.rooms = list;\n            m_net.Rpc.Return(data);\n        }\n\n        [RPCRequest]\n        private void CreateRoom(ISession session, uint userId, string roomName)\n        {\n            Room room = new Room();\n            UserData ud = OnlineManager.Instance.GetUserData(userId);\n            room.Create(userId, ud.name, session, roomName);\n            m_listRoom.Add(room);\n\n            m_net.Rpc.Return(room.data);\n        }\n\n        [RPCRequest]\n        private void JoinRoom(ISession session, uint userId, uint roomId)\n        {\n            Room room = GetRoom(roomId);\n            if (room != null)\n            {\n                UserData ud = OnlineManager.Instance.GetUserData(userId);\n                \n                room.AddPlayer(userId, ud.name, session);\n                ISession[] listSession = room.GetSessionList();\n                m_net.Rpc.Invoke(listSession,\"NotifyRoomUpdate\", room.data);\n            }\n            else\n            {\n                m_net.Rpc.ReturnError(\"房间不存在\", (int)roomId);\n            }\n        }\n\n\n        [RPCRequest]\n        private void ExitRoom(ISession session, uint userId, uint roomId)\n        {\n            Room room = GetRoom(roomId);\n            if (room != null)\n            {\n                room.RemovePlayer(userId);\n\n                if (room.GetPlayerCount() > 0)\n                {\n                    ISession[] listSession = room.GetSessionList();\n                    m_net.Rpc.Invoke(listSession, \"NotifyRoomUpdate\", room.data);\n                }\n            }\n        }\n\n        [RPCRequest]\n        private void RoomReady(ISession session, uint userId, uint roomId,  bool ready)\n        {\n            Room room = GetRoom(roomId);\n            if (room != null)\n            {\n                room.SetReady(userId, ready);\n                ISession[] listSession = room.GetSessionList();\n                m_net.Rpc.Invoke(listSession, \"NotifyRoomUpdate\", room.data);\n            }\n            else\n            {\n                m_net.Rpc.ReturnError(\"房间不存在\", (int)roomId);\n            }\n        }\n\n\n        [RPCRequest]\n        private void StartGame(ISession session, uint userId, uint roomId)\n        {\n            Room room = GetRoom(roomId);\n            if (room != null)\n            {\n                if (room.data.owner == userId)\n                {\n                    if (room.CanStartGame())\n                    {\n                        FSPParam param = room.GetGameStartParam();\n                        ISession[] listSession = room.GetSessionList();\n                        m_net.Rpc.Invoke(listSession, \"NotifyGameStart\", param);\n                    }\n                }\n            }\n            else\n            {\n                m_net.Rpc.ReturnError(\"房间不存在\", (int)roomId);\n            }\n        }\n\n\n        private Room GetRoom(uint id)\n        {\n            for (int i = 0; i < m_listRoom.Count; i++)\n            {\n                if (m_listRoom[i].data.id == id)\n                {\n                    return m_listRoom[i];\n                }\n            }\n            return null;\n        }\n\n    }\n}\n"
  },
  {
    "path": "SGFServerLite/ZoneServer/ServerContext.cs",
    "content": "﻿using SGF.IPCWork;\nusing SGF.Network.General.Server;\n\nnamespace SGFServerDemo.ZoneServer\n{\n\n    public class ServerContext\n    {\n        \n\n        public NetManager net;\n        public IPCManager ipc;\n    }\n}"
  },
  {
    "path": "SGFServerLite/ZoneServer/ZoneServer.cs",
    "content": "﻿using System;\nusing SGF;\nusing SGF.IPCWork;\nusing SGF.Network.General;\nusing SGF.Network.General.Server;\nusing SGF.Server;\nusing SGF.Utils;\n\nnamespace SGFServerDemo.ZoneServer\n{\n    \n\n    public class ZoneServer : ServerModule\n    {\n        private NetManager m_net;\n        private IPCManager m_ipc;\n        private ServerContext m_context;\n\n        public override void Start()\n        {\n            base.Start();\n\n            m_net = new NetManager();\n            m_net.Init(ConnectionType.RUDP, 4540);\n\n            m_ipc = new IPCManager();\n            m_ipc.Init(id);\n\n            m_context = new ServerContext();\n            m_context.net = m_net;\n            m_context.ipc = m_ipc;\n\n            //业务逻辑初始化\n            OnlineManager.Instance.Init(m_context);\n            RoomManager.Instance.Init(m_context);\n\n            ConsoleInput.onInputLine.AddListener(OnInputLine);\n            ConsoleInput.onInputKey.AddListener(OnInputKey);\n        }\n\n\n        public override void Tick()\n        {\n            m_net.Tick();\n            m_ipc.Tick();\n        }\n\n        private void OnInputKey(ConsoleKey key)\n        {\n            Debuger.Log(key);\n            if (key == ConsoleKey.F1)\n            {\n                m_net.Dump();\n            }\n            else if (key == ConsoleKey.F2)\n            {\n                OnlineManager.Instance.Dump();\n            }\n            else if (key == ConsoleKey.F3)\n            {\n                RoomManager.Instance.Dump();\n            }\n            else if (key == ConsoleKey.F4)\n            {\n                m_net.Dump();\n                OnlineManager.Instance.Dump();\n                RoomManager.Instance.Dump();\n            }\n        }\n\n        private void OnInputLine(string line)\n        {\n            Debuger.Log(line);\n            if (line == \"dump\")\n            {\n                m_net.Dump();\n                OnlineManager.Instance.Dump();\n                RoomManager.Instance.Dump();\n                \n            }\n        }\n    }\n\n}"
  },
  {
    "path": "SGFUnity/Class1.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace SGFUnity\n{\n    public class Class1\n    {\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Common/AppPrefs.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * AppPrefs\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing UnityEngine;\n\nnamespace SGF.Unity.Common\n{\n    public class AppPrefs\n    {\n        private static string ms_prefix = \"\";\n        public static void Init(string keyPrefix)\n        {\n            ms_prefix = keyPrefix;\n        }\n\n        public static float GetFloat(string key)\n        {\n            return PlayerPrefs.GetFloat(GetKey(key));\n        }\n\n        //\n        public static float GetFloat(string key, float defaultValue)\n        {\n            return PlayerPrefs.GetFloat(GetKey(key), defaultValue);\n        }\n\n        public static int GetInt(string key)\n        {\n            return PlayerPrefs.GetInt(GetKey(key));\n        }\n\n        //\n        public static int GetInt(string key, int defaultValue)\n        {\n            return PlayerPrefs.GetInt(GetKey(key), defaultValue);\n        }\n\n        //\n        public static string GetString(string key)\n        {\n            return PlayerPrefs.GetString(GetKey(key));\n        }\n\n        //\n        public static string GetString(string key, string defaultValue)\n        {\n            return PlayerPrefs.GetString(GetKey(key), defaultValue);\n        }\n\n        //\n        public static bool HasKey(string key)\n        {\n            return PlayerPrefs.HasKey(GetKey(key));\n        }\n\n        //\n        public static void SetFloat(string key, float value)\n        {\n            PlayerPrefs.SetFloat(GetKey(key), value);\n        }\n\n        //\n        public static void SetInt(string key, int value)\n        {\n            PlayerPrefs.SetInt(GetKey(key), value);\n        }\n\n        //\n        public static void SetString(string key, string value)\n        {\n            PlayerPrefs.SetString(GetKey(key), value);\n        }\n\n        public static void DeleteAll()\n        {\n            PlayerPrefs.DeleteAll();\n        }\n\n        //\n        public static void DeleteKey(string key)\n        {\n            PlayerPrefs.DeleteKey(key);\n        }\n\n        public static void Save()\n        {\n            PlayerPrefs.Save();\n        }\n\n        public static string GetKey(string key)\n        {\n            return ms_prefix + \"_\" + key;\n        }\n    }\n}\n\n"
  },
  {
    "path": "SGFUnity/Common/DelayInvoker.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * DelayInvoker\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing UnityEngine;\nusing System.Collections;\n\nnamespace SGF.Unity.Common\n{\n\n    public delegate void DelayFunction(object[] args);\n\n    public class DelayInvoker : MonoSingleton<DelayInvoker>\n    {\n        private List<DelayHelper> m_lstHelper;\n        private List<DelayHelper> m_lstUnscaledHelper;\n        private static WaitForEndOfFrame ms_waitForEndOfFrame = new WaitForEndOfFrame();\n\n\n        class DelayHelper\n        {\n            public object group;\n            public float delay;\n            public DelayFunction func;\n            public object[] args;\n\n            public void Invoke()\n            {\n                if (func != null)\n                {\n                    try\n                    {\n                        func(args);\n                    }\n                    catch(Exception e)\n                    {\n                        Debuger.LogError(\"DelayInvoker\", \"Invoke() Error:{0}\\n{1}\", e.Message, e.StackTrace);\n                    }\n                    \n                }\n            }\n        }\n\n        public static void DelayInvoke(object group, float delay, DelayFunction func, params object[] args)\n        {\n            DelayInvoker.Instance.DelayInvokeWorker(group, delay, func, args);\n        }\n\n\n        public static void DelayInvoke(float delay, DelayFunction func, params object[] args)\n        {\n            DelayInvoker.Instance.DelayInvokeWorker(null, delay, func, args);\n        }\n\n        public static void UnscaledDelayInvoke(float delay, DelayFunction func, params object[] args)\n        {\n            DelayInvoker.Instance.UnscaledDelayInvokeWorker(null, delay, func, args);\n        }\n\n        public static void CancelInvoke(object group)\n        {\n            DelayInvoker.Instance.CancelInvokeWorker(group);\n        }\n\n        //====================================================================\n\n        private void DelayInvokeWorker(object group, float delay, DelayFunction func, params object[] args)\n        {\n            if (m_lstHelper == null)\n            {\n                m_lstHelper = new List<DelayHelper>();\n            }\n\n            DelayHelper helper = new DelayHelper();\n            helper.group = group;\n            helper.delay = delay;\n            helper.func += func;\n            helper.args = args;\n\n            m_lstHelper.Add(helper);\n        }\n\n        private void UnscaledDelayInvokeWorker(object group, float delay, DelayFunction func, params object[] args)\n        {\n            if (m_lstUnscaledHelper == null)\n            {\n                m_lstUnscaledHelper = new List<DelayHelper>();\n            }\n\n            DelayHelper helper = new DelayHelper();\n            helper.group = group;\n            helper.delay = delay;\n            helper.func += func;\n            helper.args = args;\n\n            m_lstUnscaledHelper.Add(helper);\n        }\n\n\n\n        private void CancelInvokeWorker(object group)\n        {\n            if (null != m_lstHelper)\n            {\n                if (group == null)\n                {\n\n                    for (int i = 0; i < m_lstHelper.Count; i++)\n                    {\n                        m_lstHelper[i] = null;\n                    }\n                    m_lstHelper.Clear();\n\n                    return;\n                }\n\n                for (int i = 0; i < m_lstHelper.Count(); ++i)\n                {\n\n                    DelayHelper helper = m_lstHelper[i];\n\n                    if (helper.group == group)\n                    {\n                        m_lstHelper.RemoveAt(i);\n                        i--;\n                    }\n                }\n            }\n        }\n\n        //====================================================================\n\n        void Update()\n        {\n            if (null != m_lstHelper)\n            {\n                for (int i = 0; i < m_lstHelper.Count(); ++i)\n                {\n                    DelayHelper helper = m_lstHelper[i];\n                    helper.delay -= UnityEngine.Time.deltaTime;\n                    if (helper.delay <= 0)\n                    {\n                        m_lstHelper.RemoveAt(i);\n                        i--;\n\n                        helper.Invoke();\n                    }\n                }\n            }\n\n            if (null != m_lstUnscaledHelper)\n            {\n                for (int i = 0; i < m_lstUnscaledHelper.Count(); ++i)\n                {\n                    DelayHelper helper = m_lstUnscaledHelper[i];\n                    helper.delay -= UnityEngine.Time.unscaledDeltaTime;\n                    if (helper.delay <= 0)\n                    {\n                        m_lstUnscaledHelper.RemoveAt(i);\n                        i--;\n\n                        helper.Invoke();\n                    }\n                }\n\n            }\n        }\n\n        void OnDisable()\n        {\n//            Debug.Log(\"DelayInvoker Release!!!\");\n            CancelInvoke(null);\n            this.StopAllCoroutines();\n        }\n\n        //====================================================================\n\n        public static void DelayInvokerOnEndOfFrame(DelayFunction func, params object[] args)\n        {\n            Instance.StartCoroutine(DelayInvokerOnEndOfFrameWorker(func, args));\n        }\n\n        private static IEnumerator DelayInvokerOnEndOfFrameWorker(DelayFunction func, params object[] args)\n        {\n            yield return ms_waitForEndOfFrame;\n\n            //Profiler.BeginSample(\"DelayInvoker_DelayInvokerOnEndOfFrame\");\n\n            try\n            {\n                func(args);\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(\"DelayInvoker\", \"DelayInvokerOnEndOfFrame() Error:{0}\\n{1}\", e.Message, e.StackTrace);\n            }\n\n            //Profiler.EndSample();\n        }\n\n\n        public static void FixedTimeInvoke(int hours, int minitue)\n        {\n            \n        }\n    }\n\n\n\n}"
  },
  {
    "path": "SGFUnity/Common/MonoHelper.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * MonoHelper\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections;\nusing UnityEngine;\n\nnamespace SGF.Unity.Common\n{\n    public delegate void MonoUpdaterEvent();\n\n    public class MonoHelper : MonoSingleton<MonoHelper>\n    {\n\n        //===========================================================\n\n        private event MonoUpdaterEvent UpdateEvent;\n        private event MonoUpdaterEvent FixedUpdateEvent;\n\n        public static void AddUpdateListener(MonoUpdaterEvent listener)\n        {\n            if (Instance != null)\n            {\n                Instance.UpdateEvent += listener;\n            }\n        }\n\n        public static void RemoveUpdateListener(MonoUpdaterEvent listener)\n        {\n            if (Instance != null)\n            {\n                Instance.UpdateEvent -= listener;\n            }\n        }\n\n        public static void AddFixedUpdateListener(MonoUpdaterEvent listener)\n        {\n            if (Instance != null)\n            {\n                Instance.FixedUpdateEvent += listener;\n            }\n        }\n\n        public static void RemoveFixedUpdateListener(MonoUpdaterEvent listener)\n        {\n            if (Instance != null)\n            {\n                Instance.FixedUpdateEvent -= listener;\n            }\n        }\n\n        void Update()\n        {\n            if (UpdateEvent != null)\n            {\n                try\n                {\n                    UpdateEvent();\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogError(\"MonoHelper\", \"Update() Error:{0}\\n{1}\", e.Message, e.StackTrace);\n                }\n            }\n        }\n\n        void FixedUpdate()\n        {\n            if (FixedUpdateEvent != null)\n            {\n                try\n                {\n                    FixedUpdateEvent();\n                }\n                catch (Exception e)\n                {\n                    Debuger.LogError(\"MonoHelper\", \"FixedUpdate() Error:{0}\\n{1}\", e.Message, e.StackTrace);\n                }\n            }\n        }\n\n        //===========================================================\n\n        public new static void StartCoroutine(IEnumerator routine)\n        {\n            MonoBehaviour mono = Instance;\n            mono.StartCoroutine(routine);\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Common/MonoSingleton.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Mono单例\n * MonoSingleton\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing UnityEngine;\n\nnamespace SGF.Unity.Common\n{\n\n    public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>\n\t{\n\t\tprivate static T ms_instance;\n\t\tpublic static T Instance\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tif (ms_instance == null)\n\t\t\t\t{\n\t\t\t\t\tms_instance = Instantiate();\n\t\t\t\t}\n\n\t\t\t\treturn ms_instance;\n\t\t\t}\n\t\t}\n\n\t\tprotected static T Instantiate()\n\t\t{\n\t\t\tif (ms_instance == null)\n\t\t\t{\n\t\t\t\tms_instance = (T)FindObjectOfType(typeof(T));\n\t\t\t\tif (FindObjectsOfType(typeof(T)).Length > 1)\n\t\t\t\t{\n\t\t\t\t\treturn ms_instance;\n\t\t\t\t}\n\n\t\t\t\tif (ms_instance == null)\n\t\t\t\t{\n\t\t\t\t\tGameObject singleton = new GameObject(\"[Singleton]\" + typeof(T).Name);\n\t\t\t\t\tif (singleton != null)\n\t\t\t\t\t{\n\t\t\t\t\t\tms_instance = singleton.AddComponent<T>();\n\t\t\t\t\t\tms_instance.InitSingleton();\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn ms_instance;\n\t\t}\n\n\t\tprotected virtual void InitSingleton()\n\t\t{\n\n\t\t}\n\n\t\tprivate void Awake()\n\t\t{\n\t\t\tif (ms_instance == null)\n\t\t\t{\n\t\t\t\tms_instance = this as T;\n\t\t\t}\n\t\t}\n\n\t\tpublic void OnApplicationQuit()\n\t\t{\n\t\t\tms_instance = null;\n\t\t}\n\t}\n\n\n}\n"
  },
  {
    "path": "SGFUnity/DebugerGUI/NetDebugerGUI.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * DebugerGUI\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing SGF.Network;\nusing SGF.Network.protocol;\nusing SGF.Unity.UI.SGUI;\nusing SGF.Utils;\nusing UnityEngine;\n\nnamespace SGF.Unity.DebugerGUI\n{\n    public class NetDebugerGUI\n    {\n        public const string TAG = \"NetDebugerGUI\";\n\n\n        private static bool m_UseRealtimeProfile = false;\n\n        private static string m_dbgFileName = \"\";\n\n        public static void Init()\n        {\n            NetDebuger.EnableLog = NetDebuger.EnableLog;\n            SGFDebugerGUI.AddDbgGUI(\"NetDebuger\", OnDbgGUI);\n        }\n\n\n\n        private static void OnDbgGUI()\n        {\n            NetDebuger.EnableLog = GUILayout.Toggle(NetDebuger.EnableLog, \"NetDebuger.EnableLog\");\n\n            GUILayout.BeginHorizontal();\n            {\n                GUILayout.BeginVertical();\n                {        \n                    NetDebuger.EnableProfiler = GUILayout.Toggle(NetDebuger.EnableProfiler, \"NetDebuger.EnableProfiler\");\n                    if (NetDebuger.EnableProfiler)\n                    {\n                        OnDbgGUI_ProfilerControl();\n                    }\n                }\n                GUILayout.EndVertical();\n\n                GUILayout.BeginVertical();\n                {\n                    NetDebuger.EnableWeakNet = GUILayout.Toggle(NetDebuger.EnableWeakNet, \"NetDebuger.EnableWeakNet\");\n                    if (NetDebuger.EnableWeakNet)\n                    {\n                        OnDbgGUI_WeakNetControl();\n                    }\n                }\n                GUILayout.EndVertical();\n            }\n            GUILayout.EndHorizontal();\n\n            GUILayout.Space(5);\n            GUILayout.Box(\"\", GUILayout.Height(1));\n\n            GUILayout.BeginHorizontal();\n            {\n                if (m_UseRealtimeProfile)\n                {\n                    Color old = GUI.color;\n                    GUI.color = Color.red;\n                    GUILayout.Button(\"Realtime Profiler\");\n                    GUI.color = old;\n                    if (GUILayout.Button(\"Offline Profiler\"))\n                    {\n                        m_UseRealtimeProfile = false;\n                    }\n                }\n                else\n                {\n                    if (GUILayout.Button(\"Realtime Profiler\"))\n                    {\n                        m_UseRealtimeProfile = true;\n                    }\n                    Color old = GUI.color;\n                    GUI.color = Color.red;\n                    GUILayout.Button(\"Offline Profiler\");\n                    GUI.color = old;\n                }\n\n            }\n            GUILayout.EndHorizontal();\n\n            if (m_UseRealtimeProfile)\n            {\n                OnDbgGUI_RealtimeProfiler();\n            }\n            else\n            {\n                OnDbgGUI_OfflineProfiler();    \n            }\n\n        }\n\n        private static void OnDbgGUI_ProfilerControl()\n        {\n            if (GUILayout.Button(\"Clear Profiler Cache\"))\n            {\n                NetDebuger.ClearSample();\n                m_dbgFileName = null;\n            }\n\n            if (string.IsNullOrEmpty(m_dbgFileName))\n            {\n                m_dbgFileName = GetDefaultFileName();\n            }\n\n            GUILayout.Label(\"Input Profiler FileName:\");\n            m_dbgFileName = GUILayout.TextField(m_dbgFileName);\n\n            if (GUILayout.Button(\"Save Profiler File\"))\n            {\n                NetDebugFile file = new NetDebugFile();\n                file.Content.profiler_samples.AddRange(NetDebuger.SampleList);\n                file.Save(NetDebuger.DbgFileDir, m_dbgFileName);\n\n                NetDebuger.ClearSample();\n                m_dbgFileName = null;\n\n                CheckFileList();\n            }\n        }\n\n        private static void OnDbgGUI_WeakNetControl()\n        {\n            GUILayout.Label(\"Packet Loss Rate: \" + (int)(NetDebuger.PacketLossRate * 100) + \"%\");\n            NetDebuger.PacketLossRate = GUILayout.HorizontalSlider(NetDebuger.PacketLossRate, 0, 1f);\n\n            GUILayout.Label(\"Jitter Rate: \" + (int)(NetDebuger.JitterRate * 100) + \"%\");\n            NetDebuger.JitterRate = GUILayout.HorizontalSlider(NetDebuger.JitterRate, 0, 1f);\n\n            GUILayout.Label(string.Format(\"Jitter Delay: [{0} ~ {1}] ms\", NetDebuger.JitterDelayMin, NetDebuger.JitterDelayMax));\n\n            GUILayout.BeginHorizontal();\n            {\n                GUILayout.Label(\"Min:\", GUILayout.Width(50));\n                NetDebuger.JitterDelayMin = (int)GUILayout.HorizontalSlider(NetDebuger.JitterDelayMin, 0, 200);\n                if (NetDebuger.JitterDelayMin > NetDebuger.JitterDelayMax)\n                {\n                    NetDebuger.JitterDelayMin = NetDebuger.JitterDelayMax;\n                }         \n            }\n            GUILayout.EndHorizontal();\n\n            GUILayout.BeginHorizontal();\n            {\n                GUILayout.Label(\"Max:\", GUILayout.Width(50));\n                NetDebuger.JitterDelayMax = (int)GUILayout.HorizontalSlider(NetDebuger.JitterDelayMax, 0, 2000);\n                if (NetDebuger.JitterDelayMax < NetDebuger.JitterDelayMin)\n                {\n                    NetDebuger.JitterDelayMax = NetDebuger.JitterDelayMin;\n                }\n            }\n\n            GUILayout.EndHorizontal();\n        }\n\n        //========================================================================\n        //Realtime Profiler\n        private static DictionarySafe<string, GUICurve> m_mapProfileCurve;\n        private static DictionarySafe<string, List<NetSampleItem>> m_mapProfileSampleList;\n\n        private bool m_RealTimeUpdate = true;\n        private static int m_NumPerPage = 50;\n        private int m_MaxTimePerLog = 500;//MS\n        private int m_TotalCnt = 0;\n        private static int m_profileNextIndex = 0;\n\n        private static void OnDbgGUI_RealtimeProfiler()\n        {\n            if (m_mapProfileCurve == null)\n            {\n                m_mapProfileCurve = new DictionarySafe<string, GUICurve>();\n            }\n\n            if (m_mapProfileSampleList == null)\n            {\n                m_mapProfileSampleList = new DictionarySafe<string, List<NetSampleItem>>();\n            }\n\n            try\n            {\n                UpdateProfileSampleList();\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(TAG, \"OnDbgGUI_RealtimeProfiler() UpdateProfileSampleList: \" + e.Message);\n            }\n            \n\n\n            GUILayout.Label(\"每屏数据采样个数：\" + m_NumPerPage);\n            m_NumPerPage = (int)GUILayout.HorizontalSlider(m_NumPerPage, 10, 1800);\n\n            foreach (KeyValuePair<string, List<NetSampleItem>> pair in m_mapProfileSampleList)\n            {\n                string name = pair.Key;\n                GUICurve curve = m_mapProfileCurve[name];\n                bool toggle = (bool) curve.state;\n                toggle = GUILayout.Toggle(toggle, name);\n                curve.state = toggle;\n                \n                if (toggle)\n                {\n                    OnGUI_ReportProfiler(curve,pair.Value);\n                }\n            }\n        }\n\n\n\n        private static void UpdateProfileSampleList()\n        {\n            List<NetSampleItem> list = NetDebuger.SampleList;\n            int totalCnt = list.Count;\n\n            if (m_profileNextIndex > totalCnt)\n            {\n                m_mapProfileSampleList = new DictionarySafe<string, List<NetSampleItem>>();\n                m_mapProfileCurve = new DictionarySafe<string, GUICurve>();\n                m_profileNextIndex = 0;\n            }\n\n            \n            while (m_profileNextIndex < totalCnt)\n            {\n                NetSampleItem item = list[m_profileNextIndex];\n                List<NetSampleItem> listTemp = m_mapProfileSampleList[item.name];\n\n                if (listTemp == null)\n                {\n                    listTemp = new List<NetSampleItem>();\n                    m_mapProfileSampleList.Add(item.name, listTemp);\n\n                    GUICurve curve = new GUICurve();\n                    curve.state = false;\n                    m_mapProfileCurve.Add(item.name, curve);\n                }\n                listTemp.Add(item);\n\n                m_profileNextIndex++;\n            }\n        }\n\n        private static float m_profilerRangeMinY = 0;\n        private static float m_profilerRangeMaxY = 200;\n        private static void OnGUI_ReportProfiler(GUICurve curve, List<NetSampleItem> list)\n        {\n            curve.Clear();\n\n            if (list != null)\n            {\n                int beginIndex = list.Count - (int)m_NumPerPage;\n                if (beginIndex < 0)\n                {\n                    beginIndex = 0;\n                }\n\n                List<Vector2> listPoints = NetDebugerGUI.DoAnalyseBasic(list, beginIndex);\n\n                for (int i = 0; i < listPoints.Count; i++)\n                {\n                    curve.AddPoint(listPoints[i]);\n                }\n            }\n\n\n            float minY = m_profilerRangeMinY;\n            float maxY = m_profilerRangeMaxY;\n            GUILayout.Label(\"RangeY:\");\n            GUILayout.BeginHorizontal();\n            minY = GUILayout.HorizontalSlider(minY, 0, maxY);\n            maxY = GUILayout.HorizontalSlider(maxY, minY, 200);\n            GUILayout.EndHorizontal();\n            curve.SetRangeY(minY, maxY);\n            m_profilerRangeMinY = minY;\n            m_profilerRangeMaxY = maxY;\n\n\n            curve.DrawLayout(GUILayout.Height(200));\n            Rect rect = GUILayoutUtility.GetLastRect();\n            GUI.Label(rect, string.Format(\"X:[ {0} , {1} ]\\nY:[ {2} , {3} ]\", curve.MinX, curve.MaxX, curve.MinY, curve.MaxY));\n        }\n\n        //========================================================================\n        //Offline Profiler \n        #region Offline Profiler\n\n        private static List<string> m_listDbgFileName;\n        private static DictionarySafe<string, bool> m_mapDbgFileToggle;\n        private static DictionarySafe<string, NetDebugFile> m_mapDbgFile;\n        private static DictionarySafe<string, GUICurve> m_mapCurve;\n\n        private static void OnDbgGUI_OfflineProfiler()\n        {\n            if (GUILayout.Button(\"Refresh Profiler File List\"))\n            {\n                CheckFileList();\n            }\n\n            GUILayout.Label(\"File List:\");\n            if (m_listDbgFileName != null)\n            {\n                for (int i = 0; i < m_listDbgFileName.Count; i++)\n                {\n                    string filename = m_listDbgFileName[i];\n                    bool toggle = m_mapDbgFileToggle[filename];\n\n                    toggle = GUILayout.Toggle(toggle, filename);\n                    m_mapDbgFileToggle[filename] = toggle;\n\n                    if (toggle)\n                    {\n                        OnDbgGUI_AnalyseFile(filename);\n                    }\n\n                    GUILayout.Box(\"\", GUILayout.Height(2));\n                }\n            }\n        }\n\n        private static void OnDbgGUI_AnalyseFile(string filename)\n        {\n            NetDebugFile file = m_mapDbgFile[filename];\n            if (file == null)\n            {\n                file = new NetDebugFile();\n                file.Open(NetDebuger.DbgFileDir, filename);\n                m_mapDbgFile.Add(filename,file);\n            }\n\n            for (int i = 0; i < file.ListAllSampleName.Count; i++)\n            {\n                string name = file.ListAllSampleName[i];\n                GUICurve curve = m_mapCurve[filename + \">\" + name];\n\n                if (curve == null)\n                {\n                    curve = new GUICurve();\n                    curve.state = false;\n                    m_mapCurve[filename + \">\" + name] = curve;\n                }\n\n                bool toggle = (bool)curve.state;\n                toggle = GUILayout.Toggle(toggle, name);\n                curve.state = toggle;\n\n                if (toggle)\n                {\n                    OnDbgGUI_ReportFileCurve(curve, file, name);\n                }\n            }\n\n        }\n\n\n        private static void OnDbgGUI_ReportFileCurve(GUICurve curve, NetDebugFile file, string sampleName)\n        {\n            if (curve.Length == 0)\n            {\n                List<NetSampleItem> list = file.GetSampleList(sampleName);\n                List<Vector2> listPoints = DoAnalyseBasic(list);\n                curve.AddRangePoint(listPoints);\n            }\n\n            float minY = curve.MinY;\n            float maxY = curve.MaxY;\n            GUILayout.Label(\"RangeY:\");\n            GUILayout.BeginHorizontal();\n            minY = GUILayout.HorizontalSlider(minY, 0, maxY);\n            maxY = GUILayout.HorizontalSlider(maxY, minY, 200);\n            GUILayout.EndHorizontal();\n            curve.SetRangeY(minY, maxY);\n\n            curve.DrawLayout(GUILayout.Height(200));\n            Rect rect = GUILayoutUtility.GetLastRect();\n            GUI.Label(rect, string.Format(\"X:[ {0} , {1} ]\\nY:[ {2} , {3} ]\", curve.MinX, curve.MaxX, curve.MinY, curve.MaxY));\n        }\n\n        #endregion\n\n\n        //========================================================================\n        //数据处理\n\n        public static List<Vector2> DoAnalyseBasic(List<NetSampleItem> list, int beginIndex = 0, int endIndex = 0)\n        {\n            if (list == null || list.Count < 2)\n            {\n                return null;\n            }\n\n            if (beginIndex < 0 || beginIndex >= list.Count)\n            {\n                beginIndex = 0;\n            }\n\n            if (endIndex <= 0 || endIndex > list.Count)\n            {\n                endIndex = list.Count;\n            }\n\n            if (endIndex - beginIndex < 2)\n            {\n                return null;\n            }\n\n\n            List<Vector2> listPoint = new List<Vector2>();\n\n            for (int i = beginIndex; i < endIndex; i++)\n            {\n                if (list[i] == null)\n                {\n                    break;\n                }\n\n                long dtime = 0;\n\n                if (i > 0)\n                {\n                    dtime = list[i].time - list[i - 1].time;\n                }\n                else if (list.Count > 1)\n                {\n                    dtime = list[i + 1].time - list[i].time;\n                }\n\n                Vector2 v = new Vector2();\n                v.x = i;\n                v.y = dtime / 10000.0f;\n                if (v.y > 200)\n                {\n                    v.y = 200;\n                }\n                listPoint.Add(v);\n            }\n\n            return listPoint;\n        }\n\n        \n\n\n\n        //=============================================================\n        //\n        #region 工具函数\n\n        public static string GetDefaultFileName()\n        {\n            string filename;\n            DateTime now = DateTime.Now;\n            filename = \"FSPDebuger_\" + now.GetDateTimeFormats('s')[0].ToString(); //2005-11-05T14:06:25\n            filename = filename.Replace(\"-\", \"_\");\n            filename = filename.Replace(\":\", \"_\");\n            filename = filename.Replace(\" \", \"\");\n            filename += \".fsp\";\n            return filename;\n        }\n\n\n\n        private static void CheckFileList()\n        {\n            m_listDbgFileName = new List<string>();\n            m_mapDbgFileToggle = new DictionarySafe<string, bool>();\n            m_mapDbgFile = new DictionarySafe<string, NetDebugFile>();\n            m_mapCurve = new DictionarySafe<string, GUICurve>();\n\n            try\n            {\n                DirectoryInfo dirinfo = new DirectoryInfo(NetDebuger.DbgFileDir);\n\n                if (dirinfo.Exists == false)\n                {\n                    return;\n                }\n\n                FileInfo[] files = dirinfo.GetFiles(\"*\", SearchOption.TopDirectoryOnly);\n\n                for (int i = 0; i < files.Length; i++)\n                {\n                    m_listDbgFileName.Add(files[i].Name);\n                }\n\n            }\n            catch (IOException e)\n            {\n                Debuger.LogWarning(TAG, \"CheckFileList() Error：\" + e.Message);\n            }\n        }\n\n        #endregion\n\n    }\n}\n"
  },
  {
    "path": "SGFUnity/DebugerGUI/SGFDebugerGUI.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * SGFDebugerGUI\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\nusing SGF.Unity.Common;\nusing SGF.Utils;\nusing UnityEngine;\nusing UnityEngine.UI;\n\n\nnamespace SGF.Unity.DebugerGUI\n{\n\n    public class SGFDebugerGUI : SGFDebugerGUIBase\n    {\n        public const string BasePath = \"Assets/SGF/Debuger/\";\n        public const string UIBasePath = \"Assets/Resources/\";\n     \n        public const string Permission_Log = \"Log\";\n\n        #region 一个完整的SGFDebugerGUI类\n        private static SGFDebugerGUI ms_Instance;\n        \n        public new static void Show(string permission)\n        {\n\n            if (string.IsNullOrEmpty(permission))\n            {\n                return;\n            }\n\n            if (ms_Instance == null)\n            {\n                GameObject prefab = (GameObject)Resources.Load(\"SGFDebugerGUI\");\n                if (prefab != null)\n                {\n                    GameObject obj = (GameObject) Instantiate(prefab);\n                    ms_Instance = obj.GetComponent<SGFDebugerGUI>();\n                    DontDestroyOnLoad(obj);\n                }\n            }\n\n            if(ms_Instance!=null)\n            {\n                ms_Instance.EnsureLogCallback();\n                (ms_Instance as SGFDebugerGUIBase).Show(permission);\n            }\n        }\n\n        public static void Show(string openId, string permission)\n        {\n            //采用OpenId作为权限检查对象\n            if (string.IsNullOrEmpty(openId))\n            {\n                return;\n            }\n\n            permission = ValidPermissionInWhiteList(permission, openId);\n            if (string.IsNullOrEmpty(permission))\n            {\n                return;\n            }\n\n            Show(permission);\n        }\n\n        public new static void Hide()\n        {\n            if (ms_Instance != null)\n            {\n                (ms_Instance as SGFDebugerGUIBase).Hide();\n                //Destroy(ms_Instance.gameObject);\n                //ms_Instance = null;\n            }\n        }\n\n\n        #endregion\n\n        #region 白名单控制\n\n        private static readonly string[] WhiteList_Admin =\n        {\n            //Slicol\n            \"5FEF17CFD26A88F5C9349B71D3AD1DBE\",\n            \"C4FD8FAE90332C1EEF96443415127AC4\",\n            \"2383818E509286DDEF99183DB3E251D7\",\n            \"2A02EC0596D89486937A411680F9071E\",\n            \"ozwwNjxOTUPKIqEZk-hQ9pEkeTsA\",\n            \"ozwwNj3hYrjqN9mx7Yskg3UoGj1U\",\n        };\n\n        private static readonly string[] WhiteList_Log =\n        {\n\n        };\n\n\n        private static DictionarySafe<string, string[]> MapWhiteList; \n\n        private static string ValidPermissionInWhiteList(string permission, string openId)\n        {\n            if (MapWhiteList == null)\n            {\n                MapWhiteList = new DictionarySafe<string, string[]>();\n                MapWhiteList.Add(Permission_Admin, WhiteList_Admin);\n                MapWhiteList.Add(Permission_Log, WhiteList_Log);\n                \n                //TODO 新的白名单在这里增加\n            }\n\n            if (string.IsNullOrEmpty(permission))\n            {\n                bool valided = (Array.IndexOf(WhiteList_Admin, openId) >= 0);\n                if (valided)\n                {\n                    return Permission_Admin;\n                }\n\n                permission = \"\";\n\n                foreach (KeyValuePair<string, string[]> pair in MapWhiteList)\n                {\n                    valided = (Array.IndexOf(pair.Value, openId) >= 0);\n                    if (valided)\n                    {\n                        if (permission == \"\")\n                        {\n                            permission = pair.Key;\n                        }\n                        else\n                        {\n                            permission = permission + \"|\" + pair.Key;\n                        }\n                    }\n                }\n            }\n            else\n            {\n                bool valided = false;\n                if (MapWhiteList.ContainsKey(permission))\n                {\n                    valided = (Array.IndexOf(MapWhiteList[permission], openId) >= 0);\n                }\n\n                if (!valided)\n                {\n                    permission = \"\";\n                }\n            }\n\n            return permission;\n        }\n\n\n        #endregion\n\n        //=========================================================================================\n        private GUIStyle m_lowerLeftFontStyle;\n        //=========================================================================================\n\n        public Image UIMask;\n        //=========================================================================================\n        \n        override protected void Awake()\n        {\n            base.Awake();\n\n            ms_Instance = this;\n            \n            m_lowerLeftFontStyle = new GUIStyle();\n            m_lowerLeftFontStyle.clipping = TextClipping.Clip;\n            m_lowerLeftFontStyle.border = new RectOffset(0, 0, 0, 0);\n            m_lowerLeftFontStyle.normal.background = null;\n            m_lowerLeftFontStyle.fontSize = 12;\n            m_lowerLeftFontStyle.normal.textColor = Color.white;\n            m_lowerLeftFontStyle.fontStyle = FontStyle.Bold;\n            m_lowerLeftFontStyle.alignment = TextAnchor.LowerLeft;\n\n            if (UIMask != null)\n            {\n                UIMask.gameObject.SetActive(true);\n            }\n        }\n\n        protected void Start()\n        {\n            AddDbgGUI(\"日志\", OnGUI_LogToggle, Permission_Log);\n        }\n\n        public void EnsureLogCallback()\n        {\n\n        }\n\n        override protected void OnTitleGUI(Rect rect)\n        {\n\n        }\n\n        protected override void OnCustomGUI(Rect rect)\n        {\n\n        }\n\n\n        protected override void OnMaskGUI(Rect rect)\n        {\n            if (UIMask != null)\n            {\n                UIMask.rectTransform.sizeDelta = new Vector2(rect.width, rect.height);\n                UIMask.rectTransform.localPosition = new Vector3(rect.x - Screen.width/2 + rect.width/2,\n                    Screen.height/2 - rect.y - rect.height/2);\n            }\n        }\n\n\n        private Vector2 GUI2ScreenPoint(Vector2 v)\n        {\n            return new Vector2(v.x, Screen.height - v.y);\n        }\n        private Vector2 ScreenToGUIPoint(Vector2 v)\n        {\n            return new Vector2(v.x, Screen.height - v.y);\n        }\n\n\n\n        //==========================================================================================\n        //\n\n        private static string m_LogUploadTips = \"\";\n        private static string m_LogUploadUrl = \"http://101.227.153.40:8080/replay\";\n        private static bool m_IsLogUploading = false;\n        private static string m_LogReportText = \"\";\n\n        private void OnGUI_LogToggle()\n        {\n            GUILayout.BeginVertical();\n            \n            Debuger.EnableLog = GUILayout.Toggle(Debuger.EnableLog, \"Debuger.EnableLog\");\n            Debuger.EnableTime = GUILayout.Toggle(Debuger.EnableTime, \"Debuger.EnableTime\");\n            Debuger.EnableStack = GUILayout.Toggle(Debuger.EnableStack, \"Debuger.EnableStack\");\n            Debuger.EnableSave = GUILayout.Toggle(Debuger.EnableSave, \"Debuger.EnableSave\");\n\n            if (Debuger.EnableSave)\n            {\n                GUILayout.TextArea(Debuger.LogFileDir);\n                GUILayout.TextField(Debuger.LogFileName);\n\n                if (!string.IsNullOrEmpty(m_LogUploadTips))\n                {\n                    GUILayout.Label(\"Upload Tips:\" + m_LogUploadTips);\n                }\n\n                if (GUILayout.Button(\"上传日志\"))\n                {\n                    UploadLog();\n                }\n            }\n\n            GUILayout.Space(5);\n\n            if (!string.IsNullOrEmpty(m_LogReportText))\n            {\n                GUILayout.Label(\"当前日志\");\n                GUILayout.Label(m_LogReportText);\n            }\n\n            if (GUILayout.Button(\"显示或者刷新日志\"))\n            {\n                byte[] logBytes = LoadCurrentLogFile();\n                if (logBytes != null && logBytes.Length > 0)\n                {\n                    string logStr = Encoding.UTF8.GetString(logBytes);\n                    if (logStr.Length >= 15000)\n                    {\n                        m_LogReportText = logStr.Substring(logStr.Length - 15000);\n                    }\n                    else if (m_LogReportText.Length + logStr.Length >= 15000)\n                    {\n                        m_LogReportText = m_LogReportText.Substring(m_LogReportText.Length - (15000 - logStr.Length));\n                        m_LogReportText += logStr;\n                    }\n                    else\n                    {\n                        m_LogReportText += logStr;    \n                    }\n                }\n            }\n\n\n\n            GUILayout.EndVertical();\n        }\n\n        //==========================================================================================\n        #region 读取日志文本\n\n        private static byte[] LoadCurrentLogFile()\n        {\n            string fullpath = Debuger.LogFileDir + Debuger.LogFileName;\n\n            if (!File.Exists(fullpath))\n            {\n                Debuger.LogError(\"SGFDebugerGUI\", \"LoadCurrentLogFile() File Is Not Exist:\" + fullpath);\n                return null;\n            }\n\n            try\n            {\n                if (Debuger.LogFileWriter != null)\n                {\n                    Debuger.LogFileWriter.Close();\n                    Debuger.LogFileWriter = null;\n                    Debuger.LogWarning(\"SGFDebugerGUI\", \"LoadCurrentLogFile() 取出当前日志文件内容，之后的日志将存入新的日志文件！\");\n                }\n\n                byte[] bytes = FileUtils.ReadFile(fullpath);\n                return bytes;\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(\"SGFDebugerGUI\", \"LoadCurrentLogFile() Failed: \" + e.Message + e.StackTrace);\n                return null;\n            }\n\n        }\n        #endregion\n\n        //==========================================================================================\n        #region 上传日志\n        public static void UploadLog()\n        {\n            if (m_IsLogUploading)\n            {\n                m_LogUploadTips = \"正在上传中，请稍候再操作..\";\n                return;\n            }\n\n            try\n            {\n                byte[] bytes = LoadCurrentLogFile();\n\n                if (bytes != null && bytes.Length > 0)\n                {\n                    WWWForm form = new WWWForm();\n                    form.AddField(\"User\", 0);\n                    form.AddField(\"Time\", (int)TimeUtils.GetTotalSecondsSince1970());\n                    form.AddBinaryData(\"Content\", bytes);\n\n                    WWW www = new WWW(m_LogUploadUrl, form);\n                    MonoHelper.StartCoroutine(UploadLogPost(www));\n\n                    m_IsLogUploading = true;\n                }\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(\"SGFDebugerGUI\", \"Upload() Failed: \" + e.Message + e.StackTrace);\n                return;\n            }\n        }\n\n        private static IEnumerator UploadLogPost(WWW www)\n        {\n            m_LogUploadTips = \"开始上传...\";\n\n            yield return www;\n            m_IsLogUploading = false;\n\n            if (www.error != null)\n            {\n                m_LogUploadTips = \"上传失败!\";\n                Debuger.LogError(\"SGFDebugerGUI\", \"Upload() Failed: \" + www.error);\n            }\n            else\n            {\n                m_LogUploadTips = \"上传完成!\";\n                Debuger.Log(\"SGFDebugerGUI\", \"Upload() Complete!!!\");\n            }\n        }\n\n        #endregion\n    }\n\n\n}\n\n"
  },
  {
    "path": "SGFUnity/DebugerGUI/SGFDebugerGUIBase.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * SGFDebugerGUIBase\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing UnityEngine;\n\n\n\nnamespace SGF.Unity.DebugerGUI\n{\n\n    public class SGFDebugerGUIBase : MonoBehaviour\n    {\n        public const string Permission_Admin = \"Admin\";\n\t\tprivate const string PrefsKey_SelectedGUI = \"SGFDebugerGUI_SelectedGUI\";\n        class DbgGUIProxy\n        {\n            public string name;\n            public string permission;\n            public Action handler;\n        }\n\n        public static bool FullScreen = true;\n        public static bool UseBigGUI = true;\n        public static bool EnableSelectedFirst = true;\n\n        //DbgCmd系统\n        #region DbgCmd系统\n        private static Dictionary<string, DbgGUIProxy> ms_MapDbgGUI = new Dictionary<string, DbgGUIProxy>();\n        private static List<DbgGUIProxy> ms_ListDbgGUI = new List<DbgGUIProxy>();\n\n        private static string ms_SelectedGUI = null;\n\n        /// <summary>\n        /// 注册一个DbgGUI\n        /// </summary>\n        /// <param name=\"name\"></param>\n        /// <param name=\"handler\"></param>\n        /// <param name=\"permission\">默认是需要管理员权限的</param>\n        public static void AddDbgGUI(string name, Action handler, string permission = Permission_Admin)\n        {\n            if (ms_MapDbgGUI.ContainsKey(name))\n            {\n                DbgGUIProxy proxy = ms_MapDbgGUI[name];\n                proxy.handler = handler;\n                proxy.permission = permission;\n            }\n            else\n            {\n                DbgGUIProxy proxy = new DbgGUIProxy();\n                proxy.name = name;\n                proxy.permission = permission;\n                proxy.handler = handler;\n                ms_MapDbgGUI.Add(name, proxy);\n\n                if (name == ms_SelectedGUI && EnableSelectedFirst)\n                {\n                    ms_ListDbgGUI.Insert(0,proxy);\n                }\n                else\n                {\n                    ms_ListDbgGUI.Add(proxy);\n                }\n\n            }\n\n\n        }\n\n        public static void RemoveDbgGUI(string name)\n        {\n            if (ms_MapDbgGUI.ContainsKey(name))\n            {\n                if (ms_SelectedGUI == name)\n                {\n                    ms_SelectedGUI = null;\n                }\n\n                DbgGUIProxy proxy = ms_MapDbgGUI[name];\n                ms_ListDbgGUI.Remove(proxy);\n\n                ms_MapDbgGUI.Remove(name);\n            }\n        }\n        #endregion\n\n\n        //=========================================================================================\n\n        #region SGFDebugerGUI的View实现\n        private GUIStyle m_WinStyle;\n        \n        public int BaseSizeBig = 80;\n        public int BaseSizeSmall = 40;\n        private int m_BaseSize = 40;\n        public int BaseSize { get { return m_BaseSize; } }\n\n        public GUISkin GUISkinBig;\n        public GUISkin GUISkinSmall;\n        private GUISkin m_GuiSkin;\n        \n        //=========================================================================================\n        //=========================================================================================\n        public Rect WinRect;\n        public Rect WinRectMin = new Rect(0, 0, 150, 100);\n        public Rect WinRectMaxSmall = new Rect(0, 0, 500, 600);\n        public Rect WinRectMaxBig = new Rect(0, 0, 1000, 1200);\n        \n        private bool m_IsExpended = false;\n        public bool IsExpended { get { return m_IsExpended; } }\n\n        private bool m_IsVisible = false;\n        private string m_Permission = \"\";\n        //=========================================================================================\n        public static string StatusBarInfo = \"\";\n        private int m_StatusBarHeight = 40;\n        //=========================================================================================\n        \n\n        protected virtual  void Awake()\n        {\n            UpdateGUISkin();\n\n            DontDestroyOnLoad(this.gameObject);\n            WinRect = WinRectMin;\n\n            //ms_SelectedGUI = PlayerPrefs.GetString(PrefsKey_SelectedGUI, null);\n        }\n\n        private void UpdateGUISkin()\n        {\n            if (UseBigGUI)\n            {\n                m_BaseSize = BaseSizeBig;\n                m_GuiSkin = GUISkinBig;\n            }\n            else\n            {\n                m_BaseSize = BaseSizeSmall;\n                m_GuiSkin = GUISkinSmall;\n            }\n\n            WinRectMin = new Rect(0, 0, (m_BaseSize + 4) * 2, m_BaseSize+4);\n        }\n\n        //=========================================================================================\n\n        internal void Show(string permission)\n        {\n            if (m_Permission != Permission_Admin)\n            {\n                string[] tmp = permission.Split('|');\n                for (int i = 0; i < tmp.Length; i++)\n                {\n                    if (m_Permission.IndexOf(tmp[i]) < 0)\n                    {\n                        m_Permission = m_Permission + \"|\" + tmp[i];\n                    }\n                }                \n            }\n\n            m_IsVisible = true;\n\n            ms_SelectedGUI = PlayerPrefs.GetString(PrefsKey_SelectedGUI, null);\n            \n        }\n\n        internal void Hide()\n        {\n            m_IsVisible = false;\n        }\n\n        //=========================================================================================\n\n        private void OnGUI()\n        {\n            if (!m_IsVisible)\n            {\n                return;\n            }\n\n\n            if (m_WinStyle == null)\n            {\n                m_WinStyle = new GUIStyle(GUI.skin.window);\n                m_WinStyle.normal.textColor = Color.white;\n                m_WinStyle.alignment = TextAnchor.MiddleCenter;\n            }\n\n            GUI.color = Color.white;\n\n            WinRect = GUI.Window(0, WinRect, OnWindow, \"\", m_WinStyle);\n\n            OnMaskGUI(WinRect);\n            OnCustomGUI(WinRect);\n\n            OnStatusGUI();\n        }\n\n\n        private void OnWindow(int windowID)\n        {\n            getDownPos();\n\n            GUI.skin.button.fixedHeight = m_BaseSize;\n\n            if (!m_IsExpended)\n            {\n                if (GUI.Button(new Rect(2, 2, m_BaseSize, m_BaseSize), \"∨\"))\n                {\n                    m_IsExpended = true;\n                }\n\n                GUI.DragWindow(new Rect(0, 0, Screen.width, Screen.height));\n                return;\n            }\n\n\n            GUI.Box(new Rect(2, 2, WinRect.width - 4, m_BaseSize), \"\");\n\n            Rect rect = new Rect(2, 2, m_BaseSize, m_BaseSize);\n            if (GUI.Button(rect, \"∧\"))\n            {\n                WinRect.width = WinRectMin.width;\n                WinRect.height = WinRectMin.height;\n                m_IsExpended = false;\n                return;\n            }\n\n            rect.x += m_BaseSize + 2;\n            if (GUI.Button(rect, UseBigGUI ? \"小\" : \"大\"))\n            {\n                UseBigGUI = !UseBigGUI;\n                UpdateGUISkin();\n            }\n\n            rect.x += m_BaseSize + 2;\n            rect.width = (int)(m_BaseSize*1.2);\n            if (GUI.Button(rect, FullScreen ? \"全屏√\" : \"全屏 \"))\n            {\n                FullScreen = !FullScreen;\n            }\n\n            rect.x += m_BaseSize + 2;\n            rect.width = WinRect.width - 2 - rect.x;\n            OnTitleGUI(rect);\n\n            GUI.skin = m_GuiSkin;\n            OnGUI_DbgCmdSystem();\n\n            if (FullScreen)\n            {\n                WinRect.x = 0;\n                WinRect.y = 0;\n                WinRect.width = Screen.width;\n                WinRect.height = Screen.height - m_StatusBarHeight;      \n            }\n            else\n            {\n                if (UseBigGUI)\n                {\n                    WinRect.width = WinRectMaxBig.width;\n                    WinRect.height = System.Math.Min(WinRectMaxBig.height, Screen.height);    \n                }\n                else\n                {\n                    WinRect.width = WinRectMaxSmall.width;\n                    WinRect.height = System.Math.Min(WinRectMaxSmall.height, Screen.height);        \n                }\n                \n\n                //Debug.Log(m_winRect.y + \"  ... \" + downPos.y);\n                if ((Screen.height - downPos.y) - WinRect.y < m_BaseSize + 4)\n                {\n                    GUI.DragWindow(new Rect(0, 0, Screen.width, Screen.height));\n                }\n            }\n\n        }\n\n\n        protected virtual void OnCustomGUI(Rect rect)\n        {\n\n        }\n\n        protected virtual void OnMaskGUI(Rect rect)\n        {\n\n        }\n\n        protected virtual void OnTitleGUI(Rect rect)\n        {\n            \n        }\n\n        private void OnStatusGUI()\n        {\n            if (!string.IsNullOrEmpty(StatusBarInfo))\n            {\n                GUI.Label(new Rect(0, Screen.height - m_StatusBarHeight, Screen.width, m_StatusBarHeight), StatusBarInfo);\n            }\n        }\n\n        //=========================================================================================\n        //Win绘制\n        private Vector2 m_ScrollPosition_CmdList = new Vector2();\n        private Vector2 m_ScrollPosition_CmdGUI = new Vector2();\n\n        private float m_OldDrag_CmdGUI;\n        private float m_OldDrag_CmdList;\n\n        private void OnGUI_DbgCmdSystem()\n        {\n            getDownPos();\n\n            //命令列表\n            OnGUI_CmdList();\n\n            //命令内容\n            OnGUI_CmdGUI();\n        }\n\n        private void OnGUI_CmdList()\n        {\n            Rect rtCmdList = new Rect();\n            rtCmdList.x += 2;\n            rtCmdList.y += (m_BaseSize + 4);\n            rtCmdList.width = m_BaseSize*3 + 10;\n            rtCmdList.height = WinRect.height - (m_BaseSize + 4) - 2;\n            GUILayout.BeginArea(rtCmdList);\n            {\n                Vector2 drag = getDrag();\n                if (drag.y != 0 && rtCmdList.Contains(new Vector2(downPos.x - WinRect.x, Screen.height - downPos.y - WinRect.y)))\n                {\n                    m_ScrollPosition_CmdList.y += (drag.y - m_OldDrag_CmdList);\n                }\n\n                m_ScrollPosition_CmdList = GUILayout.BeginScrollView(m_ScrollPosition_CmdList);\n                {\n                    m_OldDrag_CmdList = drag.y;\n\n                    GUILayout.BeginVertical();\n                    {\n                        bool isSelectChanged = false;\n                        DbgGUIProxy newSelectProxy = null;\n                        for (int i = 0; i < ms_ListDbgGUI.Count; i++)\n                        {\n                            DbgGUIProxy proxy = ms_ListDbgGUI[i];\n                            if (m_Permission.IndexOf(Permission_Admin) >= 0 || m_Permission.IndexOf(proxy.permission) >= 0)\n                            {\n                                if (ms_SelectedGUI != proxy.name)\n                                {\n                                    if (GUILayout.Button(proxy.name, GUILayout.Width(m_BaseSize * 3 - 5), GUILayout.Height(m_BaseSize)))\n                                    {\n                                        ms_SelectedGUI = proxy.name;\n                                        isSelectChanged = true;\n                                        newSelectProxy = proxy;\n                                    }\n                                }\n                                else\n                                {\n                                    GUI.skin.box.alignment = TextAnchor.MiddleCenter;\n                                    Color oldColor = GUI.color;\n                                    GUI.color = Color.red;\n                                    GUILayout.Box(proxy.name, GUILayout.Width(m_BaseSize * 3 - 5), GUILayout.Height(m_BaseSize));\n                                    GUI.color = oldColor;\n                                }\n                            }\n\n                        }\n\n                        if (isSelectChanged)\n                        {\n                            PlayerPrefs.SetString(PrefsKey_SelectedGUI, ms_SelectedGUI);\n                            if (EnableSelectedFirst)\n                            {\n                                ms_ListDbgGUI.Remove(newSelectProxy);\n                                ms_ListDbgGUI.Insert(0, newSelectProxy);\n                            }\n                        }\n                    }\n                    GUILayout.EndVertical();\n                }\n                GUILayout.EndScrollView();\n\n\n            }\n            GUILayout.EndArea();\n        }\n\n        private void OnGUI_CmdGUI()\n        {\n            Rect rtCmdGUI = new Rect();\n            rtCmdGUI.x += m_BaseSize * 3 + 2;\n            rtCmdGUI.y += (m_BaseSize + 4);\n            rtCmdGUI.width = WinRect.width - (m_BaseSize * 3 + 2) - 2;\n            rtCmdGUI.height = WinRect.height - (m_BaseSize + 4) - 2;\n\n            GUILayout.BeginArea(rtCmdGUI);\n            {\n                Vector2 drag = getDrag();\n\n                if (drag.y != 0 && rtCmdGUI.Contains(new Vector2(downPos.x - WinRect.x, Screen.height - downPos.y - WinRect.y)))\n                {\n                    m_ScrollPosition_CmdGUI.y += (drag.y - m_OldDrag_CmdGUI);\n                }\n                m_ScrollPosition_CmdGUI = GUILayout.BeginScrollView(m_ScrollPosition_CmdGUI);\n                {\n                    m_OldDrag_CmdGUI = drag.y;\n\n                    if (ms_MapDbgGUI != null && ms_SelectedGUI != null)\n                    {\n                        if (ms_MapDbgGUI.ContainsKey(ms_SelectedGUI))\n                        {\n                            GUI.skin.button.fixedHeight = m_BaseSize;\n                            GUI.skin.toggle.fixedHeight = m_BaseSize/2;\n\n                            DbgGUIProxy proxy = ms_MapDbgGUI[ms_SelectedGUI];\n                            Action handler = proxy.handler;\n                            handler();\n                        }\n                    }\n                }\n                GUILayout.EndScrollView();\n            }\n            GUILayout.EndArea();\n        }\n\n\n\n        #region Drag相关\n\n        Vector2 mousePosition;\n        Vector2 getDrag()\n        {\n\n            if (Application.platform == RuntimePlatform.Android ||\n                Application.platform == RuntimePlatform.IPhonePlayer)\n            {\n                if (Input.touches.Length != 1)\n                {\n                    return Vector2.zero;\n                }\n                return Input.touches[0].position - downPos;\n            }\n            else\n            {\n                if (Input.GetMouseButton(0))\n                {\n                    mousePosition = Input.mousePosition;\n                    return mousePosition - downPos;\n                }\n                else\n                {\n                    return Vector2.zero;\n                }\n            }\n        }\n\n        Vector2 startPos;\n\n        Vector2 downPos;\n        Vector2 getDownPos()\n        {\n            if (Application.platform == RuntimePlatform.Android ||\n               Application.platform == RuntimePlatform.IPhonePlayer)\n            {\n\n                if (Input.touches.Length == 1 && Input.touches[0].phase == TouchPhase.Began)\n                {\n                    downPos = Input.touches[0].position;\n                    return downPos;\n                }\n            }\n            else\n            {\n                if (Input.GetMouseButtonDown(0))\n                {\n                    downPos.x = Input.mousePosition.x;\n                    downPos.y = Input.mousePosition.y;\n                    return downPos;\n                }\n            }\n\n            return Vector2.zero;\n        }\n        #endregion\n\n        //==========================================================================================\n        //\n\n        #endregion\n\n    }\n\n\n}\n\n"
  },
  {
    "path": "SGFUnity/Extension/BitmapDrawingExtensions.cs",
    "content": "﻿using System;\nusing UnityEngine;\nusing System.Collections.Generic;\n\n/**\nThe MIT License (MIT)\nCopyright (c) 2014 Lauri Hosio\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\nnamespace ProtoTurtle.BitmapDrawing\n{\n    /// <summary>\n    /// A extension class for UnityEngine.Texture2D that provides a bitmap drawing API.\n    /// Provides drawing methods line Line, Circle, Rectangle etc.\n    /// This class uses a convention of having the 0,0 point at the left-top corner!</summary>\n    /// <remarks>\n    /// Check this out for more cool middleware stuff:\n    /// http://prototurtle.com \n    /// \n    /// </remarks>\n    public static class BitmapDrawingExtensions\n    {\n        public static void Clear(this Texture2D texture)\n        {\n            Rect rect = new Rect(0, 0, texture.width, texture.height);\n            texture.DrawFilledRectangle(rect, Color.clear);\n        }\n\n\n        /// <summary>\n        /// Draws a pixel just like SetPixel except 0,0 is the left top corner.</summary>\n        public static void DrawPixel(this Texture2D texture, int x, int y, Color color)\n        {\n            if (x < 0 || x > texture.width || y < 0 || y > texture.height)\n            {\n                return;\n            }\n            texture.SetPixel(x, TransformToLeftTop_y(y, texture.height), color);\n        }\n\n        /// <summary>\n        /// Draws a pixel just like SetPixel except 0,0 is the left top corner.\n        /// Takes the width and height as parameters - faster for calling this in a loop.\n        /// </summary>\n        /// <param name=\"width\">Width of the target bitmap</param>\n        /// <param name=\"height\">Height of the target bitmap</param>\n        public static void DrawPixel(this Texture2D texture, int x, int y, int width, int height, Color color)\n        {\n            if (x < 0 || x > width || y < 0 || y > height)\n            {\n                return;\n            }\n            texture.SetPixel(x, TransformToLeftTop_y(y, height), color);\n        }\n\n        /// <summary>\n        /// Draws a circle with the midpoint being x0, x1.\n        /// Implementation of Bresenham's circle algorithm\n        /// </summary>\n        public static void DrawCircle(this Texture2D texture, int x, int y, int radius, Color color)\n        {\n            Circle(texture, x, y, radius, color, false);\n        }\n\n        /// <summary>\n        /// Draws a filled circle with the midpoint being x0, x1.\n        /// Implementation of Bresenham's circle algorithm\n        /// </summary>\n        public static void DrawFilledCircle(this Texture2D texture, int x, int y, int radius, Color color)\n        {\n            Circle(texture, x, y, radius, color, true);\n        }\n\n\n        private static void Circle(Texture2D texture, int x, int y, int radius, Color color, bool filled = false)\n        {\n            int cx = radius;\n            int cy = 0;\n            int radiusError = 1 - cx;\n\n            while (cx >= cy)\n            {\n                if (!filled)\n                {\n                    PlotCircle(texture, cx, x, cy, y, color);\n                }\n                else\n                {\n                    ScanLineCircle(texture, cx, x, cy, y, color);\n                }\n\n                cy++;\n\n                if (radiusError < 0)\n                {\n                    radiusError += 2 * cy + 1;\n                }\n                else\n                {\n                    cx--;\n                    radiusError += 2 * (cy - cx + 1);\n                }\n            }\n        }\n\n        private static void PlotCircle(Texture2D texture, int cx, int x, int cy, int y, Color color)\n        {\n            texture.DrawPixel(cx + x, cy + y, color); // Point in octant 1...\n            texture.DrawPixel(cy + x, cx + y, color);\n            texture.DrawPixel(-cx + x, cy + y, color);\n            texture.DrawPixel(-cy + x, cx + y, color);\n            texture.DrawPixel(-cx + x, -cy + y, color);\n            texture.DrawPixel(-cy + x, -cx + y, color);\n            texture.DrawPixel(cx + x, -cy + y, color);\n            texture.DrawPixel(cy + x, -cx + y, color); // ... point in octant 8\n        }\n\n        // Draw scanlines from opposite sides of the circle on y-scanlines instead of just plotting pixels\n        // at the right coordinates\n        private static void ScanLineCircle(Texture2D texture, int cx, int x, int cy, int y, Color color)\n        {\n            //texture.DrawPixel(cx + x,  cy + y, color);\n            //texture.DrawPixel(-cx + x, cy + y, color);\n            texture.DrawLine(cx + x, cy + y, -cx + x, cy + y, color);\n\n            //texture.DrawPixel(cy + x,  cx + y, color);\n            //texture.DrawPixel(-cy + x, cx + y, color);\n            texture.DrawLine(cy + x, cx + y, -cy + x, cx + y, color);\n\n            //texture.DrawPixel(-cx + x, -cy + y, color);\n            //texture.DrawPixel(cx + x,  -cy + y, color);\n            texture.DrawLine(-cx + x, -cy + y, cx + x, -cy + y, color);\n\n            //texture.DrawPixel(-cy + x, -cx + y, color);\n            //texture.DrawPixel(cy + x,  -cx + y, color);\n            texture.DrawLine(-cy + x, -cx + y, cy + x, -cx + y, color);\n        }\n\n\n        /// <summary>\n        /// Starts a flood fill at point startX, startY.\n\t\t/// This is a pretty slow flood fill, biggest bottle neck is comparing two colors which happens\n\t\t/// a lot. Should be a way to make it much faster.\n        /// O(n) space.  n = width*height - makes a copy of the bitmap temporarily in the memory\n        /// </summary>\n        /// <param name=\"texture\"></param>\n        /// <param name=\"startX\"></param>\n        /// <param name=\"startY\"></param>\n        /// <param name=\"newColor\"></param>\n        public static void FloodFill(this Texture2D texture, int startX, int startY, Color newColor)\n        {\n            Point start = new Point(startX, TransformToLeftTop_y(startY, texture.height));\n\n            Flat2DArray copyBmp = new Flat2DArray(texture.height, texture.width, texture.GetPixels());\n\n            Color originalColor = texture.GetPixel(start.X, start.Y);\n            int width = texture.width;\n            int height = texture.height;\n\n\n            if (originalColor == newColor)\n            {\n                return;\n            }\n\n            copyBmp[start.X, start.Y] = newColor;\n\n            Queue<Point> openNodes = new Queue<Point>();\n            openNodes.Enqueue(start);\n\n            int i = 0;\n\n            // TODO: remove this\n            // emergency switch so it doesn't hang if something goes wrong\n            int emergency = width * height;\n\n            while (openNodes.Count > 0)\n            {\n                i++;\n\n                if (i > emergency)\n                {\n                    return;\n                }\n\n                Point current = openNodes.Dequeue();\n                int x = current.X;\n                int y = current.Y;\n\n                if (x > 0)\n                {\n                    if (copyBmp[x - 1, y] == originalColor)\n                    {\n                        copyBmp[x - 1, y] = newColor;\n                        openNodes.Enqueue(new Point(x - 1, y));\n                    }\n                }\n                if (x < width - 1)\n                {\n                    if (copyBmp[x + 1, y] == originalColor)\n                    {\n                        copyBmp[x + 1, y] = newColor;\n                        openNodes.Enqueue(new Point(x + 1, y));\n                    }\n                }\n                if (y > 0)\n                {\n                    if (copyBmp[x, y - 1] == originalColor)\n                    {\n                        copyBmp[x, y - 1] = newColor;\n                        openNodes.Enqueue(new Point(x, y - 1));\n                    }\n                }\n                if (y < height - 1)\n                {\n                    if (copyBmp[x, y + 1] == originalColor)\n                    {\n                        copyBmp[x, y + 1] = newColor;\n                        openNodes.Enqueue(new Point(x, y + 1));\n                    }\n                }\n            }\n\n            texture.SetPixels(copyBmp.data);\n        }\n\n        // Could be its own file\n        private class Flat2DArray\n        {\n            public Color[] data;\n            private readonly int height;\n            private readonly int width;\n\n            public Flat2DArray(int height, int width, Color[] data)\n            {\n                this.height = height;\n                this.width = width;\n\n                this.data = data;\n            }\n\n            public Color this[int x, int y]\n            {\n                get\n                {\n                    return data[x + y * width];\n                }\n                set\n                {\n                    data[x + y * width] = value;\n                }\n            }\n        }\n\n        private struct Point\n        {\n            public int X;\n            public int Y;\n\n            public Point(int x, int y)\n            {\n                this.X = x;\n                this.Y = y;\n            }\n        }\n\n        /// <summary>\n        /// Draws a rectangle\n        /// </summary>\n        public static void DrawRectangle(this Texture2D texture, Rect rectangle, Color color)\n        {\n            int x = (int)rectangle.x;\n            int y = (int)rectangle.y;\n            int height = (int)rectangle.height;\n            int width = (int)rectangle.width;\n\n\n            // top left to bottom left\n            texture.DrawLine(x, y, x, y + height, color);\n\n            // bottom left to bottom right\n            texture.DrawLine(x, y + height, x + width, y + height, color);\n\n            // bottom right to top right\n            texture.DrawLine(x + width, y + height, x + width, y, color);\n\n            // top right to top left\n            texture.DrawLine(x + width, y, x, y, color);\n\n        }\n\n        /// <summary>\n        /// Fills the given rectangle area with a solid color.</summary>\n        public static void DrawFilledRectangle(this Texture2D texture, Rect rectangle, Color color)\n        {\n            Color[] colorsArray = new Color[(int)rectangle.width * (int)rectangle.height];\n            for (int i = 0; i < colorsArray.Length; i++)\n            {\n                colorsArray[i] = color;\n            }\n\n            int transformedY = TransformToLeftTop_y(rectangle.y, texture.height) - (int)rectangle.height;\n            texture.SetPixels((int)rectangle.x, transformedY,\n                (int)rectangle.width, (int)rectangle.height, colorsArray);\n        }\n\n\n\n        public static void DrawLine(this Texture2D texture, Vector3 start, Vector3 end, Color color)\n        {\n            Line(texture, (int)start.x, (int)start.y, (int)end.x, (int)end.y, color);\n        }\n\n        public static void DrawLine(this Texture2D texture, Vector2 start, Vector2 end, Color color)\n        {\n            Line(texture, (int)start.x, (int)start.y, (int)end.x, (int)end.y, color);\n        }\n\n        /// <summary>\n        /// Draws a line between two points. Implementation of Bresenham's line algorithm.\n        /// </summary>\n        /// <param name=\"x0\">x of the start point</param>\n        /// <param name=\"y0\">y of the start point</param>\n        /// <param name=\"x1\">x of the end point</param>\n        /// <param name=\"y1\">y of the end point</param>\n        public static void DrawLine(this Texture2D texture, int x0, int y0, int x1, int y1, Color color)\n        {\n            Line(texture, x0, y0, x1, y1, color);\n        }\n\n        private static void Line(Texture2D texture, int x0, int y0, int x1, int y1, Color color)\n        {\n            int width = texture.width;\n            int height = texture.height;\n\n            bool isSteep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);\n            if (isSteep)\n            {\n                Swap(ref x0, ref y0);\n                Swap(ref x1, ref y1);\n            }\n            if (x0 > x1)\n            {\n                Swap(ref x0, ref x1);\n                Swap(ref y0, ref y1);\n            }\n\n            int deltax = x1 - x0;\n            int deltay = Math.Abs(y1 - y0);\n\n            int error = deltax / 2;\n            int ystep;\n            int y = y0;\n\n            if (y0 < y1)\n                ystep = 1;\n            else\n                ystep = -1;\n\n            for (int x = x0; x < x1; x++)\n            {\n                if (isSteep)\n                    texture.DrawPixel(y, x, width, height, color);\n                else\n                    texture.DrawPixel(x, y, width, height, color);\n\n                error = error - deltay;\n                if (error < 0)\n                {\n                    y = y + ystep;\n                    error = error + deltax;\n                }\n            }\n        }\n\n\n        /// <summary>\n        /// Swap two ints by reference.\n        /// </summary>\n        private static void Swap(ref int x, ref int y)\n        {\n            int temp = x;\n            x = y;\n            y = temp;\n        }\n\n        /// <summary>\n        /// Transforms a point in the texture plane so that 0,0 points at left-top corner.</summary>\n        private static int TransformToLeftTop_y(int y, int height)\n        {\n            return height - y;\n        }\n\n        /// <summary>\n        /// Transforms a point in the texture plane so that 0,0 points at left-top corner.</summary>\n        private static int TransformToLeftTop_y(float y, int height)\n        {\n            return height - (int)y;\n        }\n\n\n        \n    }\n\n\n}"
  },
  {
    "path": "SGFUnity/Extension/TransformExtensions.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing UnityEngine;\nusing Object = UnityEngine.Object;\n\npublic static class TransformExtensions\n{\n    #region Position\n    /// <summary>\n    /// \tSets the X position of this transform.\n    /// </summary>\n    public static void SetX(this Transform transform, float x)\n    {\n        var newPosition = new Vector3(x, transform.position.y, transform.position.z);\n\n        transform.position = newPosition;\n    }\n\n\n    /// <summary>\n    ///   Sets the Y position of this transform.\n    /// </summary>\n    public static void SetY(this Transform transform, float y)\n    {\n        var newPosition = new Vector3(transform.position.x, y, transform.position.z);\n\n        transform.position = newPosition;\n    }\n\n    /**\n        Sets the Z position of this transform.\n    */\n    public static void SetZ(this Transform transform, float z)\n    {\n        var newPosition = new Vector3(transform.position.x, transform.position.y, z);\n\n        transform.position = newPosition;\n    }\n\n    /**\n        Sets the X and Y position of this transform.\n    */\n    public static void SetXY(this Transform transform, float x, float y)\n    {\n        var newPosition = new Vector3(x, y, transform.position.z);\n        transform.position = newPosition;\n    }\n\n    /**\n        Sets the X and Z position of this transform.\n    */\n    public static void SetXZ(this Transform transform, float x, float z)\n    {\n        var newPosition = new Vector3(x, transform.position.y, z);\n        transform.position = newPosition;\n    }\n\n    /**\n        Sets the Y and Z position of this transform.\n    */\n    public static void SetYZ(this Transform transform, float y, float z)\n    {\n        var newPosition = new Vector3(transform.position.x, y, z);\n        transform.position = newPosition;\n    }\n\n    /**\n        Sets the X, Y and Z position of this transform.\n    */\n    public static void SetXYZ(this Transform transform, float x, float y, float z)\n    {\n        var newPosition = new Vector3(x, y, z);\n        transform.position = newPosition;\n    }\n\n    /**\n        Translates this transform along the X axis.\n    */\n    public static void TranslateX(this Transform transform, float x)\n    {\n        var offset = new Vector3(x, 0, 0);\n\n        transform.position += offset;\n    }\n\n    /**\n        Translates this transform along the Y axis.\n    */\n\n    public static void TranslateY(this Transform transform, float y)\n    {\n        var offset = new Vector3(0, y, 0);\n\n        transform.position += offset;\n    }\n\n    /**\n        Translates this transform along the Z axis.\n    */\n    public static void TranslateZ(this Transform transform, float z)\n    {\n        var offset = new Vector3(0, 0, z);\n        transform.position += offset;\n    }\n\n    /**\n        Translates this transform along the X and Y axes.\n    */\n    public static void TranslateXY(this Transform transform, float x, float y)\n    {\n        var offset = new Vector3(x, y, 0);\n        transform.position += offset;\n    }\n\n    /**\n        Translates this transform along the X and Z axes.\n    */\n    public static void TranslateXZ(this Transform transform, float x, float z)\n    {\n        var offset = new Vector3(x, 0, z);\n        transform.position += offset;\n    }\n\n    /**\n        Translates this transform along the Y and Z axes.\n    */\n    public static void TranslateYZ(this Transform transform, float y, float z)\n    {\n        var offset = new Vector3(0, y, z);\n        transform.position += offset;\n    }\n\n    /**\n        Translates this transform along the X, Y and Z axis.\n    */\n    public static void TranslateXYZ(this Transform transform, float x, float y, float z)\n    {\n        var offset = new Vector3(x, y, z);\n        transform.position += offset;\n    }\n\n    /**\n        Sets the local X position of this transform.\n    */\n    public static void SetLocalX(this Transform transform, float x)\n    {\n        var newPosition = new Vector3(x, transform.localPosition.y, transform.localPosition.z);\n        transform.localPosition = newPosition;\n    }\n\n    /**\n        Sets the local Y position of this transform.\n    */\n    public static void SetLocalY(this Transform transform, float y)\n    {\n        var newPosition = new Vector3(transform.localPosition.x, y, transform.localPosition.z);\n        transform.localPosition = newPosition;\n    }\n\n    /**\n        Sets the local Z position of this transform.\n    */\n    public static void SetLocalZ(this Transform transform, float z)\n    {\n        var newPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, z);\n        transform.localPosition = newPosition;\n    }\n\n    /**\n        Sets the local X and Y position of this transform.\n    */\n    public static void SetLocalXY(this Transform transform, float x, float y)\n    {\n        var newPosition = new Vector3(x, y, transform.localPosition.z);\n        transform.localPosition = newPosition;\n    }\n\n    /**\n        Sets the local X and Z position of this transform.\n    */\n    public static void SetLocalXZ(this Transform transform, float x, float z)\n    {\n        var newPosition = new Vector3(x, transform.localPosition.z, z);\n        transform.localPosition = newPosition;\n    }\n\n    /**\n        Sets the local Y and Z position of this transform.\n    */\n    public static void SetLocalYZ(this Transform transform, float y, float z)\n    {\n        var newPosition = new Vector3(transform.localPosition.x, y, z);\n        transform.localPosition = newPosition;\n    }\n\n    /**\n        Sets the local X, Y and Z position of this transform.\n    */\n    public static void SetLocalXYZ(this Transform transform, float x, float y, float z)\n    {\n        var newPosition = new Vector3(x, y, z);\n        transform.localPosition = newPosition;\n    }\n\n    /**\n        Sets the position to 0, 0, 0.\n    */\n\n    public static void ResetPosition(this Transform transform)\n    {\n        transform.position = Vector3.zero;\n    }\n    /**\n        Sets the local position to 0, 0, 0.\n    */\n    public static void ResetLocalPosition(this Transform transform)\n    {\n        transform.localPosition = Vector3.zero;\n    }\n    #endregion\n\n    #region Scale\n    /**\n\t\t\tSets the local X scale of this transform.\n\t\t*/\n    public static void SetScaleX(this Transform transform, float x)\n    {\n        var newScale = new Vector3(x, transform.localScale.y, transform.localScale.z);\n        transform.localScale = newScale;\n    }\n\n    /**\n        Sets the local Y scale of this transform.\n    */\n    public static void SetScaleY(this Transform transform, float y)\n    {\n        var newScale = new Vector3(transform.localScale.x, y, transform.localScale.z);\n        transform.localScale = newScale;\n    }\n\n    /**\n        Sets the local Z scale of this transform.\n    */\n    public static void SetScaleZ(this Transform transform, float z)\n    {\n        var newScale = new Vector3(transform.localScale.x, transform.localScale.y, z);\n        transform.localScale = newScale;\n    }\n\n    /**\n        Sets the local X and Y scale of this transform.\n    */\n    public static void SetScaleXY(this Transform transform, float x, float y)\n    {\n        var newScale = new Vector3(x, y, transform.localScale.z);\n        transform.localScale = newScale;\n    }\n\n    /**\n        Sets the local X and Z scale of this transform.\n    */\n    public static void SetScaleXZ(this Transform transform, float x, float z)\n    {\n        var newScale = new Vector3(x, transform.localScale.y, z);\n        transform.localScale = newScale;\n    }\n\n    /**\n        Sets the local Y and Z scale of this transform.\n    */\n    public static void SetScaleYZ(this Transform transform, float y, float z)\n    {\n        var newScale = new Vector3(transform.localScale.x, y, z);\n        transform.localScale = newScale;\n    }\n\n    /**\n        Sets the local X, Y and Z scale of this transform.\n    */\n    public static void SetScaleXYZ(this Transform transform, float x, float y, float z)\n    {\n        var newScale = new Vector3(x, y, z);\n        transform.localScale = newScale;\n    }\n\n    /**\n        Scale this transform in the X direction.\n    */\n    public static void ScaleByX(this Transform transform, float x)\n    {\n        transform.localScale = new Vector3(transform.localScale.x * x, transform.localScale.y, transform.localScale.z);\n    }\n\n    /**\n        Scale this transform in the Y direction.\n    */\n    public static void ScaleByY(this Transform transform, float y)\n    {\n        transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y * y, transform.localScale.z);\n    }\n\n    /**\n        Scale this transform in the Z direction.\n    */\n    public static void ScaleByZ(this Transform transform, float z)\n    {\n        transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, transform.localScale.z * z);\n    }\n\n    /**\n        Scale this transform in the X, Y direction.\n    */\n    public static void ScaleByXY(this Transform transform, float x, float y)\n    {\n        transform.localScale = new Vector3(transform.localScale.x * x, transform.localScale.y * y, transform.localScale.z);\n    }\n\n    /**\n        Scale this transform in the X, Z directions.\n    */\n    public static void ScaleByXZ(this Transform transform, float x, float z)\n    {\n        transform.localScale = new Vector3(transform.localScale.x * x, transform.localScale.y, transform.localScale.z * z);\n    }\n\n    /**\n        Scale this transform in the Y and Z directions.\n    */\n    public static void ScaleByYZ(this Transform transform, float y, float z)\n    {\n        transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y * y, transform.localScale.z * z);\n    }\n\n    /**\n        Scale this transform in the X and Y directions.\n    */\n    public static void ScaleByXY(this Transform transform, float r)\n    {\n        transform.ScaleByXY(r, r);\n    }\n\n    /**\n        Scale this transform in the X and Z directions.\n    */\n    public static void ScaleByXZ(this Transform transform, float r)\n    {\n        transform.ScaleByXZ(r, r);\n    }\n\n    /**\n        Scale this transform in the Y and Z directions.\n    */\n    public static void ScaleByYZ(this Transform transform, float r)\n    {\n        transform.ScaleByYZ(r, r);\n    }\n\n    /**\n        Scale this transform in the X, Y and Z directions.\n    */\n    public static void ScaleByXYZ(this Transform transform, float x, float y, float z)\n    {\n        transform.localScale = new Vector3(\n            x, y, z);\n    }\n\n    /**\n        Scale this transform in the X, Y and Z directions.\n    */\n    public static void ScaleByXYZ(this Transform transform, float r)\n    {\n        transform.ScaleByXYZ(r, r, r);\n    }\n\n\n    /**\n        Resets the local scale of this transform in to 1 1 1.\n    */\n    public static void ResetScale(this Transform transform)\n    {\n        transform.localScale = Vector3.one;\n    }\n    #endregion\n\n    #region FlipScale\n\n    /**\n\t\t\tNegates the X scale.\n\t\t*/\n    public static void FlipX(this Transform transform)\n    {\n        transform.SetScaleX(-transform.localScale.x);\n    }\n\n    /**\n        Negates the Y scale.\n    */\n    public static void FlipY(this Transform transform)\n    {\n        transform.SetScaleY(-transform.localScale.y);\n    }\n\n    /**\n        Negates the Z scale.\n    */\n    public static void FlipZ(this Transform transform)\n    {\n        transform.SetScaleZ(-transform.localScale.z);\n    }\n\n    /**\n        Negates the X and Y scale.\n    */\n    public static void FlipXY(this Transform transform)\n    {\n        transform.SetScaleXY(-transform.localScale.x, -transform.localScale.y);\n    }\n\n    /**\n        Negates the X and Z scale.\n    */\n    public static void FlipXZ(this Transform transform)\n    {\n        transform.SetScaleXZ(-transform.localScale.x, -transform.localScale.z);\n    }\n\n    /**\n        Negates the Y and Z scale.\n    */\n    public static void FlipYZ(this Transform transform)\n    {\n        transform.SetScaleYZ(-transform.localScale.y, -transform.localScale.z);\n    }\n\n    /**\n        Negates the X, Y and Z scale.\n    */\n    public static void FlipXYZ(this Transform transform)\n    {\n        transform.SetScaleXYZ(-transform.localScale.z, -transform.localScale.y, -transform.localScale.z);\n    }\n\n    /**\n        Sets all scale values to the absolute values.\n    */\n    public static void FlipPostive(this Transform transform)\n    {\n        transform.localScale = new Vector3(\n            Mathf.Abs(transform.localScale.x),\n            Mathf.Abs(transform.localScale.y),\n            Mathf.Abs(transform.localScale.z));\n    }\n    #endregion\n\n    #region Rotation\n    /**\n\t\t\tRotates the transform around the X axis.\n\t\t*/\n    public static void RotateAroundX(this Transform transform, float angle)\n    {\n        var rotation = new Vector3(angle, 0, 0);\n        transform.Rotate(rotation);\n    }\n\n    /**\n        Rotates the transform around the Y axis.\n    */\n    public static void RotateAroundY(this Transform transform, float angle)\n    {\n        var rotation = new Vector3(0, angle, 0);\n        transform.Rotate(rotation);\n    }\n\n    /**\n        Rotates the transform around the Z axis.\n    */\n    public static void RotateAroundZ(this Transform transform, float angle)\n    {\n        var rotation = new Vector3(0, 0, angle);\n        transform.Rotate(rotation);\n    }\n\n    /**\n        Sets the X rotation.\n    */\n    public static void SetRotationX(this Transform transform, float angle)\n    {\n        transform.eulerAngles = new Vector3(angle, 0, 0);\n    }\n\n    /**\n        Sets the Y rotation.\n    */\n    public static void SetRotationY(this Transform transform, float angle)\n    {\n        transform.eulerAngles = new Vector3(0, angle, 0);\n    }\n\n    /**\n        Sets the Z rotation.\n    */\n    public static void SetRotationZ(this Transform transform, float angle)\n    {\n        transform.eulerAngles = new Vector3(0, 0, angle);\n    }\n\n    /**\n        Sets the local X rotation.\n    */\n    public static void SetLocalRotationX(this Transform transform, float angle)\n    {\n        transform.localRotation = Quaternion.Euler(new Vector3(angle, 0, 0));\n    }\n\n    /**\n        Sets the local Y rotation.\n    */\n    public static void SetLocalRotationY(this Transform transform, float angle)\n    {\n        transform.localRotation = Quaternion.Euler(new Vector3(0, angle, 0));\n    }\n\n    /**\n        Sets the local Z rotation.\n    */\n    public static void SetLocalRotationZ(this Transform transform, float angle)\n    {\n        transform.localRotation = Quaternion.Euler(new Vector3(0, 0, angle));\n    }\n\n    /**\n        Resets the rotation to 0, 0, 0.\n    */\n    public static void ResetRotation(this Transform transform)\n    {\n        transform.rotation = Quaternion.identity;\n    }\n\n    /**\n        Resets the local rotation to 0, 0, 0.\n    */\n    public static void ResetLocalRotation(this Transform transform)\n    {\n        transform.localRotation = Quaternion.identity;\n    }\n    #endregion\n\n    #region All\n    /**\n\t\t\tResets the ;local position, local rotation, and local scale.\n\t\t*/\n    public static void ResetLocal(this Transform transform)\n    {\n        transform.ResetLocalRotation();\n        transform.ResetLocalPosition();\n        transform.ResetScale();\n\n    }\n\n    /**\n        Resets the position, rotation, and local scale.\n    */\n    public static void Reset(this Transform transform)\n    {\n        transform.ResetRotation();\n        transform.ResetPosition();\n        transform.ResetScale();\n    }\n    #endregion\n\n    #region Children\n    public static void DestroyChildren(this Transform transform)\n    {\n        //Add children to list before destroying\n        //otherwise GetChild(i) may bomb out\n        var children = new List<Transform>();\n\n        for (var i = 0; i < transform.childCount; i++)\n        {\n            var child = transform.GetChild(i);\n            children.Add(child);\n        }\n\n        foreach (var child in children)\n        {\n            Object.Destroy(child.gameObject);\n        }\n    }\n\n    public static void DestroyChildrenImmediate(this Transform transform)\n    {\n        //Add children to list before destroying\n        //otherwise GetChild(i) may bomb out\n        var children = new List<Transform>();\n\n        for (var i = 0; i < transform.childCount; i++)\n        {\n            var child = transform.GetChild(i);\n            children.Add(child);\n        }\n\n        foreach (var child in children)\n        {\n            Object.DestroyImmediate(child.gameObject);\n        }\n    }\n\n    public static List<Transform> GetChildren(this Transform transform)\n    {\n        var children = new List<Transform>();\n\n        for (var i = 0; i < transform.childCount; i++)\n        {\n            var child = transform.GetChild(i);\n            children.Add(child);\n        }\n\n        return children;\n    }\n    public static void Sort(this Transform transform, Func<Transform, IComparable> sortFunction)\n    {\n        var children = transform.GetChildren();\n        var sortedChildren = children.OrderBy(sortFunction).ToList();\n\n        for (int i = 0; i < sortedChildren.Count(); i++)\n        {\n            sortedChildren[i].SetSiblingIndex(i);\n        }\n    }\n\n    public static void SortAlphabetically(this Transform transform)\n    {\n        transform.Sort(t => t.name);\n    }\n\n    /**\n        A lazy enumerable of this objects transform, and all it's children down the hierarchy.\n\t\t\t\n        @version_e_1_1\n    */\n    public static IEnumerable<Transform> SelfAndAllChildren(this Transform transform)\n    {\n        var openList = new Queue<Transform>();\n\n        openList.Enqueue(transform);\n\n        while (openList.Any())\n        {\n            var currentChild = openList.Dequeue();\n\n            yield return currentChild;\n\n            var children = transform.GetChildren();\n\n            foreach (var child in children)\n            {\n                openList.Enqueue(child);\n            }\n        }\n    }\n    #endregion\n\n\n    public static T FindComponent<T>(this Transform transform, string name)\n    {\n        var tmp = transform.Find(name);\n        if (tmp != null) return tmp.GetComponent<T>();\n        return default(T);\n    }\n}\t\n"
  },
  {
    "path": "SGFUnity/Extension/VectorExtensions.cs",
    "content": "﻿using UnityEngine;\n\n\npublic static class VectorExtensions\n{\n    public static Vector3 To3DXZ(this Vector2 vector, float y)\n    {\n        return new Vector3(vector.x, y, vector.y);\n    }\n\n    public static Vector3 To3DXZ(this Vector2 vector)\n    {\n        return vector.To3DXZ(0);\n    }\n\n    public static Vector3 To3DXY(this Vector2 vector, float z)\n    {\n        return new Vector3(vector.x, vector.y, z);\n    }\n\n    public static Vector3 To3DXY(this Vector2 vector)\n    {\n        return vector.To3DXY(0);\n    }\n\n    public static Vector3 To3DYZ(this Vector2 vector, float x)\n    {\n        return new Vector3(x, vector.x, vector.y);\n    }\n\n    public static Vector3 To3DYZ(this Vector2 vector)\n    {\n        return vector.To3DYZ(0);\n    }\n\n    public static Vector2 To2DXZ(this Vector3 vector)\n    {\n        return new Vector2(vector.x, vector.z);\n    }\n\n    public static Vector2 To2DXY(this Vector3 vector)\n    {\n        return new Vector2(vector.x, vector.y);\n    }\n\n    public static Vector2 To2DYZ(this Vector3 vector)\n    {\n        return new Vector2(vector.y, vector.z);\n    }\n\n    /**\n        Returns the vector rotated 90 degrees counter-clockwise. This vector is\n        always perpendicular to the given vector.\n\n        The perp dot product can be caluclted using this:\n            var perpDotPorpduct = Vector2.Dot(v1.Perp(), v2);\n    */\n    public static Vector2 Perp(this Vector2 vector)\n    {\n        return new Vector2(-vector.y, vector.x);\n    }\n\n    /**\n        Returns the projection of this vector onto the given base.\n    */\n    public static Vector2 Proj(this Vector2 vector, Vector2 baseVector)\n    {\n        var direction = baseVector.normalized;\n        var magnitude = Vector2.Dot(vector, direction);\n\n        return direction * magnitude;\n    }\n\n    /**\n        Returns the rejection of this vector onto the given base.\n\n        The sum of a vector's projection and rejection on a base is\n        equal to the original vector.\n    */\n    public static Vector2 Rej(this Vector2 vector, Vector2 baseVector)\n    {\n        return vector - vector.Proj(baseVector);\n    }\n\n    /**\n        Returns the projection of this vector onto the given base.\n    */\n    public static Vector3 Proj(this Vector3 vector, Vector3 baseVector)\n    {\n        var direction = baseVector.normalized;\n        var magnitude = Vector2.Dot(vector, direction);\n\n        return direction * magnitude;\n    }\n\n    /**\n        Returns the rejection of this vector onto the given base.\n\n        The sum of a vector's projection and rejection on a base is\n        equal to the original vector.\n    */\n    public static Vector3 Rej(this Vector3 vector, Vector3 baseVector)\n    {\n        return vector - vector.Proj(baseVector);\n    }\n\n    /**\n        Returns the projection of this vector onto the given base.\n    */\n    public static Vector4 Proj(this Vector4 vector, Vector4 baseVector)\n    {\n        var direction = baseVector.normalized;\n        var magnitude = Vector2.Dot(vector, direction);\n\n        return direction * magnitude;\n    }\n\n    /**\n        Returns the rejection of this vector onto the given base.\n\n        The sum of a vector's projection and rejection on a base is\n        equal to the original vector.\n    */\n    public static Vector4 Rej(this Vector4 vector, Vector4 baseVector)\n    {\n        return vector - vector.Proj(baseVector);\n    }\n\n    public static Vector3 PerpXZ(this Vector3 v)\n    {\n        return new Vector3(-v.z, v.y, v.x);\n    }\n\n    public static Vector3 PerpXY(this Vector3 v)\n    {\n        return new Vector3(-v.y, v.x, v.z);\n    }\n\n\n\n    public static string GetStringValue(this Vector3 v)\n    {\n        return v.x + \",\" + v.y + \",\" + v.z;\n    }\n\n    public static void SetStringValue(this Vector3 v, string strValue)\n    {\n        string[] tmp = strValue.Split(',');\n        if (tmp.Length >= 3)\n        {\n            float x = v.x;\n            float y = v.y;\n            float z = v.z;\n            float.TryParse(tmp[0], out x);\n            float.TryParse(tmp[1], out y);\n            float.TryParse(tmp[2], out z);\n\n            v.x = x;\n            v.y = y;\n            v.z = z;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILR/DebugerILR/DebugerMethodRedirector.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.Utils;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nusing AppDomain = ILRuntime.Runtime.Enviorment.AppDomain;\n\nnamespace SGF.Unity.ILR.DebugerILR\n{\n    public unsafe class DebugerMethodRedirector:ICLRMethodRedirector\n    {\n        public const string Prefix = \"ILR> \";\n\n        public void Init(AppDomain app)\n        {\n            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;\n            MethodBase method;\n            FieldInfo field;\n            Type[] args;\n            Type type = typeof(SGF.Debuger);\n\n            args = new Type[] { typeof(System.String) };\n            method = type.GetMethod(\"Log\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, Log_1);\n\n            args = new Type[] { typeof(System.String), typeof(System.Object[]) };\n            method = type.GetMethod(\"Log\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, Log_2);\n\n            args = new Type[] { typeof(SGF.ILogTag), typeof(System.String) };\n            method = type.GetMethod(\"Log\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, Log_3);\n\n            args = new Type[] { typeof(SGF.ILogTag), typeof(System.String), typeof(System.Object[]) };\n            method = type.GetMethod(\"Log\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, Log_4);\n\n            args = new Type[] { typeof(System.String) };\n            method = type.GetMethod(\"LogWarning\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, LogWarning_5);\n\n            args = new Type[] { typeof(System.String), typeof(System.Object[]) };\n            method = type.GetMethod(\"LogWarning\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, LogWarning_6);\n\n            args = new Type[] { typeof(SGF.ILogTag), typeof(System.String) };\n            method = type.GetMethod(\"LogWarning\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, LogWarning_7);\n\n            args = new Type[] { typeof(SGF.ILogTag), typeof(System.String), typeof(System.Object[]) };\n            method = type.GetMethod(\"LogWarning\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, LogWarning_8);\n\n            args = new Type[] { typeof(System.String) };\n            method = type.GetMethod(\"LogError\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, LogError_9);\n\n            args = new Type[] { typeof(System.String), typeof(System.Object[]) };\n            method = type.GetMethod(\"LogError\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, LogError_10);\n\n            args = new Type[] { typeof(SGF.ILogTag), typeof(System.String) };\n            method = type.GetMethod(\"LogError\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, LogError_11);\n\n            args = new Type[] { typeof(SGF.ILogTag), typeof(System.String), typeof(System.Object[]) };\n            method = type.GetMethod(\"LogError\", flag, null, args, null);\n            app.RegisterCLRMethodRedirection(method, LogError_12);\n        }\n\n\n\n        static StackObject* Log_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 1);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.String message = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = frame.Method.DeclearingType.Name + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_Log(Prefix + caller + message);\n\n            return __ret;\n        }\n\n        static StackObject* Log_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 2);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.Object[] args = (System.Object[])typeof(System.Object[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);\n            System.String format = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = frame.Method.DeclearingType.Name + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_Log(Prefix + caller + string.Format(format, args));\n\n\n\n            return __ret;\n        }\n\n        static StackObject* Log_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 2);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.String message = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);\n            SGF.ILogTag obj = (SGF.ILogTag)typeof(SGF.ILogTag).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = obj.LOG_TAG + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_Log(Prefix + caller + message);\n\n            return __ret;\n        }\n\n        static StackObject* Log_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 3);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.Object[] args = (System.Object[])typeof(System.Object[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);\n            System.String format = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);\n            SGF.ILogTag obj = (SGF.ILogTag)typeof(SGF.ILogTag).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = obj.LOG_TAG + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_Log(Prefix + caller + string.Format(format, args));\n\n            return __ret;\n        }\n\n        static StackObject* LogWarning_5(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 1);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.String message = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = frame.Method.DeclearingType.Name + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_LogWarning(Prefix + caller + message);\n\n\n            return __ret;\n        }\n\n        static StackObject* LogWarning_6(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 2);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.Object[] args = (System.Object[])typeof(System.Object[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);\n            System.String format = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = frame.Method.DeclearingType.Name + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_LogWarning(Prefix + caller + string.Format(format, args));\n\n\n            return __ret;\n        }\n\n        static StackObject* LogWarning_7(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 2);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.String message = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);\n            SGF.ILogTag obj = (SGF.ILogTag)typeof(SGF.ILogTag).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = obj.LOG_TAG + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_LogWarning(Prefix + caller + message);\n\n\n            return __ret;\n        }\n\n        static StackObject* LogWarning_8(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 3);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.Object[] args = (System.Object[])typeof(System.Object[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);\n            System.String format = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);\n            SGF.ILogTag obj = (SGF.ILogTag)typeof(SGF.ILogTag).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = obj.LOG_TAG + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_LogWarning(Prefix + caller + string.Format(format, args));\n\n\n            return __ret;\n        }\n\n        static StackObject* LogError_9(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 1);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.String message = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n            var stacktrace = __domain.DebugService.GetStackTrance(__intp);\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = frame.Method.DeclearingType.Name + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_LogError(Prefix + caller + message + \"\\n\" + stacktrace);\n\n            return __ret;\n        }\n\n        static StackObject* LogError_10(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 2);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.Object[] args = (System.Object[])typeof(System.Object[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);\n            System.String format = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n            var stacktrace = __domain.DebugService.GetStackTrance(__intp);\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = frame.Method.DeclearingType.Name + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_LogError(Prefix + caller + string.Format(format, args) + \"\\n\" + stacktrace);\n\n            return __ret;\n        }\n\n        static StackObject* LogError_11(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 2);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.String message = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);\n            SGF.ILogTag obj = (SGF.ILogTag)typeof(SGF.ILogTag).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n            var stacktrace = __domain.DebugService.GetStackTrance(__intp);\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = obj.LOG_TAG + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_LogError(Prefix + caller + message + \"\\n\" + stacktrace);\n\n\n            return __ret;\n        }\n\n        static StackObject* LogError_12(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\n        {\n            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\n            StackObject* ptr_of_this_method;\n            StackObject* __ret = ILIntepreter.Minus(__esp, 3);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);\n            System.Object[] args = (System.Object[])typeof(System.Object[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);\n            System.String format = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);\n            SGF.ILogTag obj = (SGF.ILogTag)typeof(SGF.ILogTag).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));\n            __intp.Free(ptr_of_this_method);\n\n            var stacktrace = __domain.DebugService.GetStackTrance(__intp);\n\n            StackFrame frame = __intp.Stack.Frames.Peek();\n            var caller = obj.LOG_TAG + \"::\" + frame.Method.Name + \"() \";\n            SGF.Debuger.Internal_LogError(Prefix + caller + string.Format(format, args) + \"\\n\" + stacktrace);\n\n            return __ret;\n        }\n\n\n\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/DebugerILR/ILogTagAdaptor.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing AppDomain = ILRuntime.Runtime.Enviorment.AppDomain;\n\nnamespace SGF.Unity.ILR.DebugerILR\n{\n    public class ILogTagAdaptor:CrossBindingAdaptor\n    {\n        public override object CreateCLRInstance(AppDomain appdomain, ILTypeInstance instance)\n        {\n            return new Adaptor(appdomain, instance);\n        }\n\n        public override Type BaseCLRType { get { return typeof(ILogTag); } }\n        public override Type AdaptorType { get { return typeof(Adaptor); } }\n\n\n\n        class Adaptor : ILogTag, CrossBindingAdaptorType\n        {\n            private AppDomain m_appdomain;\n\n            public ILTypeInstance ILInstance { get; private set; }\n\n\n            public Adaptor(ILRuntime.Runtime.Enviorment.AppDomain appdomain, ILTypeInstance instance)\n            {\n                m_appdomain = appdomain;\n                ILInstance = instance;\n            }\n\n\n            private IMethod mGetLogTag;\n            private bool isGetLogTagInvoking = false;\n            public string LOG_TAG\n            {\n                get\n                {\n                    if (mGetLogTag == null)\n                    {\n                        mGetLogTag = ILInstance.Type.GetMethod(\"get_LOG_TAG\", 0);\n                    }\n\n                    if (mGetLogTag != null && !isGetLogTagInvoking)\n                    {\n                        isGetLogTagInvoking = true;\n                        var result = m_appdomain.Invoke(mGetLogTag, ILInstance) as string;\n                        isGetLogTagInvoking = false;\n                        return result;\n                    }\n\n                    return \"\";\n\n                }\n            }\n\n\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/DelegateConvertor.cs",
    "content": "﻿/*\r\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\r\n * \r\n * Licensed under the MIT License (the \"License\"); \r\n * you may not use this file except in compliance with the License. \r\n * You may obtain a copy of the License at\r\n * http://opensource.org/licenses/MIT\r\n * Unless required by applicable law or agreed to in writing, \r\n * software distributed under the License is distributed on an \"AS IS\" BASIS, \r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \r\n * either express or implied. \r\n * See the License for the specific language governing permissions and limitations under the License.\r\n*/\r\n\r\nusing AppDomain = ILRuntime.Runtime.Enviorment.AppDomain;\r\n\r\nnamespace SGF.Unity.ILR\r\n{\r\n    public class DelegateConvertor\r\n    {\r\n        public static void Init(AppDomain appdomain)\r\n        {\r\n            appdomain.DelegateManager.RegisterMethodDelegate<int>();\r\n            appdomain.DelegateManager.RegisterMethodDelegate<float>();\r\n            appdomain.DelegateManager.RegisterMethodDelegate<object>();\r\n            appdomain.DelegateManager.RegisterMethodDelegate<System.Object>();\r\n\r\n\r\n\r\n\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "SGFUnity/ILR/ILRManager.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * ILR管理器\n * 用来实现原生模块与ILR模块的无缝衔接\n * 你在用模块管理器管理模块时，不需要关心该模块是ILR的，还是原生的\n * ILR Manager\n * It is used to realize the seamless connection between the native module and the ILR module\n * When you manage the module with the module manager, you don't need to care if the module is ILR or native\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Reflection;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing Mono.Cecil.Pdb;\nusing SGF.Utils;\nusing AppDomain = ILRuntime.Runtime.Enviorment.AppDomain;\nusing SGF.Extension;\nusing SGF.Unity.ILR.DebugerILR;\nusing SGF.Unity.ILR.ModuleILR;\nusing SGF.Unity.ILR.UIILR;\n\nnamespace SGF.Unity.ILR\n{\n    public interface ICLRMethodRedirector\n    {\n        void Init(AppDomain app);\n    }\n\n    public enum RunMode\n    {\n        Script = 0,\n        Native = 1\n    }\n\n\n    public class ILRManager:Singleton<ILRManager>\n    {\n        public RunMode RunMode { get; private set; }\n        public bool UsePdb { get; private set; }\n\n        private List<string> m_listSearchDir = new List<string>();\n        private AppDomain m_appdomain;\n        private List<Assembly> m_listNativeAssembly = new List<Assembly>();\n\n\n        public static object CreateInstance(string typeName, string assemblyName = \"\", params object[] args)\n        {\n            return Instance.CreateInstanceInternal(typeName, assemblyName, args);\n        }\n\n        public static object CreateInstance(string typeName, params object[] args)\n        {\n            return Instance.CreateInstanceInternal(typeName, \"\", args);\n        }\n\n        public static object CreateInstance(string typeName)\n        {\n            return Instance.CreateInstanceInternal(typeName, \"\", null);\n        }\n\n\n        //======================================================================================\n\n\n        public void Init(RunMode runMode, bool usePdb)\n        {\n            Debuger.Log(\"RunMode:{0}, UsePdb:{1}\", runMode, usePdb);\n\n            RunMode = runMode;\n            UsePdb = usePdb;\n\n            //首先实例化ILRuntime的AppDomain，AppDomain是一个应用程序域，每个AppDomain都是一个独立的沙盒\n            m_appdomain = new AppDomain();\n\n            if (runMode == RunMode.Script)\n            {\n                //注册Adaptor\n                RegisterCrossBindingAdaptor(new ILogTagAdaptor());\n                RegisterCrossBindingAdaptor(new GeneralModuleAdaptor());\n                RegisterCrossBindingAdaptor(new ILRUILoadingAdaptor());\n                RegisterCrossBindingAdaptor(new ILRUIPageAdaptor());\n                RegisterCrossBindingAdaptor(new ILRUIWindowAdaptor());\n                RegisterCrossBindingAdaptor(new ILRUIWidgetAdaptor());\n                RegisterCrossBindingAdaptor(new ILRUIPanelAdaptor());\n\n                //注册重定向器\n                RegisterCLRMethodRedirector(new DebugerMethodRedirector());\n            }\n        }\n\n\n        public void Clean()\n        {\n            Debuger.Log();\n            if (m_appdomain != null)\n            {\n                m_appdomain = null;\n            }\n            m_listNativeAssembly.Clear();\n        }\n\n\n        //========================================================================\n        //注册函数\n        //========================================================================\n        public void RegisterCrossBindingAdaptor(CrossBindingAdaptor adaptor)\n        {\n            if (m_appdomain != null)\n            {\n                m_appdomain.RegisterCrossBindingAdaptor(adaptor);\n            }\n            else\n            {\n                Debuger.LogError(\"ILRuntime的AppDomain未创建！\");\n            }\n        }\n\n        public void RegisterCLRMethodRedirector(ICLRMethodRedirector redirector)\n        {\n            if (m_appdomain != null)\n            {\n                if (redirector != null)\n                {\n                    redirector.Init(m_appdomain);\n                }\n            }\n            else\n            {\n                Debuger.LogError(\"ILRuntime的AppDomain未创建！\");\n            }\n        }\n\n        //========================================================================\n        //加载Assembly\n        //========================================================================\n\n        #region 加载Assembly相关函数\n\n        public void AddSearchDirectory(string path)\n        {\n            Debuger.Log(path);\n            if (!m_listSearchDir.Contains(path))\n            {\n                m_listSearchDir.Add(path);\n            }\n        }\n\n\n        private string FindAssemblyFullPath(string assemblyName)\n        {\n            for (int i = 0; i < m_listSearchDir.Count; i++)\n            {\n                string path = m_listSearchDir[i] + \"/\" + assemblyName + \".dll\";\n                if (File.Exists(path))\n                {\n                    return path;\n                }\n            }\n            return null;\n        }\n\n\n        public void LoadAssembly(string assemblyName)\n        {\n            if (RunMode == RunMode.Native)\n            {\n                LoadAssemblyNative(assemblyName);\n            }\n            else\n            {\n                LoadAssemblyScript(assemblyName);\n            }\n        }\n\n\n        private void LoadAssemblyNative(string assemblyName)\n        {\n            Debuger.Log(assemblyName);\n\n            string dllPath = FindAssemblyFullPath(assemblyName);\n            if (string.IsNullOrEmpty(dllPath))\n            {\n                Debuger.LogError(\"Assembly不存在：{0}\", assemblyName);\n                return;\n            }\n\n            Assembly assembly = Assembly.LoadFile(dllPath);\n            if (assembly != null)\n            {\n                m_listNativeAssembly.Add(assembly);\n            }\n        }\n\n\n        private void LoadAssemblyScript(string assemblyName)\n        {\n            Debuger.Log(assemblyName);\n\n            string dllPath = FindAssemblyFullPath(assemblyName);\n            if (string.IsNullOrEmpty(dllPath))\n            {\n                Debuger.LogError(\"Assembly不存在：{0}\", assemblyName);\n                return;\n            }\n\n\n            byte[] dllBytes = FileUtils.ReadFile(dllPath);\n            byte[] pdbBytes = null;\n\n            if (UsePdb)\n            {\n                pdbBytes = FileUtils.ReadFile(GetPdbPath(dllPath));\n            }\n\n\n            try\n            {\n                using (MemoryStream dll = new MemoryStream(dllBytes))\n                {\n                    if (pdbBytes != null)\n                    {\n                        using (MemoryStream pdb = new MemoryStream(pdbBytes))\n                        {\n                            Debuger.Log(\"LoadAssembly\");\n                            m_appdomain.LoadAssembly(dll, pdb, new PdbReaderProvider());\n                        }\n                    }\n                    else\n                    {\n                        Debuger.Log(\"LoadAssembly\");\n                        m_appdomain.LoadAssembly(dll, null, null);\n                    }\n\n                }\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(e.Message);\n            }\n        }\n\n        private string GetPdbPath(string dllPath)\n        {\n            int i = dllPath.LastIndexOf(\".dll\");\n            return dllPath.Substring(0, i) + \".pdb\";\n        }\n        #endregion\n\n\n        //========================================================================\n        //获取类型\n        //========================================================================\n\n        private Type GetNativeType(string typeName)\n        {\n            Type type = null;\n            for (int i = 0; i < m_listNativeAssembly.Count; i++)\n            {\n                type = m_listNativeAssembly[i].GetType(typeName);\n                if (type != null)\n                {\n                    break;\n                }\n            }\n            return type;\n        }\n\n\n        private IType GetScriptType(string typeName)\n        {\n            IType type = m_appdomain.GetType(typeName);\n            return type;\n        }\n\n\n        //========================================================================\n        //函数调用\n        //========================================================================\n\n        public object Invoke(string typeName, string methodName, params object[] args)\n        {\n            Debuger.Log(\"{0}::{1}({2})\", typeName, methodName, args.ToListString());\n\n            if (RunMode == RunMode.Native)\n            {\n                Type type = GetNativeType(typeName);\n                if (type != null)\n                {\n                    MethodInfo mi = type.GetMethod(methodName);\n                    if (mi != null)\n                    {\n                        return mi.Invoke(null, args);\n                    }\n                    else\n                    {\n                        Debuger.LogError(\"从NativeAssembly中找不到该函数!\");\n                    }\n                }\n                else\n                {\n                    Debuger.LogError(\"从NativeAssembly中找不到该类型!\");\n                }\n            }\n            else\n            {\n                return m_appdomain.Invoke(typeName, methodName, null, args);\n            }\n            return null;\n\n        }\n\n        //========================================================================\n        //创建实例\n        //========================================================================\n        private object CreateInstanceInternal(string typeName, string assemblyName, object[] args)\n        {\n            if (RunMode == RunMode.Native)\n            {\n                if (string.IsNullOrEmpty(assemblyName))\n                {\n                    return System.AppDomain.CurrentDomain.GetType().Assembly.CreateInstance(typeName);\n                }\n                else\n                {\n                    Type type = Type.GetType(typeName + \",\" + assemblyName);\n                    if (type != null)\n                    {\n                        return Activator.CreateInstance(type, args);\n                    }\n                }\n            }\n            else\n            {\n                ILTypeInstance obj = m_appdomain.Instantiate(typeName, args);\n                if (obj != null)\n                {\n                    return obj.CLRInstance;\n                }\n            }\n\n            Debuger.LogError(\"找不到类型：\" + typeName);\n            return null;\n        }\n\n\n\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/ModuleILR/GeneralModuleAdaptor.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing SGF.Module;\nusing AppDomain = ILRuntime.Runtime.Enviorment.AppDomain;\n\nnamespace SGF.Unity.ILR.ModuleILR\n{\n    public class GeneralModuleAdaptor:CrossBindingAdaptor\n    {\n        public override object CreateCLRInstance(AppDomain appdomain, ILTypeInstance instance)\n        {\n            return new Adaptor(appdomain, instance);\n        }\n\n        public override Type BaseCLRType { get { return typeof(GeneralModule); } }\n        public override Type AdaptorType { get { return typeof(Adaptor); } }\n    }\n\n\n\n    class  Adaptor:GeneralModule, CrossBindingAdaptorType\n    {\n        //缓存这个数组来避免调用时的GC Alloc\n        private object[] m_args = new object[1];\n\n        ILTypeInstance m_instance;\n        AppDomain m_appdomain;\n        \n        public ILTypeInstance ILInstance { get { return m_instance; } }\n\n        public Adaptor(AppDomain appdomain, ILTypeInstance instance)\n        {\n            this.m_appdomain = appdomain;\n            this.m_instance = instance;\n            LOG_TAG = \"Apdator[\" + m_instance.Type.Name + \"]\";\n        }\n\n\n        //==============================================================================\n        private IMethod mToString;\n\n        private bool mToStringInvokeing;\n        public override string ToString()\n        {\n            if (mToString == null)\n            {\n                mToString = m_instance.Type.GetMethod(\"ToString\",0);\n            }\n\n            if (mToString != null && !mToStringInvokeing)\n            {\n                mToStringInvokeing = true;\n                var result = m_appdomain.Invoke(mToString, m_instance) as string;\n                mToStringInvokeing = false;\n                return result;\n            }\n            else\n            {\n                return m_instance.Type.FullName;\n            }\n\n        }\n\n\n        //==============================================================================\n\n\n        private IMethod m_miCreate;\n\n        private bool m_isCreateInvoking;\n        public override void Create(object args = null)\n        {\n            //Debuger.Log(args);\n\n            if (m_miCreate == null)\n            {\n                m_miCreate = m_instance.Type.GetMethod(\"Create\", 1);\n            }\n            if (m_miCreate != null && !m_isCreateInvoking)\n            {\n                m_isCreateInvoking = true;\n                m_args[0] = args;\n                m_appdomain.Invoke(m_miCreate, m_instance, m_args);\n                m_isCreateInvoking = false;\n            }\n            else\n            {\n                base.Create(args);\n            }\n        }\n\n\n        private IMethod m_miRelease;\n\n        private bool m_isReleaseInvoking;\n        public override void Release()\n        {\n            //Debuger.Log();\n\n            if (m_miRelease == null)\n            {\n                m_miRelease = m_instance.Type.GetMethod(\"Release\", 0);\n            }\n            if (m_miRelease != null && !m_isReleaseInvoking)\n            {\n                m_isReleaseInvoking = true;\n                m_appdomain.Invoke(m_miRelease, m_instance);\n                m_isReleaseInvoking = false;\n            }\n            else\n            {\n                base.Release();\n            }\n        }\n\n\n\n        private IMethod m_miOnHandleMessage;\n\n        private bool m_isOnHandleMessageInvoking;\n        protected override void OnModuleMessage(string msg, object[] args)\n        {\n            //Debuger.Log(\"msg:{0}, args:{1}\", msg, args.ToListString());\n\n            IMethod mi = m_instance.Type.GetMethod(msg, args.Length);\n            if (mi != null)\n            {\n                m_appdomain.Invoke(mi, m_instance, args);\n            }\n            else\n            {\n                if (m_miOnHandleMessage == null)\n                {\n                    m_miOnHandleMessage = m_instance.Type.GetMethod(\"OnModuleMessage\", 1);\n                }\n                if (m_miOnHandleMessage != null && !m_isOnHandleMessageInvoking)\n                {\n                    m_isOnHandleMessageInvoking = true;\n                    m_appdomain.Invoke(m_miOnHandleMessage, m_instance, args);\n                    m_isOnHandleMessageInvoking = false;\n                }\n                else\n                {\n                    base.OnModuleMessage(msg, args);\n                }\n            }\n        }\n\n\n        private IMethod m_miShow;\n\n        private bool m_isShowInvoking;\n        protected override void Show(object arg)\n        {\n            //Debuger.Log(arg);\n\n            if (m_miShow == null)\n            {\n                m_miShow = m_instance.Type.GetMethod(\"Show\", 1);\n            }\n            if (m_miShow != null && !m_isShowInvoking)\n            {\n                m_isShowInvoking = true;\n                m_args[0] = arg;\n                m_appdomain.Invoke(m_miShow, m_instance, m_args);\n                m_isShowInvoking = false;\n            }\n            else\n            {\n                base.Show(arg);\n            }\n        }\n\n\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/ModuleILR/ILRModuleActivator.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing SGF.Module;\n\nnamespace SGF.Unity.ILR.ModuleILR\n{\n    public class ILRModuleActivator:IModuleActivator\n    {\n        private string m_namespace;\n        private string m_assemblyName;\n\n\n        public ILRModuleActivator(string _namespace, string assemblyName)\n        {\n            m_namespace = _namespace;\n            m_assemblyName = assemblyName;\n        }\n\n\n\n        public GeneralModule CreateInstance(string moduleName)\n        {\n            Type type = null;\n            string fullname = m_namespace + \".\" + moduleName;\n\n            return ILRManager.CreateInstance(fullname, m_assemblyName) as GeneralModule;\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/UIILR/ILRUILoading.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing SGF.Unity.UI;\n\nnamespace SGF.Unity.ILR.UIILR\n{\n    public class ILRUILoading:ILRUIPanel\n    {\n        \n    }\n\n    public class ILRUILoadingBridge : UILoading\n    {\n        public string AssemblyName = \"\";\n        public string Namespace = \"\";\n        public string TypeName = \"\";\n\n\n        private ILRUIPanel m_impl;\n\n        protected override void OnAwake()\n        {\n            base.OnAwake();\n\n            string fullName = Namespace + \".\" + TypeName;\n            m_impl = ILRManager.CreateInstance(fullName, AssemblyName) as ILRUIPanel;\n            if (m_impl == null)\n            {\n                Debuger.LogError(\"无法在Assembly[{0}]中创建实例:{1}\", AssemblyName, fullName);\n            }\n            else\n            {\n                m_impl.OnAwakeInternal(this);\n            }\n        }\n\n\n        protected override void OnDestroy()\n        {\n            base.OnDestroy();\n            if (m_impl != null)\n            {\n                m_impl.OnDestroyInternal();\n            }\n        }\n\n        protected override void OnEnable()\n        {\n            base.OnEnable();\n            if (m_impl != null)\n            {\n                m_impl.OnEnableInternal();\n            }\n        }\n\n        protected override void OnDisable()\n        {\n            base.OnDisable();\n            if (m_impl != null)\n            {\n                m_impl.OnDisableInternal();\n            }\n        }\n\n\n        protected override void OnOpen(object arg = null)\n        {\n            base.OnOpen(arg);\n            if (m_impl != null)\n            {\n                m_impl.OnOpenInternal(arg);\n            }\n        }\n\n        protected override void OnClose(object arg = null)\n        {\n            base.OnClose(arg);\n            if (m_impl != null)\n            {\n                m_impl.OnCloseInternal(arg);\n            }\n        }\n\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/UIILR/ILRUILoadingAdaptor.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing AppDomain = ILRuntime.Runtime.Enviorment.AppDomain;\n\nnamespace SGF.Unity.ILR.UIILR\n{\n    public class ILRUILoadingAdaptor : CrossBindingAdaptor\n    {\n        public override Type BaseCLRType\n        {\n            get { return typeof(ILRUILoading); }\n        }\n\n        public override Type AdaptorType\n        {\n            get { return typeof(Adaptor); }\n        }\n\n        public override object CreateCLRInstance(AppDomain appdomain, ILTypeInstance instance)\n        {\n            return new Adaptor(appdomain, instance); //创建一个新的实例\n        }\n\n\n\n        class Adaptor : ILRUIPanelAdaptor.Adaptor\n        {\n            private ILTypeInstance m_instance;\n            private AppDomain m_appdomain;\n            private object[] m_args = new object[1];\n\n            public Adaptor(AppDomain appdomain, ILTypeInstance instance)\n                : base(appdomain, instance)\n            {\n                this.m_appdomain = appdomain;\n                this.m_instance = instance;\n            }\n\n            //==============================================================================\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/UIILR/ILRUIPage.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing SGF.Unity.UI;\n\nnamespace SGF.Unity.ILR.UIILR\n{\n    public class ILRUIPage:ILRUIPanel\n    {\n        \n    }\n\n\n    public class ILRUIPageBridge : UIPage\n    {\n        public string AssemblyName = \"\";\n        public string Namespace = \"\";\n        public string TypeName = \"\";\n\n\n        private ILRUIPanel m_impl;\n\n        protected override void OnAwake()\n        {\n            base.OnAwake();\n\n            string fullName = Namespace + \".\" + TypeName;\n            m_impl = ILRManager.CreateInstance(fullName, AssemblyName) as ILRUIPanel;\n            if (m_impl == null)\n            {\n                Debuger.LogError(\"无法在Assembly[{0}]中创建实例:{1}\", AssemblyName, fullName);\n            }\n            else\n            {\n                m_impl.OnAwakeInternal(this);\n            }\n        }\n\n\n        protected override void OnDestroy()\n        {\n            base.OnDestroy();\n            if (m_impl != null)\n            {\n                m_impl.OnDestroyInternal();\n            }\n        }\n\n        protected override void OnEnable()\n        {\n            base.OnEnable();\n            if (m_impl != null)\n            {\n                m_impl.OnEnableInternal();\n            }\n        }\n\n        protected override void OnDisable()\n        {\n            base.OnDisable();\n            if (m_impl != null)\n            {\n                m_impl.OnDisableInternal();\n            }\n        }\n\n\n        protected override void OnOpen(object arg = null)\n        {\n            base.OnOpen(arg);\n            if (m_impl != null)\n            {\n                m_impl.OnOpenInternal(arg);\n            }\n        }\n\n        protected override void OnClose(object arg = null)\n        {\n            base.OnClose(arg);\n            if (m_impl != null)\n            {\n                m_impl.OnCloseInternal(arg);\n            }\n        }\n\n\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/UIILR/ILRUIPageAdaptor.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing AppDomain = ILRuntime.Runtime.Enviorment.AppDomain;\n\n\nnamespace SGF.Unity.ILR.UIILR\n{\n    public class ILRUIPageAdaptor : CrossBindingAdaptor\n    {\n        public override Type BaseCLRType\n        {\n            get { return typeof(ILRUIPage); }\n        }\n\n        public override Type AdaptorType\n        {\n            get { return typeof(Adaptor); }\n        }\n\n        public override object CreateCLRInstance(AppDomain appdomain, ILTypeInstance instance)\n        {\n            return new Adaptor(appdomain, instance); //创建一个新的实例\n        }\n\n\n\n        class Adaptor : ILRUIPanelAdaptor.Adaptor\n        {\n            private ILTypeInstance m_instance;\n            private AppDomain m_appdomain;\n            private object[] m_args = new object[1];\n\n            public Adaptor(AppDomain appdomain, ILTypeInstance instance)\n                :base(appdomain, instance)\n            {\n                this.m_appdomain = appdomain;\n                this.m_instance = instance;\n            }\n            \n            //==============================================================================\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/UIILR/ILRUIPanel.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing SGF.Unity.UI;\n\nnamespace SGF.Unity.ILR.UIILR\n{\n    public class ILRUIPanel\n    {\n        private UIPanel m_base;\n        public UIPanel Base{get { return m_base; }}\n\n\n\n        protected virtual void OnAwake() { }\n\n        internal void OnAwakeInternal(UIPanel _base)\n        {\n            m_base = _base;\n            OnAwake();\n        }\n\n\n        protected virtual void OnDestroy() { }\n        internal void OnDestroyInternal() { OnDestroy(); }\n\n\n        protected virtual void OnOpen(object arg = null) { }\n        internal void OnOpenInternal(object arg) { OnOpen(arg); }\n\n        protected virtual void OnClose(object arg = null) { }\n        internal void OnCloseInternal(object arg) { OnClose(arg); }\n\n\n\n        protected virtual void OnEnable() { }\n        internal void OnEnableInternal() { OnEnable(); }\n\n        protected virtual void OnDisable() { }\n        internal void OnDisableInternal() { OnDisable(); }\n\n\n    }\n\n\n\n\n\n\n    public class ILRUIPanelBridge : UIPanel\n    {\n\n        public string AssemblyName = \"\";\n        public string Namespace = \"\";\n        public string TypeName = \"\";\n\n\n        private ILRUIPanel m_impl;\n\n        protected override void OnAwake()\n        {\n            base.OnAwake();\n\n            string fullName = Namespace + \".\" + TypeName;\n            m_impl = ILRManager.CreateInstance(fullName, AssemblyName) as ILRUIPanel;\n            if (m_impl == null)\n            {\n                Debuger.LogError(\"无法在Assembly[{0}]中创建实例:{1}\", AssemblyName, fullName);\n            }\n            else\n            {\n                m_impl.OnAwakeInternal(this);\n            }\n        }\n\n\n        protected override void OnDestroy()\n        {\n            base.OnDestroy();\n            if (m_impl != null)\n            {\n                m_impl.OnDestroyInternal();\n            }\n        }\n\n        protected override void OnEnable()\n        {\n            base.OnEnable();\n            if (m_impl != null)\n            {\n                m_impl.OnEnableInternal();\n            }\n        }\n\n        protected override void OnDisable()\n        {\n            base.OnDisable();\n            if (m_impl != null)\n            {\n                m_impl.OnDisableInternal();\n            }\n        }\n\n\n        protected override void OnOpen(object arg = null)\n        {\n            base.OnOpen(arg);\n            if (m_impl != null)\n            {\n                m_impl.OnOpenInternal(arg);\n            }\n        }\n\n        protected override void OnClose(object arg = null)\n        {\n            base.OnClose(arg);\n            if (m_impl != null)\n            {\n                m_impl.OnCloseInternal(arg);\n            }\n        }\n\n\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/UIILR/ILRUIPanelAdaptor.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing AppDomain = ILRuntime.Runtime.Enviorment.AppDomain;\n\nnamespace SGF.Unity.ILR.UIILR\n{\n    public class ILRUIPanelAdaptor : CrossBindingAdaptor\n    {\n        public override Type BaseCLRType\n        {\n            get { return typeof(ILRUIPanel); }\n        }\n\n        public override Type AdaptorType\n        {\n            get { return typeof(Adaptor); }\n        }\n\n        public override object CreateCLRInstance(AppDomain appdomain, ILTypeInstance instance)\n        {\n            return new Adaptor(appdomain, instance); //创建一个新的实例\n        }\n\n\n\n        internal class Adaptor : ILRUIPage, CrossBindingAdaptorType\n        {\n            ILTypeInstance m_instance;\n            AppDomain m_appdomain;\n\n            public ILTypeInstance ILInstance\n            {\n                get { return m_instance; }\n            }\n\n            //缓存这个数组来避免调用时的GC Alloc\n            private object[] m_args = new object[1];\n\n            public Adaptor(AppDomain appdomain, ILTypeInstance instance)\n            {\n                this.m_appdomain = appdomain;\n                this.m_instance = instance;\n            }\n\n\n\n\n            //==============================================================================\n            private IMethod mToString;\n\n            private bool mToStringInvokeing;\n\n            public override string ToString()\n            {\n                if (mToString == null)\n                {\n                    mToString = m_instance.Type.GetMethod(\"ToString\", 0);\n                }\n\n                if (mToString != null && !mToStringInvokeing)\n                {\n                    mToStringInvokeing = true;\n                    var result = m_appdomain.Invoke(mToString, m_instance) as string;\n                    mToStringInvokeing = false;\n                    return result;\n                }\n                else\n                {\n                    return m_instance.Type.FullName;\n                }\n\n            }\n\n\n            //==============================================================================\n\n            private IMethod m_miOnAwake;\n\n            private bool m_isOnAwakeInvoking;\n            protected override void OnAwake()\n            {\n                if (m_miOnAwake == null)\n                {\n                    m_miOnAwake = m_instance.Type.GetMethod(\"OnAwake\", 0);\n                }\n                if (m_miOnAwake != null && !m_isOnOpenInvoking)\n                {\n                    m_isOnAwakeInvoking = true;\n                    m_appdomain.Invoke(m_miOnAwake, m_instance);\n                    m_isOnAwakeInvoking = false;\n                }\n                else\n                {\n                    base.OnAwake();\n                }\n            }\n            //==============================================================================\n\n            private IMethod m_miOnOpen;\n\n            private bool m_isOnOpenInvoking;\n            protected override void OnOpen(object args = null)\n            {\n                Debuger.Log(args);\n\n                if (m_miOnOpen == null)\n                {\n                    m_miOnOpen = m_instance.Type.GetMethod(\"OnOpen\", 1);\n                }\n                if (m_miOnOpen != null && !m_isOnOpenInvoking)\n                {\n                    m_isOnOpenInvoking = true;\n                    m_args[0] = args;\n                    m_appdomain.Invoke(m_miOnOpen, m_instance, m_args);\n                    m_isOnOpenInvoking = false;\n                }\n                else\n                {\n                    base.OnOpen(args);\n                }\n            }\n\n            //==============================================================================\n\n            private IMethod m_miOnClose;\n\n            private bool m_isOnCloseInvoking;\n            protected override void OnClose(object args = null)\n            {\n                Debuger.Log(args);\n\n                if (m_miOnClose == null)\n                {\n                    m_miOnClose = m_instance.Type.GetMethod(\"OnClose\", 1);\n                }\n                if (m_miOnClose != null && !m_isOnCloseInvoking)\n                {\n                    m_isOnCloseInvoking = true;\n                    m_args[0] = args;\n                    m_appdomain.Invoke(m_miOnClose, m_instance, m_args);\n                    m_isOnCloseInvoking = false;\n                }\n                else\n                {\n                    base.OnClose(args);\n                }\n            }\n\n\n            //==============================================================================\n\n\n\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/UIILR/ILRUIWidget.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing SGF.Unity.UI;\n\nnamespace SGF.Unity.ILR.UIILR\n{\n    public class ILRUIWidget:ILRUIPanel\n    {\n        \n    }\n\n    public class ILRUIWidgetBridge : UIWidget\n    {\n        public string AssemblyName = \"\";\n        public string Namespace = \"\";\n        public string TypeName = \"\";\n\n\n        private ILRUIPanel m_impl;\n\n        protected override void OnAwake()\n        {\n            base.OnAwake();\n\n            string fullName = Namespace + \".\" + TypeName;\n            m_impl = ILRManager.CreateInstance(fullName, AssemblyName) as ILRUIPanel;\n            if (m_impl == null)\n            {\n                Debuger.LogError(\"无法在Assembly[{0}]中创建实例:{1}\", AssemblyName, fullName);\n            }\n            else\n            {\n                m_impl.OnAwakeInternal(this);\n            }\n        }\n\n\n        protected override void OnDestroy()\n        {\n            base.OnDestroy();\n            if (m_impl != null)\n            {\n                m_impl.OnDestroyInternal();\n            }\n        }\n\n        protected override void OnEnable()\n        {\n            base.OnEnable();\n            if (m_impl != null)\n            {\n                m_impl.OnEnableInternal();\n            }\n        }\n\n        protected override void OnDisable()\n        {\n            base.OnDisable();\n            if (m_impl != null)\n            {\n                m_impl.OnDisableInternal();\n            }\n        }\n\n\n        protected override void OnOpen(object arg = null)\n        {\n            base.OnOpen(arg);\n            if (m_impl != null)\n            {\n                m_impl.OnOpenInternal(arg);\n            }\n        }\n\n        protected override void OnClose(object arg = null)\n        {\n            base.OnClose(arg);\n            if (m_impl != null)\n            {\n                m_impl.OnCloseInternal(arg);\n            }\n        }\n\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/UIILR/ILRUIWidgetAdaptor.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing AppDomain = ILRuntime.Runtime.Enviorment.AppDomain;\n\nnamespace SGF.Unity.ILR.UIILR\n{\n\n    public class ILRUIWidgetAdaptor : CrossBindingAdaptor\n    {\n        public override Type BaseCLRType\n        {\n            get { return typeof(ILRUIWidget); }\n        }\n\n        public override Type AdaptorType\n        {\n            get { return typeof(Adaptor); }\n        }\n\n        public override object CreateCLRInstance(AppDomain appdomain, ILTypeInstance instance)\n        {\n            return new Adaptor(appdomain, instance); //创建一个新的实例\n        }\n\n\n\n        class Adaptor : ILRUIPanelAdaptor.Adaptor\n        {\n            private ILTypeInstance m_instance;\n            private AppDomain m_appdomain;\n            private object[] m_args = new object[1];\n\n            public Adaptor(AppDomain appdomain, ILTypeInstance instance)\n                : base(appdomain, instance)\n            {\n                this.m_appdomain = appdomain;\n                this.m_instance = instance;\n            }\n\n            //==============================================================================\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/ILR/UIILR/ILRUIWindow.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\n\nusing SGF.Unity.UI;\n\nnamespace SGF.Unity.ILR.UIILR\n{\n\n    public class ILRUIWindow : ILRUIPanel\n    {\n\n    }\n\n\n    public class ILRUIWindowBridge : UIWindow\n    {\n        public string AssemblyName = \"\";\n        public string Namespace = \"\";\n        public string TypeName = \"\";\n\n\n        private ILRUIPanel m_impl;\n\n        protected override void OnAwake()\n        {\n            base.OnAwake();\n\n            string fullName = Namespace + \".\" + TypeName;\n            m_impl = ILRManager.CreateInstance(fullName, AssemblyName) as ILRUIPanel;\n            if (m_impl == null)\n            {\n                Debuger.LogError(\"无法在Assembly[{0}]中创建实例:{1}\", AssemblyName, fullName);\n            }\n            else\n            {\n                m_impl.OnAwakeInternal(this);\n            }\n        }\n\n\n        protected override void OnDestroy()\n        {\n            base.OnDestroy();\n            if (m_impl != null)\n            {\n                m_impl.OnDestroyInternal();\n            }\n        }\n\n        protected override void OnEnable()\n        {\n            base.OnEnable();\n            if (m_impl != null)\n            {\n                m_impl.OnEnableInternal();\n            }\n        }\n\n        protected override void OnDisable()\n        {\n            base.OnDisable();\n            if (m_impl != null)\n            {\n                m_impl.OnDisableInternal();\n            }\n        }\n\n\n        protected override void OnOpen(object arg = null)\n        {\n            base.OnOpen(arg);\n            if (m_impl != null)\n            {\n                m_impl.OnOpenInternal(arg);\n            }\n        }\n\n        protected override void OnClose(object arg = null)\n        {\n            base.OnClose(arg);\n            if (m_impl != null)\n            {\n                m_impl.OnCloseInternal(arg);\n            }\n        }\n\n    }\n\n\n}"
  },
  {
    "path": "SGFUnity/ILR/UIILR/ILRUIWindowAdaptor.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing AppDomain = ILRuntime.Runtime.Enviorment.AppDomain;\n\nnamespace SGF.Unity.ILR.UIILR\n{\n\n    public class ILRUIWindowAdaptor : CrossBindingAdaptor\n    {\n        public override Type BaseCLRType\n        {\n            get { return typeof(ILRUIWindow); }\n        }\n\n        public override Type AdaptorType\n        {\n            get { return typeof(Adaptor); }\n        }\n\n        public override object CreateCLRInstance(AppDomain appdomain, ILTypeInstance instance)\n        {\n            return new Adaptor(appdomain, instance); //创建一个新的实例\n        }\n\n\n\n        class Adaptor : ILRUIPanelAdaptor.Adaptor\n        {\n            private ILTypeInstance m_instance;\n            private AppDomain m_appdomain;\n            private object[] m_args = new object[1];\n\n            public Adaptor(AppDomain appdomain, ILTypeInstance instance)\n                : base(appdomain, instance)\n            {\n                this.m_appdomain = appdomain;\n                this.m_instance = instance;\n            }\n\n            //==============================================================================\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/ILRuntime/Adapters/Editor/ILRuntimeCLRBinding.cs",
    "content": "﻿#if UNITY_EDITOR\nusing UnityEditor;\nusing UnityEngine;\nusing System;\nusing System.Text;\nusing System.Collections.Generic;\nusing OT.Foundation;\n\n[System.Reflection.Obfuscation(Exclude = true)]\npublic class ILRuntimeCLRBinding\n{\n    [MenuItem(\"ILRuntime/Generate CLR Binding Code\")]\n    static void GenerateCLRBinding()\n    {\n        List<Type> types = new List<Type>();\n        types.Add(typeof(int));\n        types.Add(typeof(float));\n        types.Add(typeof(long));\n        types.Add(typeof(object));\n        types.Add(typeof(string));\n        types.Add(typeof(Array));\n        types.Add(typeof(Vector2));\n        types.Add(typeof(Vector3));\n        types.Add(typeof(Quaternion));\n        types.Add(typeof(GameObject));\n        types.Add(typeof(UnityEngine.Object));\n        types.Add(typeof(Transform));\n        types.Add(typeof(RectTransform));\n        types.Add(typeof(CLRBindingTestClass));\n        types.Add(typeof(Time));\n        types.Add(typeof(Debug));\n        types.Add(typeof(OT.Foundation.Debuger));\n        //所有DLL内的类型的真实C#类型都是ILTypeInstance\n        types.Add(typeof(List<ILRuntime.Runtime.Intepreter.ILTypeInstance>));\n\n        ILRuntime.Runtime.CLRBinding.BindingCodeGenerator.GenerateBindingCode(types, \"Assets/ILRuntime/Generated\");\n\n    }\n\n    [MenuItem(\"ILRuntime/Generate CLR Binding Code by Analysis\")]\n    static void GenerateCLRBindingByAnalysis()\n    {\n        //用新的分析热更dll调用引用来生成绑定代码\n        ILRuntime.Runtime.Enviorment.AppDomain domain = new ILRuntime.Runtime.Enviorment.AppDomain();\n        using (System.IO.FileStream fs = new System.IO.FileStream(\"Assets/StreamingAssets/HotFix_Project.dll\", System.IO.FileMode.Open, System.IO.FileAccess.Read))\n        {\n            domain.LoadAssembly(fs);\n        }\n        //Crossbind Adapter is needed to generate the correct binding code\n        InitILRuntime(domain);\n        ILRuntime.Runtime.CLRBinding.BindingCodeGenerator.GenerateBindingCode(domain, \"Assets/ILRuntime/Generated\");\n    }\n\n    static void InitILRuntime(ILRuntime.Runtime.Enviorment.AppDomain domain)\n    {\n        //这里需要注册所有热更DLL中用到的跨域继承Adapter，否则无法正确抓取引用\n        domain.RegisterCrossBindingAdaptor(new MonoBehaviourAdapter());\n        domain.RegisterCrossBindingAdaptor(new CoroutineAdapter());\n        domain.RegisterCrossBindingAdaptor(new InheritanceAdapter());\n    }\n}\n#endif\n"
  },
  {
    "path": "SGFUnity/ILRuntime/CLR/Method/CLRMethod.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\n\nusing Mono.Cecil;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.CLR.Utils;\nnamespace ILRuntime.CLR.Method\n{\n    public class CLRMethod : IMethod\n    {\n        MethodInfo def;\n        ConstructorInfo cDef;\n        List<IType> parameters;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n        CLRType declaringType;\n        ParameterInfo[] param;\n        bool isConstructor;\n        CLRRedirectionDelegate redirect;\n        IType[] genericArguments;\n        object[] invocationParam;\n        bool isDelegateInvoke;\n        int hashCode = -1;\n        static int instance_id = 0x20000000;\n\n        public IType DeclearingType\n        {\n            get\n            {\n                return declaringType;\n            }\n        }\n        public string Name\n        {\n            get\n            {\n                return def.Name;\n            }\n        }\n        public bool HasThis\n        {\n            get\n            {\n                return isConstructor ? !cDef.IsStatic : !def.IsStatic;\n            }\n        }\n        public int GenericParameterCount\n        {\n            get\n            {\n                if (def.ContainsGenericParameters && def.IsGenericMethodDefinition)\n                {\n                    return def.GetGenericArguments().Length;\n                }\n                return 0;\n            }\n        }\n        public bool IsGenericInstance\n        {\n            get\n            {\n                return genericArguments != null;\n            }\n        }\n\n        public bool IsDelegateInvoke\n        {\n            get\n            {\n                return isDelegateInvoke;\n            }\n        }\n\n        public bool IsStatic\n        {\n            get { return def.IsStatic; }\n        }\n\n        public CLRRedirectionDelegate Redirection { get { return redirect; } }\n\n        public MethodInfo MethodInfo { get { return def; } }\n\n        public ConstructorInfo ConstructorInfo { get { return cDef; } }\n\n        public IType[] GenericArguments { get { return genericArguments; } }\n\n        internal CLRMethod(MethodInfo def, CLRType type, ILRuntime.Runtime.Enviorment.AppDomain domain)\n        {\n            this.def = def;\n            declaringType = type;\n            this.appdomain = domain;\n            param = def.GetParameters();\n            if (!def.ContainsGenericParameters)\n            {\n                ReturnType = domain.GetType(def.ReturnType.FullName);\n                if (ReturnType == null)\n                {\n                    ReturnType = domain.GetType(def.ReturnType.AssemblyQualifiedName);\n                }\n            }\n            if (type.IsDelegate && def.Name == \"Invoke\")\n                isDelegateInvoke = true;\n            isConstructor = false;\n\n            if (def != null)\n            {\n                if (def.IsGenericMethod && !def.IsGenericMethodDefinition)\n                {\n                    appdomain.RedirectMap.TryGetValue(def.GetGenericMethodDefinition(), out redirect);\n                }\n                else\n                    appdomain.RedirectMap.TryGetValue(def, out redirect);\n            }\n        }\n        internal CLRMethod(ConstructorInfo def, CLRType type, ILRuntime.Runtime.Enviorment.AppDomain domain)\n        {\n            this.cDef = def;\n            declaringType = type;\n            this.appdomain = domain;\n            param = def.GetParameters();\n            if (!def.ContainsGenericParameters)\n            {\n                ReturnType = type;\n            }\n            isConstructor = true;\n\n            if (def != null)\n            {\n                appdomain.RedirectMap.TryGetValue(cDef, out redirect);\n            }\n        }\n\n        public int ParameterCount\n        {\n            get\n            {\n                return param != null ? param.Length : 0;\n            }\n        }\n\n\n        public List<IType> Parameters\n        {\n            get\n            {\n                if (parameters == null)\n                {\n                    InitParameters();\n                }\n                return parameters;\n            }\n        }\n\n        public IType ReturnType\n        {\n            get;\n            private set;\n        }\n\n        public bool IsConstructor\n        {\n            get\n            {\n                return cDef != null;\n            }\n        }\n\n        void InitParameters()\n        {\n            parameters = new List<IType>();\n            foreach (var i in param)\n            {\n                IType type = appdomain.GetType(i.ParameterType.FullName);\n                if (type == null)\n                    type = appdomain.GetType(i.ParameterType.AssemblyQualifiedName);\n                if (i.ParameterType.IsGenericTypeDefinition)\n                {\n                    if (type == null)\n                        type = appdomain.GetType(i.ParameterType.GetGenericTypeDefinition().FullName);\n                    if (type == null)\n                        type = appdomain.GetType(i.ParameterType.GetGenericTypeDefinition().AssemblyQualifiedName);\n                }\n                if (i.ParameterType.ContainsGenericParameters)\n                {\n                    var t = i.ParameterType;\n                    if (t.HasElementType)\n                        t = i.ParameterType.GetElementType();\n                    else if (t.GetGenericArguments().Length > 0)\n                    {\n                        t = t.GetGenericArguments()[0];\n                    }\n                    type = new ILGenericParameterType(t.Name);\n                }\n                if (type == null)\n                    throw new TypeLoadException();\n                parameters.Add(type);\n            }\n        }\n\n        unsafe StackObject* Minus(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a - sizeof(StackObject) * b);\n        }\n\n        public unsafe object Invoke(Runtime.Intepreter.ILIntepreter intepreter, StackObject* esp, IList<object> mStack, bool isNewObj = false)\n        {\n            if (parameters == null)\n            {\n                InitParameters();\n            }\n            int paramCount = ParameterCount;\n            if (invocationParam == null)\n                invocationParam = new object[paramCount];\n            object[] param = invocationParam;\n            for (int i = paramCount; i >= 1; i--)\n            {\n                var p = Minus(esp, i);\n                var obj = this.param[paramCount - i].ParameterType.CheckCLRTypes(StackObject.ToObject(p, appdomain, mStack));\n                obj = ILIntepreter.CheckAndCloneValueType(obj, appdomain);\n                param[paramCount - i] = obj;\n            }\n\n            if (isConstructor)\n            {\n                if (!isNewObj)\n                {\n                    if (!cDef.IsStatic)\n                    {\n                        object instance = declaringType.TypeForCLR.CheckCLRTypes(StackObject.ToObject((Minus(esp, paramCount + 1)), appdomain, mStack));\n                        if (instance == null)\n                            throw new NullReferenceException();\n                        if (instance is CrossBindingAdaptorType && paramCount == 0)//It makes no sense to call the Adaptor's default constructor\n                            return null;\n                        cDef.Invoke(instance, param);\n                        return null;\n                    }\n                    else\n                    {\n                        throw new NotImplementedException();\n                    }\n                }\n                else\n                {\n                    var res = cDef.Invoke(param);\n\n                    FixReference(paramCount, esp, param, mStack);\n                    return res;\n                }\n\n            }\n            else\n            {\n                object instance = null;\n\n                if (!def.IsStatic)\n                {\n                    instance = declaringType.TypeForCLR.CheckCLRTypes(StackObject.ToObject((Minus(esp, paramCount + 1)), appdomain, mStack));\n                    if (instance == null)\n                        throw new NullReferenceException();\n                }\n                object res = null;\n                /*if (redirect != null)\n                    res = redirect(new ILContext(appdomain, intepreter, esp, mStack, this), instance, param, genericArguments);\n                else*/\n                {\n                    res = def.Invoke(instance, param);\n                }\n\n                FixReference(paramCount, esp, param, mStack);\n                return res;\n            }\n        }\n\n        unsafe void FixReference(int paramCount, StackObject* esp, object[] param, IList<object> mStack)\n        {\n            for (int i = paramCount; i >= 1; i--)\n            {\n                var p = Minus(esp, i);\n                var val = param[paramCount - i];\n                switch (p->ObjectType)\n                {\n                    case ObjectTypes.StackObjectReference:\n                        {\n                            var dst = *(StackObject**)&p->Value;\n                            if (dst->ObjectType >= ObjectTypes.Object)\n                            {\n                                var obj = val;\n                                if (obj is CrossBindingAdaptorType)\n                                    obj = ((CrossBindingAdaptorType)obj).ILInstance;\n                                mStack[dst->Value] = obj;\n                            }\n                            else\n                            {\n                                ILIntepreter.UnboxObject(dst, val);\n                            }\n                        }\n                        break;\n                    case ObjectTypes.FieldReference:\n                        {\n                            var obj = mStack[p->Value];\n                            if(obj is ILTypeInstance)\n                            {\n                                ((ILTypeInstance)obj)[p->ValueLow] = val;\n                            }\n                            else\n                            {\n                                var t = appdomain.GetType(obj.GetType()) as CLRType;\n                                t.GetField(p->ValueLow).SetValue(obj, val);\n                            }\n                        }\n                        break;\n                    case ObjectTypes.StaticFieldReference:\n                        {\n                            var t = appdomain.GetType(p->Value);\n                            if(t is ILType)\n                            {\n                                ((ILType)t).StaticInstance[p->ValueLow] = val;\n                            }\n                            else\n                            {\n                                ((CLRType)t).SetStaticFieldValue(p->ValueLow, val);\n                            }\n                        }\n                        break;\n                }\n            }\n        }\n\n        public IMethod MakeGenericMethod(IType[] genericArguments)\n        {\n            Type[] p = new Type[genericArguments.Length];\n            for (int i = 0; i < genericArguments.Length; i++)\n            {\n                p[i] = genericArguments[i].TypeForCLR;\n            }\n            var t = def.MakeGenericMethod(p);\n            var res = new CLRMethod(t, declaringType, appdomain);\n            res.genericArguments = genericArguments;\n            return res;\n        }\n\n        public override string ToString()\n        {\n            if (def != null)\n                return def.ToString();\n            else\n                return cDef.ToString();\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/CLR/Method/ExceptionHandler.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.TypeSystem;\n\nnamespace ILRuntime.CLR.Method\n{\n    enum ExceptionHandlerType\n    {\n        Catch,\n        Finally,\n        Fault,\n    }\n    class ExceptionHandler\n    {\n        public ExceptionHandlerType HandlerType { get; set; }\n\n        public int TryStart { get; set; }\n        public int TryEnd { get; set; }\n        public int HandlerStart { get; set; }\n        public int HandlerEnd { get; set; }\n        public IType CatchType { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/CLR/Method/ILMethod.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nusing Mono.Cecil;\nusing ILRuntime.Runtime.Intepreter.OpCodes;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Debugger;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Reflection;\nnamespace ILRuntime.CLR.Method\n{\n    public class ILMethod : IMethod\n    {\n        OpCode[] body;\n        MethodDefinition def;\n        List<IType> parameters;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n        ILType declaringType;\n        ExceptionHandler[] exceptionHandler;\n        KeyValuePair<string, IType>[] genericParameters;\n        IType[] genericArguments;\n        Dictionary<int, int[]> jumptables;\n        bool isDelegateInvoke;\n        ILRuntimeMethodInfo refletionMethodInfo;\n        ILRuntimeConstructorInfo reflectionCtorInfo;\n        int paramCnt, localVarCnt;\n        Mono.Collections.Generic.Collection<Mono.Cecil.Cil.VariableDefinition> variables;\n        int hashCode = -1;\n        static int instance_id = 0x10000000;\n\n        public MethodDefinition Definition { get { return def; } }\n\n        public Dictionary<int, int[]> JumpTables { get { return jumptables; } }\n\n        internal IDelegateAdapter DelegateAdapter { get; set; }\n\n        internal int StartLine { get; set; }\n\n        internal int EndLine { get; set; }\n\n        public MethodInfo ReflectionMethodInfo\n        {\n            get\n            {\n                if (IsConstructor)\n                    throw new NotSupportedException();\n                if (refletionMethodInfo == null)\n                    refletionMethodInfo = new ILRuntimeMethodInfo(this);\n                return refletionMethodInfo;\n            }\n        }\n\n        public ConstructorInfo ReflectionConstructorInfo\n        {\n            get\n            {\n                if (!IsConstructor)\n                    throw new NotSupportedException();\n                if (reflectionCtorInfo == null)\n                    reflectionCtorInfo = new ILRuntimeConstructorInfo(this);\n                return reflectionCtorInfo;\n            }\n        }\n\n        internal ExceptionHandler[] ExceptionHandler\n        {\n            get\n            {\n                if (body == null)\n                    InitCodeBody();\n                return exceptionHandler;\n            }\n        }\n\n        public string Name\n        {\n            get\n            {\n                return def.Name;\n            }\n        }\n\n        public IType DeclearingType\n        {\n            get\n            {\n                return declaringType;\n            }\n        }\n\n        public bool HasThis\n        {\n            get\n            {\n                return def.HasThis;\n            }\n        }\n        public int GenericParameterCount\n        {\n            get\n            {\n                if (IsGenericInstance)\n                    return 0;\n                return def.GenericParameters.Count;\n            }\n        }\n        public bool IsGenericInstance\n        {\n            get\n            {\n                return genericParameters != null;\n            }\n        }\n        public Mono.Collections.Generic.Collection<Mono.Cecil.Cil.VariableDefinition> Variables\n        {\n            get\n            {\n                return variables;\n            }\n        }\n\n        public KeyValuePair<string, IType>[] GenericArguments { get { return genericParameters; } }\n\n        public IType[] GenericArugmentsArray { get { return genericArguments; } }\n        public ILMethod(MethodDefinition def, ILType type, ILRuntime.Runtime.Enviorment.AppDomain domain)\n        {\n            this.def = def;\n            declaringType = type;\n            if (def.ReturnType.IsGenericParameter)\n            {\n                ReturnType = FindGenericArgument(def.ReturnType.Name);\n            }\n            else\n                ReturnType = domain.GetType(def.ReturnType, type, this);\n            if (type.IsDelegate && def.Name == \"Invoke\")\n                isDelegateInvoke = true;\n            this.appdomain = domain;\n            paramCnt = def.HasParameters ? def.Parameters.Count : 0;\n#if DEBUG\n            if (def.HasBody)\n            {\n                var sp = DebugService.FindSequencePoint(def.Body.Instructions[0]);\n                if (sp != null)\n                {\n                    StartLine = sp.StartLine;\n                    sp = DebugService.FindSequencePoint(def.Body.Instructions[def.Body.Instructions.Count - 1]);\n                    if (sp != null)\n                    {\n                        EndLine = sp.EndLine;\n                    }\n                }\n            }\n#endif\n        }\n\n        public IType FindGenericArgument(string name)\n        {\n            IType res = declaringType.FindGenericArgument(name);\n            if (res == null && genericParameters != null)\n            {\n                foreach (var i in genericParameters)\n                {\n                    if (i.Key == name)\n                        return i.Value;\n                }\n            }\n            else\n                return res;\n            return null;\n        }\n\n        internal OpCode[] Body\n        {\n            get\n            {\n                if (body == null)\n                    InitCodeBody();\n                return body;\n            }\n        }\n\n        public int LocalVariableCount\n        {\n            get\n            {\n                return localVarCnt;\n            }\n        }\n\n        public bool IsConstructor\n        {\n            get\n            {\n                return def.IsConstructor;\n            }\n        }\n\n        public bool IsDelegateInvoke\n        {\n            get\n            {\n                return isDelegateInvoke;\n            }\n        }\n\n        public bool IsStatic\n        {\n            get { return def.IsStatic; }\n        }\n\n        public int ParameterCount\n        {\n            get\n            {\n                return paramCnt;\n            }\n        }\n\n\n        public List<IType> Parameters\n        {\n            get\n            {\n                if (def.HasParameters && parameters == null)\n                {\n                    InitParameters();\n                }\n                return parameters;\n            }\n        }\n\n        public IType ReturnType\n        {\n            get;\n            private set;\n        }\n        void InitCodeBody()\n        {\n            if (def.HasBody)\n            {\n                localVarCnt = def.Body.Variables.Count;\n                body = new OpCode[def.Body.Instructions.Count];\n                Dictionary<Mono.Cecil.Cil.Instruction, int> addr = new Dictionary<Mono.Cecil.Cil.Instruction, int>();\n                for (int i = 0; i < body.Length; i++)\n                {\n                    var c = def.Body.Instructions[i];\n                    OpCode code = new OpCode();\n                    code.Code = (OpCodeEnum)c.OpCode.Code;\n                    addr[c] = i;\n                    body[i] = code;\n                }\n                for (int i = 0; i < body.Length; i++)\n                {\n                    var c = def.Body.Instructions[i];\n                    InitToken(ref body[i], c.Operand, addr);\n                }\n\n                for (int i = 0; i < def.Body.ExceptionHandlers.Count; i++)\n                {\n                    var eh = def.Body.ExceptionHandlers[i];\n                    if (exceptionHandler == null)\n                        exceptionHandler = new Method.ExceptionHandler[def.Body.ExceptionHandlers.Count];\n                    ExceptionHandler e = new ExceptionHandler();\n                    e.HandlerStart = addr[eh.HandlerStart];\n                    e.HandlerEnd = addr[eh.HandlerEnd] - 1;\n                    e.TryStart = addr[eh.TryStart];\n                    e.TryEnd = addr[eh.TryEnd] - 1;\n                    switch (eh.HandlerType)\n                    {\n                        case Mono.Cecil.Cil.ExceptionHandlerType.Catch:\n                            e.CatchType = appdomain.GetType(eh.CatchType, declaringType, this);\n                            e.HandlerType = ExceptionHandlerType.Catch;\n                            break;\n                        case Mono.Cecil.Cil.ExceptionHandlerType.Finally:\n                            e.HandlerType = ExceptionHandlerType.Finally;\n                            break;\n                        case Mono.Cecil.Cil.ExceptionHandlerType.Fault:\n                            e.HandlerType = ExceptionHandlerType.Fault;\n                            break;\n                        default:\n                            throw new NotImplementedException();\n                    }\n                    exceptionHandler[i] = e;\n                    //Mono.Cecil.Cil.ExceptionHandlerType.\n                }\n                //Release Method body to save memory\n                variables = def.Body.Variables;\n                def.Body = null;\n            }\n            else\n                body = new OpCode[0];\n        }\n\n        unsafe void InitToken(ref OpCode code, object token, Dictionary<Mono.Cecil.Cil.Instruction, int> addr)\n        {\n            switch (code.Code)\n            {\n                case OpCodeEnum.Leave:\n                case OpCodeEnum.Leave_S:\n                case OpCodeEnum.Br:\n                case OpCodeEnum.Br_S:\n                case OpCodeEnum.Brtrue:\n                case OpCodeEnum.Brtrue_S:\n                case OpCodeEnum.Brfalse:\n                case OpCodeEnum.Brfalse_S:\n                //比较流程控制\n                case OpCodeEnum.Beq:\n                case OpCodeEnum.Beq_S:\n                case OpCodeEnum.Bne_Un:\n                case OpCodeEnum.Bne_Un_S:\n                case OpCodeEnum.Bge:\n                case OpCodeEnum.Bge_S:\n                case OpCodeEnum.Bge_Un:\n                case OpCodeEnum.Bge_Un_S:\n                case OpCodeEnum.Bgt:\n                case OpCodeEnum.Bgt_S:\n                case OpCodeEnum.Bgt_Un:\n                case OpCodeEnum.Bgt_Un_S:\n                case OpCodeEnum.Ble:\n                case OpCodeEnum.Ble_S:\n                case OpCodeEnum.Ble_Un:\n                case OpCodeEnum.Ble_Un_S:\n                case OpCodeEnum.Blt:\n                case OpCodeEnum.Blt_S:\n                case OpCodeEnum.Blt_Un:\n                case OpCodeEnum.Blt_Un_S:\n                    code.TokenInteger = addr[(Mono.Cecil.Cil.Instruction)token];\n                    break;\n                case OpCodeEnum.Ldc_I4:\n                    code.TokenInteger = (int)token;\n                    break;\n                case OpCodeEnum.Ldc_I4_S:\n                    code.TokenInteger = (sbyte)token;\n                    break;\n                case OpCodeEnum.Ldc_I8:\n                    code.TokenLong = (long)token;\n                    break;\n                case OpCodeEnum.Ldc_R4:\n                    {\n                        float val = (float)token;\n                        code.TokenInteger = *(int*)&val;\n                    }\n                    break;\n                case OpCodeEnum.Ldc_R8:\n                    {\n                        double val = (double)token;\n                        code.TokenLong = *(long*)&val;\n                    }\n                    break;\n                case OpCodeEnum.Stloc:\n                case OpCodeEnum.Stloc_S:\n                case OpCodeEnum.Ldloc:\n                case OpCodeEnum.Ldloc_S:\n                case OpCodeEnum.Ldloca:\n                case OpCodeEnum.Ldloca_S:\n                    {\n                        Mono.Cecil.Cil.VariableDefinition vd = (Mono.Cecil.Cil.VariableDefinition)token;\n                        code.TokenInteger = vd.Index;\n                    }\n                    break;\n                case OpCodeEnum.Ldarg_S:\n                case OpCodeEnum.Ldarg:\n                case OpCodeEnum.Ldarga:\n                case OpCodeEnum.Ldarga_S:\n                case OpCodeEnum.Starg:\n                case OpCodeEnum.Starg_S:\n                    {\n                        Mono.Cecil.ParameterDefinition vd = (Mono.Cecil.ParameterDefinition)token;\n                        code.TokenInteger = vd.Index;\n                        if (HasThis)\n                            code.TokenInteger++;\n                    }\n                    break;\n                case OpCodeEnum.Call:\n                case OpCodeEnum.Newobj:\n                case OpCodeEnum.Ldftn:\n                case OpCodeEnum.Ldvirtftn:\n                case OpCodeEnum.Callvirt:\n                    {\n                        bool invalidToken;\n                        var m = appdomain.GetMethod(token, declaringType, this, out invalidToken);\n                        if (m != null)\n                        {\n                            if (invalidToken)\n                                code.TokenInteger = m.GetHashCode();\n                            else\n                                code.TokenInteger = token.GetHashCode();\n                        }\n                        else\n                        {\n                            //Cannot find method or the method is dummy\n                            MethodReference _ref = (MethodReference)token;\n                            int paramCnt = _ref.HasParameters ? _ref.Parameters.Count : 0;\n                            if (_ref.HasThis)\n                                paramCnt++;\n                            code.TokenLong = paramCnt;\n                        }\n                    }\n                    break;\n                case OpCodeEnum.Constrained:\n                case OpCodeEnum.Box:\n                case OpCodeEnum.Unbox_Any:\n                case OpCodeEnum.Unbox:\n                case OpCodeEnum.Initobj:\n                case OpCodeEnum.Isinst:\n                case OpCodeEnum.Newarr:\n                case OpCodeEnum.Stobj:\n                case OpCodeEnum.Ldobj:\n                    {\n                        code.TokenInteger = GetTypeTokenHashCode(token);\n                    }\n                    break;\n                case OpCodeEnum.Stfld:\n                case OpCodeEnum.Ldfld:\n                case OpCodeEnum.Ldflda:\n                    {\n                        code.TokenLong = appdomain.GetStaticFieldIndex(token, declaringType, this);\n                    }\n                    break;\n\n                case OpCodeEnum.Stsfld:\n                case OpCodeEnum.Ldsfld:\n                case OpCodeEnum.Ldsflda:\n                    {\n                        code.TokenLong = appdomain.GetStaticFieldIndex(token, declaringType, this);\n                    }\n                    break;\n                case OpCodeEnum.Ldstr:\n                    {\n                        long hashCode = appdomain.CacheString(token);\n                        code.TokenLong = hashCode;\n                    }\n                    break;\n                case OpCodeEnum.Ldtoken:\n                    {\n                        if (token is FieldReference)\n                        {\n                            code.TokenInteger = 0;\n                            code.TokenLong = appdomain.GetStaticFieldIndex(token, declaringType, this);\n                        }\n                        else if (token is TypeReference)\n                        {\n                            code.TokenInteger = 1;\n                            code.TokenLong = GetTypeTokenHashCode(token);\n                        }\n                        else\n                            throw new NotImplementedException();\n                    }\n                    break;\n                case OpCodeEnum.Switch:\n                    {\n                        PrepareJumpTable(token, addr);\n                        code.TokenInteger = token.GetHashCode();\n                    }\n                    break;\n            }\n        }\n\n        int GetTypeTokenHashCode(object token)\n        {\n            var t = appdomain.GetType(token, declaringType, this);\n            bool isGenericParameter = CheckHasGenericParamter(token);\n            if (t == null && isGenericParameter)\n            {\n                t = FindGenericArgument(((TypeReference)token).Name);\n            }\n            if (t != null)\n            {\n                if (t is ILType)\n                {\n                    if (((ILType)t).TypeReference.HasGenericParameters)\n                        return t.GetHashCode();\n                    else\n                        return ((ILType)t).TypeReference.GetHashCode();\n                }\n                else if (isGenericParameter)\n                {\n                    return t.GetHashCode();\n                }\n                else\n                    return token.GetHashCode();\n            }\n            return 0;\n        }\n\n        bool CheckHasGenericParamter(object token)\n        {\n            if (token is TypeReference)\n            {\n                TypeReference _ref = ((TypeReference)token);\n                if (_ref.IsGenericParameter)\n                    return true;\n                if (_ref.IsGenericInstance)\n                {\n                    GenericInstanceType gi = (GenericInstanceType)_ref;\n                    foreach(var i in gi.GenericArguments)\n                    {\n                        if (CheckHasGenericParamter(i))\n                            return true;\n                    }\n                    return false;\n                }\n                else\n                    return false;\n            }\n            else\n                return false;\n        }\n\n        void PrepareJumpTable(object token, Dictionary<Mono.Cecil.Cil.Instruction, int> addr)\n        {\n            int hashCode = token.GetHashCode();\n\n            if (jumptables == null)\n                jumptables = new Dictionary<int, int[]>();\n            if (jumptables.ContainsKey(hashCode))\n                return;\n            Mono.Cecil.Cil.Instruction[] e = token as Mono.Cecil.Cil.Instruction[];\n            int[] addrs = new int[e.Length];\n            for (int i = 0; i < e.Length; i++)\n            {\n                addrs[i] = addr[e[i]];\n            }\n\n            jumptables[hashCode] = addrs;\n        }\n\n        void InitParameters()\n        {\n            parameters = new List<IType>();\n            foreach (var i in def.Parameters)\n            {\n                IType type = null;\n                bool isByRef = false;\n                bool isArray = false;\n                TypeReference pt = i.ParameterType;\n                if (i.ParameterType.IsByReference)\n                {\n                    isByRef = true;\n                    pt = pt.GetElementType();\n                }\n                if (i.ParameterType.IsArray)\n                {\n                    isArray = true;\n                    pt = pt.GetElementType();\n                }\n                if (pt.IsGenericParameter)\n                {\n                    type = FindGenericArgument(pt.Name);\n                    if (type == null && def.HasGenericParameters)\n                    {\n                        bool found = false;\n                        foreach (var j in def.GenericParameters)\n                        {\n                            if (j.Name == pt.Name)\n                            {\n                                found = true;\n                                break;\n                            }\n                        }\n                        if (found)\n                        {\n                            type = new ILGenericParameterType(pt.Name);\n                        }\n                        else\n                            throw new NotSupportedException(\"Cannot find Generic Parameter \" + pt.Name + \" in \" + def.FullName);\n                    }\n\n                    if (isByRef)\n                        type = type.MakeByRefType();\n                    if (isArray)\n                        type = type.MakeArrayType();\n                }\n                else\n                    type = appdomain.GetType(i.ParameterType, declaringType, this);\n                parameters.Add(type);\n            }\n        }\n\n        public IMethod MakeGenericMethod(IType[] genericArguments)\n        {\n            KeyValuePair<string, IType>[] genericParameters = new KeyValuePair<string, IType>[genericArguments.Length];\n            for (int i = 0; i < genericArguments.Length; i++)\n            {\n                string name = def.GenericParameters[i].Name;\n                IType val = genericArguments[i];\n                genericParameters[i] = new KeyValuePair<string, IType>(name, val);\n            }\n\n            ILMethod m = new ILMethod(def, declaringType, appdomain);\n            m.genericParameters = genericParameters;\n            m.genericArguments = genericArguments;\n            if (m.def.ReturnType.IsGenericParameter)\n            {\n                m.ReturnType = m.FindGenericArgument(m.def.ReturnType.Name);\n            }\n            return m;\n        }\n\n        public override string ToString()\n        {\n            StringBuilder sb = new StringBuilder();\n            sb.Append(declaringType.FullName);\n            sb.Append('.');\n            sb.Append(Name);\n            sb.Append('(');\n            bool isFirst = true;\n            if (parameters == null)\n                InitParameters();\n            for (int i = 0; i < parameters.Count; i++)\n            {\n                if (isFirst)\n                    isFirst = false;\n                else\n                    sb.Append(\", \");\n                sb.Append(parameters[i].Name);\n                sb.Append(' ');\n                sb.Append(def.Parameters[i].Name);\n            }\n            sb.Append(')');\n            return sb.ToString();\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/CLR/Method/IMethod.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.TypeSystem;\nnamespace ILRuntime.CLR.Method\n{\n    public interface IMethod\n    {\n        string Name { get; }\n        int ParameterCount { get; }\n\n        bool HasThis { get; }\n\n        IType DeclearingType { get; }\n\n        IType ReturnType { get; }\n        List<IType> Parameters { get; }\n\n        int GenericParameterCount { get; }\n\n        bool IsGenericInstance { get; }\n\n        bool IsConstructor { get; }\n\n        bool IsDelegateInvoke { get; }\n\n        bool IsStatic { get; }\n\n        IMethod MakeGenericMethod(IType[] genericArguments);\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/CLR/TypeSystem/CLRType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nusing Mono.Cecil;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Reflection;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.CLR.TypeSystem\n{\n    public class CLRType : IType\n    {\n        Type clrType;\n        bool isPrimitive, isValueType;\n        Dictionary<string, List<CLRMethod>> methods;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n        List<CLRMethod> constructors;\n        KeyValuePair<string, IType>[] genericArguments;\n        List<CLRType> genericInstances;\n        Dictionary<string, int> fieldMapping;\n        Dictionary<int, FieldInfo> fieldInfoCache;\n        Dictionary<int, CLRFieldGetterDelegate> fieldGetterCache;\n        Dictionary<int, CLRFieldSetterDelegate> fieldSetterCache;\n        Dictionary<int, int> fieldIdxMapping;\n        IType[] orderedFieldTypes;\n\n        CLRMemberwiseCloneDelegate memberwiseCloneDelegate;\n        CLRCreateDefaultInstanceDelegate createDefaultInstanceDelegate;\n        CLRCreateArrayInstanceDelegate createArrayInstanceDelegate;\n        Dictionary<int, int> fieldTokenMapping;\n        IType byRefType, arrayType, elementType;\n        IType[] interfaces;\n        bool isDelegate;\n        IType baseType;\n        bool isBaseTypeInitialized = false, interfaceInitialized = false, valueTypeBinderGot = false;\n        ILRuntimeWrapperType wraperType;\n        ValueTypeBinder valueTypeBinder;\n\n        int hashCode = -1;\n        static int instance_id = 0x20000000;\n\n        public Dictionary<int, FieldInfo> Fields\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return fieldInfoCache;\n            }\n        }\n\n        public Dictionary<int, int> FieldIndexMapping\n        {\n            get { return fieldIdxMapping; }\n        }\n\n        public IType[] OrderedFieldTypes\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return orderedFieldTypes;\n            }\n        }\n\n        public int TotalFieldCount\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return fieldIdxMapping.Count;\n            }\n        }\n\n        public ILRuntime.Runtime.Enviorment.AppDomain AppDomain\n        {\n            get\n            {\n                return appdomain;\n            }\n        }\n\n        public CLRType(Type clrType, Runtime.Enviorment.AppDomain appdomain)\n        {\n            this.clrType = clrType;\n            this.appdomain = appdomain;\n            isPrimitive = clrType.IsPrimitive;\n            isValueType = clrType.IsValueType;\n            isDelegate = clrType.BaseType == typeof(MulticastDelegate);\n        }\n\n        public bool IsGenericInstance\n        {\n            get\n            {\n                return genericArguments != null;\n            }\n        }\n\n        public KeyValuePair<string, IType>[] GenericArguments\n        {\n            get\n            {\n                return genericArguments;\n            }\n        }\n\n        public IType ElementType { get { return elementType; } }\n\n        public bool HasGenericParameter\n        {\n            get\n            {\n                return clrType.ContainsGenericParameters;\n            }\n        }\n\n        public Type TypeForCLR\n        {\n            get\n            {\n                return clrType;\n            }\n        }\n\n        public Type ReflectionType\n        {\n            get\n            {\n                if (wraperType == null)\n                    wraperType = new ILRuntimeWrapperType(this);\n                return wraperType;\n            }\n        }\n        public IType ByRefType\n        {\n            get\n            {\n                return byRefType;\n            }\n        }\n        public IType ArrayType\n        {\n            get\n            {\n                return arrayType;\n            }\n        }\n\n        public bool IsArray\n        {\n            get;private set;\n        }\n\n        public bool IsValueType\n        {\n            get\n            {\n                return isValueType;\n            }\n        }\n        public bool IsDelegate\n        {\n            get\n            {\n                return isDelegate;\n            }\n        }\n\n        public bool IsPrimitive\n        {\n            get\n            {\n                return isPrimitive;\n            }\n        }\n        public string FullName\n        {\n            get\n            {\n                return clrType.FullName;\n            }\n        }\n        public string Name\n        {\n            get\n            {\n                return clrType.Name;\n            }\n        }\n\n        public IType BaseType\n        {\n            get\n            {\n                if (!isBaseTypeInitialized)\n                    InitializeBaseType();\n                return baseType;\n            }\n        }\n\n        public IType[] Implements\n        {\n            get\n            {\n                if (!interfaceInitialized)\n                    InitializeInterfaces();\n                return interfaces;\n            }\n        }\n\n        public ValueTypeBinder ValueTypeBinder\n        {\n            get\n            {\n                if (clrType.IsValueType)\n                {\n                    if (!valueTypeBinderGot)\n                    {\n                        valueTypeBinderGot = true;\n                        if (appdomain.ValueTypeBinders.TryGetValue(clrType, out valueTypeBinder))\n                            valueTypeBinder.CLRType = this;\n                    }\n                    return valueTypeBinder;\n                }\n                else\n                    return null;\n            }\n        }\n\n        public object PerformMemberwiseClone(object target)\n        {\n            if (memberwiseCloneDelegate == null)\n            {\n                if (!AppDomain.MemberwiseCloneMap.TryGetValue(this.clrType, out memberwiseCloneDelegate))\n                {\n                    var memberwiseClone = clrType.GetMethod(\"MemberwiseClone\", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);\n\n                    if (memberwiseClone != null)\n                    {\n                        memberwiseCloneDelegate = (ref object t) => memberwiseClone.Invoke(t, null);\n                    }\n                    else\n                    {\n                        throw new InvalidOperationException(\"Memberwise clone method not found for \" + clrType.FullName);\n                    }\n                }\n            }\n\n            return memberwiseCloneDelegate(ref target);\n        }\n\n        void InitializeBaseType()\n        {\n            baseType = appdomain.GetType(clrType.BaseType);\n            if (baseType.TypeForCLR == typeof(Enum) || baseType.TypeForCLR == typeof(object) || baseType.TypeForCLR == typeof(ValueType) || baseType.TypeForCLR == typeof(System.Enum))\n            {//都是这样，无所谓\n                baseType = null;\n            }\n            isBaseTypeInitialized = true;\n        }\n\n        void InitializeInterfaces()\n        {\n            interfaceInitialized = true;\n            var arr = clrType.GetInterfaces();\n            if (arr.Length >0)\n            {\n                interfaces = new IType[arr.Length];\n                for (int i = 0; i < interfaces.Length; i++)\n                {\n                    interfaces[i] = appdomain.GetType(arr[i]);\n                }\n            }\n        }\n\n        public object GetFieldValue(int hash, object target)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n\n            var getter = GetFieldGetter(hash);\n            if (getter != null)\n            {\n                return getter(ref target);\n            }\n\n            var fieldinfo = GetField(hash);\n            if (fieldinfo != null)\n            {\n                return fieldinfo.GetValue(target);\n            }\n\n            return null;\n        }\n\n        public void SetStaticFieldValue(int hash, object value)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n\n            var setter = GetFieldSetter(hash);\n            object target = null;\n            if (setter != null)\n            {\n                setter(ref target, value);\n                return;\n            }\n\n            var fieldInfo = GetField(hash);\n            if (fieldInfo != null)\n            {\n                fieldInfo.SetValue(null, value);\n            }\n        }\n\n        public unsafe void SetFieldValue(int hash, ref object target, object value)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n\n            var setter = GetFieldSetter(hash);\n            if (setter != null)\n            {\n                setter(ref target, value);\n                return;\n            }\n\n            var fieldInfo = GetField(hash);\n            if (fieldInfo != null)\n            {\n                fieldInfo.SetValue(target, value);\n            }\n        }\n\n        private CLRFieldGetterDelegate GetFieldGetter(int hash)\n        {\n            var dic = fieldGetterCache;\n            CLRFieldGetterDelegate res;\n            if (dic != null && dic.TryGetValue(hash, out res))\n                return res;\n            else if (BaseType != null)\n                return ((CLRType)BaseType).GetFieldGetter(hash);\n            else\n                return null;\n        }\n\n        private CLRFieldSetterDelegate GetFieldSetter(int hash)\n        {\n            var dic = fieldSetterCache;\n            CLRFieldSetterDelegate res;\n            if (dic != null && dic.TryGetValue(hash, out res))\n                return res;\n            else if (BaseType != null)\n                return ((CLRType)BaseType).GetFieldSetter(hash);\n            else\n                return null;\n        }\n\n        public FieldInfo GetField(int hash)\n        {\n            var dic = Fields;\n            FieldInfo res;\n            if (dic.TryGetValue(hash, out res))\n                return res;\n            else if (BaseType != null)\n                return ((CLRType)BaseType).GetField(hash);\n            else\n                return null;\n        }\n\n        void InitializeMethods()\n        {\n            methods = new Dictionary<string, List<CLRMethod>>();\n            constructors = new List<CLRMethod>();\n            foreach (var i in clrType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))\n            {\n                if (i.IsPrivate)\n                    continue;\n                List<CLRMethod> lst;\n                if (!methods.TryGetValue(i.Name, out lst))\n                {\n                    lst = new List<CLRMethod>();\n                    methods[i.Name] = lst;\n                }\n                lst.Add(new CLRMethod(i, this, appdomain));\n            }\n            foreach (var i in clrType.GetConstructors())\n            {\n                constructors.Add(new CLRMethod(i, this, appdomain));\n            }\n        }\n        public List<IMethod> GetMethods()\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<IMethod> res = new List<IMethod>();\n            foreach (var i in methods)\n            {\n                foreach (var j in i.Value)\n                    res.Add(j);\n            }\n\n            return res;\n        }\n\n        public IMethod GetVirtualMethod(IMethod method)\n        {\n            var m = GetMethod(method.Name, method.Parameters, null, method.ReturnType);\n            if (m == null)\n            {\n                return method;\n            }\n            else\n                return m;\n        }\n\n        void InitializeFields()\n        {\n            fieldMapping = new Dictionary<string, int>();\n            fieldInfoCache = new Dictionary<int, FieldInfo>();\n\n            var fields = clrType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);\n            int idx = 0;\n            bool hasValueTypeBinder = ValueTypeBinder != null;\n            if (hasValueTypeBinder)\n            {\n                fieldIdxMapping = new Dictionary<int, int>();\n                orderedFieldTypes = new IType[fields.Length];\n            }\n            foreach (var i in fields)\n            {\n                int hashCode = i.GetHashCode();\n\n                if (i.IsPublic || i.IsFamily || hasValueTypeBinder)\n                {\n                    fieldMapping[i.Name] = hashCode;\n                    fieldInfoCache[hashCode] = i;\n                }\n                if (hasValueTypeBinder && !i.IsStatic)\n                {\n                    orderedFieldTypes[idx] = appdomain.GetType(i.FieldType);\n                    fieldIdxMapping[hashCode] = idx++;\n                }\n\n                CLRFieldGetterDelegate getter;\n                if (AppDomain.FieldGetterMap.TryGetValue(i, out getter))\n                {\n                    if (fieldGetterCache == null) fieldGetterCache = new Dictionary<int, CLRFieldGetterDelegate>();\n                    fieldGetterCache[hashCode] = getter;\n                }\n\n                CLRFieldSetterDelegate setter;\n                if (AppDomain.FieldSetterMap.TryGetValue(i, out setter))\n                {\n                    if (fieldSetterCache == null) fieldSetterCache = new Dictionary<int, CLRFieldSetterDelegate>();\n                    fieldSetterCache[hashCode] = setter;\n                }\n            }\n        }\n        public int GetFieldIndex(object token)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n            int idx;\n            int hashCode = token.GetHashCode();\n            if (fieldTokenMapping == null)\n                fieldTokenMapping = new Dictionary<int, int>();\n            if (fieldTokenMapping.TryGetValue(hashCode, out idx))\n                return idx;\n            FieldReference f = token as FieldReference;\n            if (fieldMapping.TryGetValue(f.Name, out idx))\n            {\n                fieldTokenMapping[hashCode] = idx;\n                return idx;\n            }\n\n            return -1;\n        }\n        public IType FindGenericArgument(string key)\n        {\n            if (genericArguments != null)\n            {\n                foreach (var i in genericArguments)\n                {\n                    if (i.Key == key)\n                        return i.Value;\n                }\n            }\n            return null;\n        }\n        public IMethod GetMethod(string name, int paramCount, bool declaredOnly = false)\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<CLRMethod> lst;\n            if (methods.TryGetValue(name, out lst))\n            {\n                foreach (var i in lst)\n                {\n                    if (i.ParameterCount == paramCount)\n                        return i;\n                }\n            }\n            return null;\n        }\n\n        public IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false)\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<CLRMethod> lst;\n            IMethod genericMethod = null;\n            if (methods.TryGetValue(name, out lst))\n            {\n                foreach (var i in lst)\n                {\n                    if (i.ParameterCount == param.Count)\n                    {\n                        bool match = true;\n                        if (genericArguments != null && i.GenericParameterCount == genericArguments.Length)\n                        {\n                            for (int j = 0; j < param.Count; j++)\n                            {\n                                var p = i.Parameters[j].TypeForCLR;\n                                var q = param[j].TypeForCLR;\n\n                                if (i.Parameters[j].HasGenericParameter)\n                                {\n                                    //TODO should match the generic parameters;\n                                    continue;\n                                }\n                                if (q != p)\n                                {\n                                    match = false;\n                                    break;\n                                }\n                            }\n                            if (match && genericMethod == null)\n                            {\n                                genericMethod = i;\n                            }\n                        }\n                        else\n                        {\n                            if (genericArguments == null)\n                                match = i.GenericArguments == null;\n                            else\n                            {\n                                if (i.GenericArguments == null)\n                                    match = false;\n                                else\n                                    match = i.GenericArguments.Length == genericArguments.Length;\n                            }\n                            for (int j = 0; j < param.Count; j++)\n                            {\n                                var typeA = param[j].TypeForCLR.IsByRef ? param[j].TypeForCLR.GetElementType() : param[j].TypeForCLR;\n                                var typeB = i.Parameters[j].TypeForCLR.IsByRef ? i.Parameters[j].TypeForCLR.GetElementType() : i.Parameters[j].TypeForCLR;\n\n                                if (typeA != typeB)\n                                {\n                                    match = false;\n                                    break;\n                                }\n                            }\n                            if (match)\n                            {\n                                match = returnType == null || i.ReturnType.TypeForCLR == returnType.TypeForCLR;\n                            }\n                            if (match)\n                            {\n\n                                if (i.IsGenericInstance)\n                                {\n                                    if (i.GenericArguments.Length == genericArguments.Length)\n                                    {\n                                        for (int j = 0; j < genericArguments.Length; j++)\n                                        {\n                                            if (i.GenericArguments[j] != genericArguments[j])\n                                            {\n                                                match = false;\n                                                break;\n                                            }\n                                        }\n                                        if (match)\n                                            return i;\n                                    }\n                                }\n                                else\n                                    return i;\n                            }\n                        }\n                    }\n                }\n            }\n            if (genericArguments != null && genericMethod != null)\n            {\n                var m = genericMethod.MakeGenericMethod(genericArguments);\n                lst.Add((CLRMethod)m);\n                return m;\n            }\n            return null;\n        }\n        public bool CanAssignTo(IType type)\n        {\n            if (this == type)\n            {\n                return true;\n            }\n            else\n                return false;\n        }\n\n        public IMethod GetConstructor(List<IType> param)\n        {\n            if (constructors == null)\n                InitializeMethods();\n            foreach (var i in constructors)\n            {\n                if (i.ParameterCount == param.Count)\n                {\n                    bool match = true;\n\n                    for (int j = 0; j < param.Count; j++)\n                    {\n                        if (param[j].TypeForCLR != i.Parameters[j].TypeForCLR)\n                        {\n                            match = false;\n                            break;\n                        }\n                    }\n                    if (match)\n                    {\n                        return i;\n                    }\n                }\n            }\n\n            return null;\n        }\n\n        public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)\n        {\n            if (genericInstances == null)\n                genericInstances = new List<CLRType>();\n            foreach (var i in genericInstances)\n            {\n                bool match = true;\n                for (int j = 0; j < genericArguments.Length; j++)\n                {\n                    if (i.genericArguments[j].Value != genericArguments[j].Value)\n                    {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match)\n                    return i;\n            }\n            Type[] args = new Type[genericArguments.Length];\n            for (int i = 0; i < genericArguments.Length; i++)\n            {\n                args[i] = genericArguments[i].Value.TypeForCLR;\n            }\n            Type newType = clrType.MakeGenericType(args);\n            var res = new CLRType(newType, appdomain);\n            res.genericArguments = genericArguments;\n\n            genericInstances.Add(res);\n            return res;\n        }\n\n        public object CreateDefaultInstance()\n        {\n            if (createDefaultInstanceDelegate == null)\n            {\n                if (!AppDomain.CreateDefaultInstanceMap.TryGetValue(clrType, out createDefaultInstanceDelegate))\n                {\n                    createDefaultInstanceDelegate = () => Activator.CreateInstance(TypeForCLR);\n                }\n            }\n\n            return createDefaultInstanceDelegate();\n        }\n\n        public object CreateArrayInstance(int size)\n        {\n            if (createArrayInstanceDelegate == null)\n            {\n                if (!AppDomain.CreateArrayInstanceMap.TryGetValue(clrType, out createArrayInstanceDelegate))\n                {\n                    createArrayInstanceDelegate = s => Array.CreateInstance(TypeForCLR, s);\n                }\n            }\n\n            return createArrayInstanceDelegate(size);\n        }\n\n        public IType MakeByRefType()\n        {\n            if (byRefType == null)\n            {\n                Type t = clrType.MakeByRefType();\n                byRefType = new CLRType(t, appdomain);\n            }\n            return byRefType;\n        }\n        public IType MakeArrayType()\n        {\n            if (arrayType == null)\n            {\n                Type t = clrType.MakeArrayType();\n                arrayType = new CLRType(t, appdomain);\n                ((CLRType)arrayType).elementType = this;\n                ((CLRType)arrayType).IsArray = true;\n            }\n            return arrayType;\n        }\n\n        public IType ResolveGenericType(IType contextType)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n\n        public override string ToString()\n        {\n            return clrType.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/CLR/TypeSystem/ILGenericParameterType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.CLR.TypeSystem\n{\n    class ILGenericParameterType : IType\n    {\n        string name;\n        ILGenericParameterType arrayType;\n        public ILGenericParameterType(string name)\n        {\n            this.name = name;\n        }\n        public bool IsGenericInstance\n        {\n            get { return false; }\n        }\n\n        public KeyValuePair<string, IType>[] GenericArguments\n        {\n            get { return null; }\n        }\n        public bool HasGenericParameter\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        public Type TypeForCLR\n        {\n            get { return typeof(ILGenericParameterType); }\n        }\n\n        public string FullName\n        {\n            get { return name; }\n        }\n\n        public Runtime.Enviorment.AppDomain AppDomain\n        {\n            get { return null; }\n        }\n\n        public Method.IMethod GetMethod(string name, int paramCount, bool declaredOnly = false)\n        {\n            return null;\n        }\n\n        public Method.IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false)\n        {\n            return null;\n        }\n\n        public List<Method.IMethod> GetMethods()\n        {\n            return null;\n        }\n\n        public Method.IMethod GetConstructor(List<IType> param)\n        {\n            return null;\n        }\n\n        public bool CanAssignTo(IType type)\n        {\n            return false;\n        }\n\n        public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)\n        {\n            return null;\n        }\n\n        public IType ResolveGenericType(IType contextType)\n        {\n            throw new NotImplementedException();\n        }\n\n\n        public int GetFieldIndex(object token)\n        {\n            return -1;\n        }\n\n\n        public IType FindGenericArgument(string key)\n        {\n            return null;\n        }\n\n\n        public IType ByRefType\n        {\n            get { throw new NotImplementedException(); }\n        }\n\n        public IType MakeByRefType()\n        {\n            return this;\n        }\n\n\n        public IType ArrayType\n        {\n            get { return arrayType; }\n        }\n\n        public IType MakeArrayType()\n        {\n            if (arrayType == null)\n                arrayType = new ILGenericParameterType(name + \"[]\");\n            return arrayType;\n        }\n\n\n        public bool IsValueType\n        {\n            get { throw new NotImplementedException(); }\n        }\n\n        public bool IsPrimitive\n        {\n            get { return false; }\n        }\n\n        public string Name\n        {\n            get\n            {\n                return name;\n            }\n        }\n\n        public bool IsDelegate\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        public Type ReflectionType\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public IType BaseType\n        {\n            get\n            {\n                return null;\n            }\n        }\n\n        public Method.IMethod GetVirtualMethod(Method.IMethod method)\n        {\n            return method;\n        }\n\n        public bool IsArray\n        {\n            get { return false; }\n        }\n\n        public IType[] Implements\n        {\n            get\n            {\n                return null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/CLR/TypeSystem/ILType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing Mono.Cecil;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Reflection;\n\nnamespace ILRuntime.CLR.TypeSystem\n{\n    public class ILType : IType\n    {\n        Dictionary<string, List<ILMethod>> methods;\n        TypeReference typeRef;\n        TypeDefinition definition;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n        ILMethod staticConstructor;\n        List<ILMethod> constructors;\n        IType[] fieldTypes;\n        FieldDefinition[] fieldDefinitions;\n        IType[] staticFieldTypes;\n        FieldDefinition[] staticFieldDefinitions;\n        Dictionary<string, int> fieldMapping;\n        Dictionary<string, int> staticFieldMapping;\n        ILTypeStaticInstance staticInstance;\n        Dictionary<int, int> fieldTokenMapping = new Dictionary<int, int>();\n        int fieldStartIdx = -1;\n        int totalFieldCnt = -1;\n        KeyValuePair<string, IType>[] genericArguments;\n        IType baseType, byRefType, arrayType, enumType, elementType;\n        Type arrayCLRType, byRefCLRType;\n        IType[] interfaces;\n        bool baseTypeInitialized = false;\n        bool interfaceInitialized = false;\n        List<ILType> genericInstances;\n        bool isDelegate;\n        ILRuntimeType reflectionType;\n        IType firstCLRBaseType, firstCLRInterface;\n        int hashCode = -1;\n        static int instance_id = 0x10000000;\n        public TypeDefinition TypeDefinition { get { return definition; } }\n\n        public TypeReference TypeReference\n        {\n            get { return typeRef; }\n            set\n            {\n                typeRef = value;\n                RetriveDefinitino(value);\n            }\n        }\n\n        public IType BaseType\n        {\n            get\n            {\n                if (!baseTypeInitialized)\n                    InitializeBaseType();\n                return baseType;\n            }\n        }\n\n        public IType[] Implements\n        {\n            get\n            {\n                if (!interfaceInitialized)\n                    InitializeInterfaces();\n                return interfaces;\n            }\n        }\n\n        public ILTypeStaticInstance StaticInstance\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                if (methods == null)\n                    InitializeMethods();\n                return staticInstance;\n            }\n        }\n\n        public IType[] FieldTypes\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return fieldTypes;\n            }\n        }\n\n        public IType[] StaticFieldTypes\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return staticFieldTypes;\n            }\n        }\n\n        public FieldDefinition[] StaticFieldDefinitions\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields();\n                return staticFieldDefinitions;\n            }\n        }\n\n        public Dictionary<string, int> FieldMapping\n        {\n            get\n            {\n                if (fieldMapping == null)\n                    InitializeFields(); return fieldMapping;\n            }\n        }\n\n        public IType FirstCLRBaseType\n        {\n            get\n            {\n                if (!baseTypeInitialized)\n                    InitializeBaseType();\n                return firstCLRBaseType;\n            }\n        }\n\n        public IType FirstCLRInterface\n        {\n            get\n            {\n                if (!interfaceInitialized)\n                    InitializeInterfaces();\n                return firstCLRInterface;\n            }\n        }\n        public bool HasGenericParameter\n        {\n            get\n            {\n                return definition.HasGenericParameters && genericArguments == null;\n            }\n        }\n\n        public Dictionary<string, int> StaticFieldMapping { get { return staticFieldMapping; } }\n        public ILRuntime.Runtime.Enviorment.AppDomain AppDomain\n        {\n            get\n            {\n                return appdomain;\n            }\n        }\n\n        internal int FieldStartIndex\n        {\n            get\n            {\n                if (fieldStartIdx < 0)\n                {\n                    if (BaseType != null)\n                    {\n                        if (BaseType is ILType)\n                        {\n                            fieldStartIdx = ((ILType)BaseType).TotalFieldCount;\n                        }\n                        else\n                            fieldStartIdx = 0;\n                    }\n                    else\n                        fieldStartIdx = 0;\n                }\n                return fieldStartIdx;\n            }\n        }\n\n        public int TotalFieldCount\n        {\n            get\n            {\n                if (totalFieldCnt < 0)\n                {\n                    if (fieldMapping == null)\n                        InitializeFields();\n                    if (BaseType != null)\n                    {\n                        if (BaseType is ILType)\n                        {\n                            totalFieldCnt = ((ILType)BaseType).TotalFieldCount + fieldTypes.Length;\n                        }\n                        else\n                            totalFieldCnt = fieldTypes.Length;\n                    }\n                    else\n                        totalFieldCnt = fieldTypes.Length;\n                }\n                return totalFieldCnt;\n            }\n        }\n\n        /// <summary>\n        /// 初始化IL类型\n        /// </summary>\n        /// <param name=\"def\">MONO返回的类型定义</param>\n        /// <param name=\"domain\">ILdomain</param>\n        public ILType(TypeReference def, Runtime.Enviorment.AppDomain domain)\n        {\n            this.typeRef = def;\n            RetriveDefinitino(def);\n            appdomain = domain;\n        }\n\n        /// <summary>\n        /// 加载类型\n        /// </summary>\n        /// <param name=\"def\"></param>\n        void RetriveDefinitino(TypeReference def)\n        {\n            if (!def.IsGenericParameter)\n            {\n                if (def is TypeSpecification)\n                    RetriveDefinitino(def.GetElementType());\n                else\n                    definition = def as TypeDefinition;\n            }\n        }\n\n        public bool IsGenericInstance\n        {\n            get\n            {\n                return genericArguments != null;\n            }\n        }\n        public KeyValuePair<string, IType>[] GenericArguments\n        {\n            get\n            {\n                return genericArguments;\n            }\n        }\n\n        public IType ElementType { get { return elementType; } }\n\n        public bool IsArray\n        {\n            get; private set;\n        }\n\n        private bool? isValueType;\n\n        public bool IsValueType\n        {\n            get\n            {\n                if (isValueType == null)\n                    isValueType = definition.IsValueType;\n\n                return isValueType.Value;\n            }\n        }\n\n        public bool IsDelegate\n        {\n            get\n            {\n                if (!baseTypeInitialized)\n                    InitializeBaseType();\n                return isDelegate;\n            }\n        }\n\n        public bool IsPrimitive\n        {\n            get { return false; }\n        }\n\n        public Type TypeForCLR\n        {\n            get\n            {\n                if (!baseTypeInitialized)\n                    InitializeBaseType();\n                if (typeRef is ArrayType)\n                {\n                    return arrayCLRType;\n                }\n                else if (typeRef is ByReferenceType)\n                {\n                    return byRefCLRType;\n                }\n                else if (definition.IsEnum)\n                {\n                    if (enumType == null)\n                        InitializeFields();\n                    return enumType.TypeForCLR;\n                }\n                else if (FirstCLRBaseType != null && FirstCLRBaseType is CrossBindingAdaptor)\n                {\n                    return ((CrossBindingAdaptor)FirstCLRBaseType).RuntimeType.TypeForCLR;\n                }\n                else if (FirstCLRInterface != null && FirstCLRInterface is CrossBindingAdaptor)\n                {\n                    return ((CrossBindingAdaptor)FirstCLRInterface).RuntimeType.TypeForCLR;\n                }\n                else\n                    return typeof(ILTypeInstance);\n            }\n        }\n\n        public Type ReflectionType\n        {\n            get\n            {\n                if (reflectionType == null)\n                    reflectionType = new ILRuntimeType(this);\n                return reflectionType;\n            }\n        }\n\n        public IType ByRefType\n        {\n            get\n            {\n                return byRefType;\n            }\n        }\n        public IType ArrayType\n        {\n            get\n            {\n                return arrayType;\n            }\n        }\n\n        public bool IsEnum\n        {\n            get\n            {\n                return definition.IsEnum;\n            }\n        }\n        public string FullName\n        {\n            get\n            {\n                return typeRef.FullName;\n            }\n        }\n        public string Name\n        {\n            get\n            {\n                return typeRef.Name;\n            }\n        }\n        public List<IMethod> GetMethods()\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<IMethod> res = new List<IMethod>();\n            foreach (var i in methods)\n            {\n                foreach (var j in i.Value)\n                    res.Add(j);\n            }\n\n            return res;\n        }\n        void InitializeInterfaces()\n        {\n            interfaceInitialized = true;\n            if (definition.HasInterfaces)\n            {\n                interfaces = new IType[definition.Interfaces.Count];\n                for (int i = 0; i < interfaces.Length; i++)\n                {\n                    interfaces[i] = appdomain.GetType(definition.Interfaces[i], this, null);\n                    //only one clrInterface is valid\n                    if (interfaces[i] is CLRType && firstCLRInterface == null)\n                    {\n                        CrossBindingAdaptor adaptor;\n                        if (appdomain.CrossBindingAdaptors.TryGetValue(interfaces[i].TypeForCLR, out adaptor))\n                        {\n                            interfaces[i] = adaptor;\n                            firstCLRInterface = adaptor;\n                        }\n                        else\n                            throw new TypeLoadException(\"Cannot find Adaptor for:\" + interfaces[i].TypeForCLR.ToString());\n                    }\n                }\n            }\n        }\n        void InitializeBaseType()\n        {\n            if (definition.BaseType != null)\n            {\n                bool specialProcess = false;\n                List<int> spIdx = null;\n                if (definition.BaseType.IsGenericInstance)\n                {\n                    GenericInstanceType git = definition.BaseType as GenericInstanceType;\n                    var elementType = appdomain.GetType(definition.BaseType.GetElementType(), this, null);\n                    if (elementType is CLRType)\n                    {\n                        for (int i = 0; i < git.GenericArguments.Count; i++)\n                        {\n                            var ga = git.GenericArguments[i];\n                            if (ga == typeRef)\n                            {\n                                specialProcess = true;\n                                if (spIdx == null)\n                                    spIdx = new List<int>();\n                                spIdx.Add(i);\n                            }\n                        }\n                    }\n                }\n                if (specialProcess)\n                {\n                    //如果泛型参数是自身，则必须要特殊处理，否则会StackOverflow\n                    var elementType = appdomain.GetType(definition.BaseType.GetElementType(), this, null);\n                    foreach (var i in appdomain.CrossBindingAdaptors)\n                    {\n                        if (i.Key.IsGenericType && !i.Key.IsGenericTypeDefinition)\n                        {\n                            var gd = i.Key.GetGenericTypeDefinition();\n                            if (gd == elementType.TypeForCLR)\n                            {\n                                var ga = i.Key.GetGenericArguments();\n                                bool match = true;\n                                foreach (var j in spIdx)\n                                {\n                                    if (ga[j] != i.Value.AdaptorType)\n                                    {\n                                        match = false;\n                                        break;\n                                    }\n                                }\n                                if (match)\n                                {\n                                    baseType = i.Value;\n                                    break;\n                                }\n                            }\n                        }\n                    }\n                    if (baseType == null)\n                    {\n                        throw new TypeLoadException(\"Cannot find Adaptor for:\" + definition.BaseType.FullName);\n                    }\n                }\n                else\n                {\n                    baseType = appdomain.GetType(definition.BaseType, this, null);\n                    if (baseType is CLRType)\n                    {\n                        if (baseType.TypeForCLR == typeof(Enum) || baseType.TypeForCLR == typeof(object) || baseType.TypeForCLR == typeof(ValueType) || baseType.TypeForCLR == typeof(System.Enum))\n                        {//都是这样，无所谓\n                            baseType = null;\n                        }\n                        else if (baseType.TypeForCLR == typeof(MulticastDelegate))\n                        {\n                            baseType = null;\n                            isDelegate = true;\n                        }\n                        else\n                        {\n                            CrossBindingAdaptor adaptor;\n                            if (appdomain.CrossBindingAdaptors.TryGetValue(baseType.TypeForCLR, out adaptor))\n                            {\n                                baseType = adaptor;\n                            }\n                            else\n                                throw new TypeLoadException(\"Cannot find Adaptor for:\" + baseType.TypeForCLR.ToString());\n                            //继承了其他系统类型\n                            //env.logger.Log_Error(\"ScriptType:\" + Name + \" Based On a SystemType:\" + BaseType.Name);\n                            //HasSysBase = true;\n                            //throw new Exception(\"不得继承系统类型，脚本类型系统和脚本类型系统是隔离的\");\n                        }\n                    }\n                }\n            }\n            var curBase = baseType;\n            while (curBase is ILType)\n            {\n                curBase = curBase.BaseType;\n            }\n            firstCLRBaseType = curBase;\n            baseTypeInitialized = true;\n        }\n\n        public IMethod GetMethod(string name)\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<ILMethod> lst;\n            if (methods.TryGetValue(name, out lst))\n            {\n                return lst[0];\n            }\n            return null;\n        }\n\n        public IMethod GetMethod(string name, int paramCount, bool declaredOnly = false)\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<ILMethod> lst;\n            if (methods.TryGetValue(name, out lst))\n            {\n                foreach (var i in lst)\n                {\n                    if (i.ParameterCount == paramCount)\n                        return i;\n                }\n            }\n            if (declaredOnly)\n                return null;\n            else\n            {\n                //skip clr base type, this doesn't make any sense\n                if (BaseType != null && !(BaseType is CrossBindingAdaptor))\n                    return BaseType.GetMethod(name, paramCount, false);\n                else\n                    return null;\n            }\n        }\n\n        void InitializeMethods()\n        {\n            methods = new Dictionary<string, List<ILMethod>>();\n            constructors = new List<ILMethod>();\n            foreach (var i in definition.Methods)\n            {\n                if (i.IsConstructor)\n                {\n                    if (i.IsStatic)\n                        staticConstructor = new ILMethod(i, this, appdomain);\n                    else\n                        constructors.Add(new ILMethod(i, this, appdomain));\n                }\n                else\n                {\n                    List<ILMethod> lst;\n                    if (!methods.TryGetValue(i.Name, out lst))\n                    {\n                        lst = new List<ILMethod>();\n                        methods[i.Name] = lst;\n                    }\n                    var m = new ILMethod(i, this, appdomain);\n                    lst.Add(new ILMethod(i, this, appdomain));\n                }\n            }\n\n            if (staticConstructor != null && (!TypeReference.HasGenericParameters || IsGenericInstance))\n            {\n                appdomain.Invoke(staticConstructor, null, null);\n            }\n        }\n\n        public IMethod GetVirtualMethod(IMethod method)\n        {\n            IType[] genericArguments = null;\n            if (method.IsGenericInstance)\n            {\n                if (method is ILMethod)\n                {\n                    genericArguments = ((ILMethod)method).GenericArugmentsArray;\n                }\n                else\n                {\n                    genericArguments = ((CLRMethod)method).GenericArguments;\n                }\n            }\n\n            var m = GetMethod(method.Name, method.Parameters, genericArguments, method.ReturnType, true);\n            if (m == null)\n            {\n                if (BaseType != null)\n                {\n                    return BaseType.GetVirtualMethod(method);\n                }\n                else\n                    return null;//BaseType == null means base type is Object or Enum\n            }\n            else if (m.IsGenericInstance == method.IsGenericInstance)\n                return m;\n            else\n                return method;\n        }\n\n        public IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false)\n        {\n            if (methods == null)\n                InitializeMethods();\n            List<ILMethod> lst;\n            IMethod genericMethod = null;\n            if (methods.TryGetValue(name, out lst))\n            {\n                for (var idx = 0; idx < lst.Count; idx++)\n                {\n                    var i = lst[idx];\n                    int pCnt = param != null ? param.Count : 0;\n                    if (i.ParameterCount == pCnt)\n                    {\n                        bool match = true;\n                        if (genericArguments != null && i.GenericParameterCount == genericArguments.Length)\n                        {\n                            genericMethod = CheckGenericParams(i, param, ref match);\n                        }\n                        else\n                        {\n                            match = CheckGenericArguments(i, genericArguments);\n                            if (!match)\n                                continue;\n                            for (int j = 0; j < pCnt; j++)\n                            {\n                                if (param[j] != i.Parameters[j])\n                                {\n                                    match = false;\n                                    break;\n                                }\n                            }\n                            if (match)\n                            {\n                                match = returnType == null || i.ReturnType == returnType;\n                            }\n                            if (match)\n                                return i;\n                        }\n                    }\n                }\n            }\n            if (genericArguments != null && genericMethod != null)\n            {\n                var m = genericMethod.MakeGenericMethod(genericArguments);\n                lst.Add((ILMethod)m);\n                return m;\n            }\n            if (declaredOnly)\n                return null;\n            else\n            {\n                if (BaseType != null)\n                    return BaseType.GetMethod(name, param, genericArguments, returnType, false);\n                else\n                    return null;\n            }\n        }\n\n        bool CheckGenericArguments(ILMethod i, IType[] genericArguments)\n        {\n            if (genericArguments == null)\n            {\n                return i.GenericArguments == null;\n            }\n            else\n            {\n                if (i.GenericArguments == null)\n                    return false;\n                else if (i.GenericArguments.Length != genericArguments.Length)\n                    return false;\n                if (i.GenericArguments.Length == genericArguments.Length)\n                {\n                    for (int j = 0; j < genericArguments.Length; j++)\n                    {\n                        if (i.GenericArguments[j].Value != genericArguments[j])\n                            return false;\n                    }\n                    return true;\n                }\n                else\n                    return false;\n            }\n        }\n\n        ILMethod CheckGenericParams(ILMethod i, List<IType> param, ref bool match)\n        {\n            ILMethod genericMethod = null;\n            if (param != null)\n            {\n                for (int j = 0; j < param.Count; j++)\n                {\n                    var p = i.Parameters[j];\n                    if (p.HasGenericParameter)\n                    {\n                        //TODO should match the generic parameters;\n                        continue;\n                    }\n\n                    if (param[j] != p)\n                    {\n                        match = false;\n                        break;\n                    }\n                }\n            }\n            if (match)\n            {\n                genericMethod = i;\n            }\n            return genericMethod;\n        }\n\n        public List<ILMethod> GetConstructors()\n        {\n            if (constructors == null)\n                InitializeMethods();\n            return constructors;\n        }\n\n        public IMethod GetStaticConstroctor()\n        {\n            if (constructors == null)\n                InitializeMethods();\n            return staticConstructor;\n        }\n\n        public IMethod GetConstructor(int paramCnt)\n        {\n            if (constructors == null)\n                InitializeMethods();\n            foreach (var i in constructors)\n            {\n                if (i.ParameterCount == paramCnt)\n                {\n                    return i;\n                }\n            }\n            return null;\n        }\n\n        public IMethod GetConstructor(List<IType> param)\n        {\n            if (constructors == null)\n                InitializeMethods();\n            foreach (var i in constructors)\n            {\n                if (i.ParameterCount == param.Count)\n                {\n                    bool match = true;\n\n                    for (int j = 0; j < param.Count; j++)\n                    {\n                        if (param[j] != i.Parameters[j])\n                        {\n                            match = false;\n                            break;\n                        }\n                    }\n\n                    if (match)\n                        return i;\n                }\n            }\n            return null;\n        }\n\n        public int GetFieldIndex(object token)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n            int idx;\n            int hashCode = token.GetHashCode();\n            if (fieldTokenMapping.TryGetValue(hashCode, out idx))\n                return idx;\n            FieldReference f = token as FieldReference;\n            if (staticFieldMapping != null && staticFieldMapping.TryGetValue(f.Name, out idx))\n            {\n                fieldTokenMapping[hashCode] = idx;\n                return idx;\n            }\n            if (fieldMapping.TryGetValue(f.Name, out idx))\n            {\n                fieldTokenMapping[hashCode] = idx;\n                return idx;\n            }\n\n            return -1;\n        }\n\n        public IType GetField(string name, out int fieldIdx)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n            if (fieldMapping.TryGetValue(name, out fieldIdx))\n            {\n                return fieldTypes[fieldIdx - FieldStartIndex];\n            }\n            else if (BaseType != null && BaseType is ILType)\n            {\n                return ((ILType)BaseType).GetField(name, out fieldIdx);\n            }\n            else\n                return null;\n        }\n\n        public IType GetField(int fieldIdx, out FieldDefinition fd)\n        {\n            if (fieldMapping == null)\n                InitializeFields();\n            if (fieldIdx < FieldStartIndex)\n                return ((ILType)BaseType).GetField(fieldIdx, out fd);\n            else\n            {\n                fd = fieldDefinitions[fieldIdx - FieldStartIndex];\n                return fieldTypes[fieldIdx - FieldStartIndex];\n            }\n        }\n\n        void InitializeFields()\n        {\n            fieldMapping = new Dictionary<string, int>();\n            fieldTypes = new IType[definition.Fields.Count];\n            fieldDefinitions = new FieldDefinition[definition.Fields.Count];\n            var fields = definition.Fields;\n            int idx = FieldStartIndex;\n            int idxStatic = 0;\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var field = fields[i];\n                if (field.IsStatic)\n                {\n                    //It makes no sence to initialize\n                    if (!TypeReference.HasGenericParameters || IsGenericInstance)\n                    {\n                        if (staticFieldTypes == null)\n                        {\n                            staticFieldTypes = new IType[definition.Fields.Count];\n                            staticFieldDefinitions = new FieldDefinition[definition.Fields.Count];\n                            staticFieldMapping = new Dictionary<string, int>();\n                        }\n                        staticFieldMapping[field.Name] = idxStatic;\n                        staticFieldDefinitions[idxStatic] = field;\n                        if (field.FieldType.IsGenericParameter)\n                        {\n                            staticFieldTypes[idxStatic] = FindGenericArgument(field.FieldType.Name);\n                        }\n                        else\n                            staticFieldTypes[idxStatic] = appdomain.GetType(field.FieldType, this, null);\n                        idxStatic++;\n                    }\n                }\n                else\n                {\n                    fieldMapping[field.Name] = idx;\n                    fieldDefinitions[idx - FieldStartIndex] = field;\n                    if (field.FieldType.IsGenericParameter)\n                    {\n                        fieldTypes[idx - FieldStartIndex] = FindGenericArgument(field.FieldType.Name);\n                    }\n                    else\n                        fieldTypes[idx - FieldStartIndex] = appdomain.GetType(field.FieldType, this, null);\n                    if (IsEnum)\n                    {\n                        enumType = fieldTypes[idx - FieldStartIndex];\n                    }\n                    idx++;\n                }\n            }\n            Array.Resize(ref fieldTypes, idx - FieldStartIndex);\n            Array.Resize(ref fieldDefinitions, idx - FieldStartIndex);\n\n            if (staticFieldTypes != null)\n            {\n                Array.Resize(ref staticFieldTypes, idxStatic);\n                Array.Resize(ref staticFieldDefinitions, idxStatic);\n                staticInstance = new ILTypeStaticInstance(this);\n            }\n        }\n\n        public IType FindGenericArgument(string key)\n        {\n            if (genericArguments != null)\n            {\n                foreach (var i in genericArguments)\n                {\n                    if (i.Key == key)\n                        return i.Value;\n                }\n            }\n            return null;\n        }\n\n        public bool CanAssignTo(IType type)\n        {\n            bool res = false;\n            if (this == type)\n            {\n                return true;\n            }\n\n            if (BaseType != null)\n            {\n                res = BaseType.CanAssignTo(type);\n\n                if (res) return true;\n            }\n\n            if (Implements != null)\n            {\n                for (int i = 0; i < interfaces.Length; i++)\n                {\n                    var im = interfaces[i];\n                    res = im.CanAssignTo(type);\n                    if (res)\n                        return true;\n                }\n            }\n            return res;\n        }\n\n        public ILTypeInstance Instantiate(bool callDefaultConstructor = true)\n        {\n            var res = new ILTypeInstance(this);\n            if (callDefaultConstructor)\n            {\n                var m = GetConstructor(CLR.Utils.Extensions.EmptyParamList);\n                if (m != null)\n                {\n                    appdomain.Invoke(m, res, null);\n                }\n            }\n            return res;\n        }\n        public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)\n        {\n            if (genericInstances == null)\n                genericInstances = new List<ILType>();\n            foreach (var i in genericInstances)\n            {\n                bool match = true;\n                for (int j = 0; j < genericArguments.Length; j++)\n                {\n                    if (i.genericArguments[j].Value != genericArguments[j].Value)\n                    {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match)\n                    return i;\n            }\n            var res = new ILType(definition, appdomain);\n            res.genericArguments = genericArguments;\n\n            genericInstances.Add(res);\n            return res;\n        }\n\n        public IType MakeByRefType()\n        {\n            if (byRefType == null)\n            {\n                var def = new ByReferenceType(typeRef);\n                byRefType = new ILType(def, appdomain);\n                ((ILType)byRefType).elementType = this;\n                ((ILType)byRefType).byRefCLRType = this.TypeForCLR.MakeByRefType();\n            }\n            return byRefType;\n        }\n\n        public IType MakeArrayType()\n        {\n            if (arrayType == null)\n            {\n                var def = new ArrayType(typeRef);\n                arrayType = new ILType(def, appdomain);\n                ((ILType)arrayType).IsArray = true;\n                ((ILType)arrayType).elementType = this;\n                ((ILType)arrayType).arrayCLRType = this.TypeForCLR.MakeArrayType();\n            }\n            return arrayType;\n        }\n\n        public IType ResolveGenericType(IType contextType)\n        {\n            var ga = contextType.GenericArguments;\n            IType[] kv = new IType[definition.GenericParameters.Count];\n            for (int i = 0; i < kv.Length; i++)\n            {\n                var gp = definition.GenericParameters[i];\n                string name = gp.Name;\n                foreach (var j in ga)\n                {\n                    if (j.Key == name)\n                    {\n                        kv[i] = j.Value;\n                        break;\n                    }\n                }\n            }\n\n            foreach (var i in genericInstances)\n            {\n                bool match = true;\n                for (int j = 0; j < kv.Length; j++)\n                {\n                    if (i.genericArguments[j].Value != kv[j])\n                    {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match)\n                    return i;\n            }\n\n            return null;\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n\n        public override string ToString()\n        {\n            return FullName;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/CLR/TypeSystem/IType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.Method;\n\nnamespace ILRuntime.CLR.TypeSystem\n{\n    public interface IType\n    {\n        bool IsGenericInstance { get; }\n        KeyValuePair<string, IType>[] GenericArguments { get; }\n        Type TypeForCLR { get; }\n        Type ReflectionType { get; }\n\n        IType BaseType { get; }\n\n        IType[] Implements { get; }\n\n        IType ByRefType { get; }\n\n        IType ArrayType { get; }\n\n        string FullName { get; }\n\n        string Name { get; }\n\n        bool IsArray { get; }\n\n        bool IsValueType { get; }\n\n        bool IsDelegate { get; }\n\n        bool IsPrimitive { get; }\n\n        bool HasGenericParameter { get; }\n\n        ILRuntime.Runtime.Enviorment.AppDomain AppDomain { get; }\n\n        /// <summary>\n        /// Get a specified Method in this type\n        /// </summary>\n        /// <param name=\"name\">Name of the Type</param>\n        /// <param name=\"paramCount\">Parameter count</param>\n        /// <param name=\"declaredOnly\">True to search the methods decleared in this type only, false to search base types.</param>\n        /// <returns></returns>\n        IMethod GetMethod(string name, int paramCount, bool declaredOnly = false);\n        /// <summary>\n        ///  Get a specified Method in this type\n        /// </summary>\n        /// <param name=\"name\">Name of the Type</param>\n        /// <param name=\"param\">List of parameter's types</param>\n        /// <param name=\"genericArguments\">List of Generic Arguments</param>\n        /// <param name=\"returnType\">Return Type</param>\n        /// <param name=\"declaredOnly\">True to search the methods decleared in this type only, false to search base types.</param>\n        /// <returns></returns>\n        IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false);\n        IMethod GetVirtualMethod(IMethod method);\n\n        List<IMethod> GetMethods();\n\n        int GetFieldIndex(object token);\n\n        IMethod GetConstructor(List<IType> param);\n\n        bool CanAssignTo(IType type);\n\n        IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments);\n\n        IType MakeByRefType();\n\n        IType MakeArrayType();\n        IType FindGenericArgument(string key);\n\n        IType ResolveGenericType(IType contextType);\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/CLR/Utils/Extensions.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Other;\nusing Mono.Cecil;\nusing ILRuntime.Runtime.Intepreter;\nnamespace ILRuntime.CLR.Utils\n{\n    public delegate TResult Func<T1, T2, T3, T4, T5, TResult>(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5);\n\n    public static class Extensions\n    {\n        public static List<IType> EmptyParamList = new List<IType>();\n        public static List<IType> GetParamList(this MethodReference def, ILRuntime.Runtime.Enviorment.AppDomain appdomain, IType contextType, IMethod contextMethod, IType[] genericArguments)\n        {\n            if (def.HasParameters)\n            {\n                List<IType> param = new List<IType>();\n                var dt = appdomain.GetType(def.DeclaringType, contextType, contextMethod);\n                foreach (var i in def.Parameters)\n                {\n                    IType t = null;\n                    t = appdomain.GetType(i.ParameterType, dt, null);\n                    if (t == null && def.IsGenericInstance)\n                    {\n                        GenericInstanceMethod gim = (GenericInstanceMethod)def;\n                        string name = i.ParameterType.IsByReference ? i.ParameterType.GetElementType().FullName : i.ParameterType.FullName;\n                        \n                        for (int j = 0; j < gim.GenericArguments.Count; j++)\n                        {\n                            var gp = gim.ElementMethod.GenericParameters[j];\n                            var ga = gim.GenericArguments[j];\n                            if (name == gp.Name)\n                            {\n                                t = appdomain.GetType(ga, contextType, contextMethod);\n                                if (t == null && genericArguments != null)\n                                    t = genericArguments[j];\n                                break;\n                            }\n                            else if (name.Contains(gp.Name))\n                            {\n                                if (name == gp.Name)\n                                {\n                                    name = ga.FullName;\n                                }\n                                else if (name == gp.Name + \"[]\")\n                                {\n                                    name = ga.FullName + \"[]\";\n                                }\n                                else\n                                {\n                                    /*name = name.Replace(\"<\" + gp.Name + \">\", \"<\" + ga.FullName + \">\");\n                                    name = name.Replace(\"<\" + gp.Name + \"[\", \"<\" + ga.FullName + \"[\");\n                                    name = name.Replace(\"<\" + gp.Name + \",\", \"<\" + ga.FullName + \",\");\n                                    name = name.Replace(\",\" + gp.Name + \">\", \",\" + ga.FullName + \">\");\n                                    name = name.Replace(\",\" + gp.Name + \"[\", \",\" + ga.FullName + \"[\");\n                                    name = name.Replace(\",\" + gp.Name + \",\", \",\" + ga.FullName + \",\");\n                                    name = name.Replace(\",\" + gp.Name + \"[\", \",\" + ga.FullName + \"[\");*/\n                                    name = ReplaceGenericArgument(name, gp.Name, ga.FullName);\n                                }\n                            }\n                        }\n                        if (t == null)\n                            t = appdomain.GetType(name);\n                    }\n\n                    param.Add(t);\n                }\n                return param;\n            }\n            else\n                return EmptyParamList;\n        }\n\n        static string ReplaceGenericArgument(string typename, string argumentName, string argumentType)\n        {\n            string baseType;\n            StringBuilder sb = new StringBuilder();\n            List<string> ga;\n            bool isArray;\n            Runtime.Enviorment.AppDomain.ParseGenericType(typename, out baseType, out ga, out isArray);\n            if (baseType == argumentName)\n                sb.Append(argumentType);\n            else\n                sb.Append(baseType);\n            if (ga != null && ga.Count > 0)\n            {\n                sb.Append(\"<\");\n                bool isFirst = true;\n                foreach(var i in ga)\n                {\n                    if (isFirst)\n                        isFirst = false;\n                    else\n                        sb.Append(\",\");\n\n                    sb.Append(ReplaceGenericArgument(i, argumentName, argumentType));\n                }\n                sb.Append(\">\");\n            }\n            if (isArray)\n                sb.Append(\"[]\");\n            return sb.ToString();\n        }\n\n        [Flags]\n        public enum TypeFlags\n        {\n            Default = 0,\n            IsPrimitive = 0x1,\n            IsByRef = 0x2,\n            IsEnum = 0x4,\n            IsDelegate = 0x8,\n            IsValueType = 0x10,\n        }\n\n        private static readonly Dictionary<Type, TypeFlags> typeFlags = new Dictionary<Type, TypeFlags>(new ByReferenceKeyComparer<Type>());\n\n        public static bool FastIsEnum(this Type pt)\n        {\n            return (pt.GetTypeFlags() & TypeFlags.IsEnum) != 0;\n        }\n\n        public static bool FastIsByRef(this Type pt)\n        {\n            return (pt.GetTypeFlags() & TypeFlags.IsByRef) != 0;\n        }\n\n        public static bool FastIsPrimitive(this Type pt)\n        {\n            return (pt.GetTypeFlags() & TypeFlags.IsPrimitive) != 0;\n        }\n\n        public static bool FastIsValueType(this Type pt)\n        {\n            return (pt.GetTypeFlags() & TypeFlags.IsValueType) != 0;\n        }\n\n        public static TypeFlags GetTypeFlags(this Type pt)\n        {\n            var result = TypeFlags.Default;\n\n            if (!typeFlags.TryGetValue(pt, out result))\n            {\n                if (pt.IsPrimitive)\n                {\n                    result |= TypeFlags.IsPrimitive;\n                }\n\n                if (pt == typeof(Delegate) || pt.IsSubclassOf(typeof(Delegate)))\n                {\n                    result |= TypeFlags.IsDelegate;\n                }\n\n                if (pt.IsByRef)\n                {\n                    result |= TypeFlags.IsByRef;\n                }\n\n                if (pt.IsEnum)\n                {\n                    result |= TypeFlags.IsEnum;\n                }\n\n                if (pt.IsValueType)\n                {\n                    result |= TypeFlags.IsValueType;\n                }\n\n                typeFlags[pt] = result;\n            }\n\n            return result;\n        }\n\n        public static object CheckCLRTypes(this Type pt, object obj)\n        {\n            if (obj == null)\n                return null;\n\n            var typeFlags = GetTypeFlags(pt);\n\n            if ((typeFlags & TypeFlags.IsPrimitive) != 0 && pt != typeof(int))\n            {\n                if (pt == typeof(bool) && !(obj is bool))\n                {\n                    obj = (int)obj == 1;\n                }\n                else if (pt == typeof(byte) && !(obj is byte))\n                    obj = (byte)(int)obj;\n                else if (pt == typeof(short) && !(obj is short))\n                    obj = (short)(int)obj;\n                else if (pt == typeof(char) && !(obj is char))\n                    obj = (char)(int)obj;\n                else if (pt == typeof(ushort) && !(obj is ushort))\n                    obj = (ushort)(int)obj;\n                else if (pt == typeof(uint) && !(obj is uint))\n                    obj = (uint)(int)obj;\n                else if (pt == typeof(sbyte) && !(obj is sbyte))\n                    obj = (sbyte)(int)obj;\n                else if (pt == typeof(ulong) && !(obj is ulong))\n                {\n                    obj = (ulong)(long)obj;\n                }\n            }\n            else if (obj is ILRuntime.Reflection.ILRuntimeWrapperType)\n            {\n                obj = ((ILRuntime.Reflection.ILRuntimeWrapperType)obj).RealType;\n            }\n            else if ((typeFlags & TypeFlags.IsDelegate) != 0)\n            {\n                if (obj is Delegate)\n                    return obj;\n                if (pt == typeof(Delegate))\n                    return ((IDelegateAdapter)obj).Delegate;\n                return ((IDelegateAdapter)obj).GetConvertor(pt);\n            }\n            else if ((typeFlags & TypeFlags.IsByRef) != 0)\n            {\n                return CheckCLRTypes(pt.GetElementType(), obj);\n            }\n            else if ((typeFlags & TypeFlags.IsEnum) != 0)\n            {\n                return Enum.ToObject(pt, obj);\n            }\n            else if (obj is ILTypeInstance)\n            {\n                var adapter = obj as IDelegateAdapter;\n\n                if (adapter != null && pt != typeof(ILTypeInstance))\n                {\n                    return adapter.Delegate;\n                }\n\n                if (!(obj is ILEnumTypeInstance))\n                {\n                    var ins = (ILTypeInstance)obj;\n                    if (ins.IsValueType)\n                        ins = ins.Clone();\n                    return ins.CLRInstance;\n                }\n            }\n            return obj;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Other/ByReferenceKeyComparer.cs",
    "content": "﻿using System.Collections.Generic;\nusing System.Runtime.CompilerServices;\n\nnamespace ILRuntime.Other\n{\n    class ByReferenceKeyComparer<T> : IEqualityComparer<T>\n    {\n        public bool Equals(T x, T y)\n        {\n            return object.ReferenceEquals(x, y);\n        }\n\n        public int GetHashCode(T obj)\n        {\n            return RuntimeHelpers.GetHashCode(obj);\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Other/DelegateExportAttribute.cs",
    "content": "﻿namespace ILRuntime.Other\n{\n    /// <summary>\n    /// A Delegate Custom Attr, It tells the CodeGenerationTools : this delegate need to register a delegate convertor,when generate ILRuntimeHelper.cs file.\n    /// </summary>\n    public class DelegateExportAttribute : System.Attribute\n    {\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Other/NeedAdaptorAttribute.cs",
    "content": "﻿namespace ILRuntime.Other\n{\n    /// <summary>\n    /// A Class Custom Attr, It tells the CodeGenerationTools :there is a class need to generate an adaptor for ILScript\n    /// </summary>\n    public class NeedAdaptorAttribute : System.Attribute\n    {\n\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Other/ThreadSafeDictionary.cs",
    "content": "﻿using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.Runtime.Versioning;\nusing System.Threading;\n\nnamespace ILRuntime.Other\n{\n    /// <summary>\n    /// A thread safe dictionary for internal use\n    /// </summary>\n    /// <typeparam name=\"K\"></typeparam>\n    /// <typeparam name=\"V\"></typeparam>\n    class ThreadSafeDictionary<K, V> : IDictionary<K, V>\n    {\n        Dictionary<K, V> dic = new Dictionary<K, V>();\n\n        public Dictionary<K,V> InnerDictionary { get { return dic; } }\n        public V this[K key]\n        {\n            get\n            {\n                lock(dic)\n                    return dic[key];\n            }\n\n            set\n            {\n               lock(dic)\n                    dic[key] = value;\n            }\n        }\n\n        public int Count\n        {\n            get\n            {\n                lock(dic)\n                    return dic.Count;\n            }\n        }\n\n        public bool IsReadOnly\n        {\n            get\n            {\n                lock(dic)\n                    return IsReadOnly;\n            }\n        }\n\n        public ICollection<K> Keys\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public ICollection<V> Values\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public void Add(KeyValuePair<K, V> item)\n        {\n            lock (dic)\n                 dic.Add(item.Key, item.Value);\n        }\n\n        public void Add(K key, V value)\n        {\n            lock(dic)\n                dic.Add(key, value);\n        }\n\n        public void Clear()\n        {\n            lock(dic)\n                dic.Clear();\n        }\n\n        public bool Contains(KeyValuePair<K, V> item)\n        {\n           lock(dic)\n                return dic.ContainsKey(item.Key);\n        }\n\n        public bool ContainsKey(K key)\n        {\n            lock(dic)\n                return dic.ContainsKey(key);\n        }\n\n        public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex)\n        {\n            throw new NotImplementedException();\n        }\n\n        public IEnumerator<KeyValuePair<K, V>> GetEnumerator()\n        {\n            throw new NotImplementedException();\n        }\n\n        public bool Remove(KeyValuePair<K, V> item)\n        {\n            throw new NotImplementedException();\n        }\n\n        public bool Remove(K key)\n        {\n            lock(dic)\n                return dic.Remove(key);\n        }\n\n        public bool TryGetValue(K key, out V value)\n        {\n             lock(dic)\n                return dic.TryGetValue(key, out value);\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            throw new NotImplementedException();\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/ILRuntime/Other/UncheckedList.cs",
    "content": "﻿using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.Runtime.Versioning;\nusing System.Threading;\n\nnamespace ILRuntime.Other\n{\n    /// <summary>\n    /// This is a copy of the latest .NET framework 4.5 List implementation, with all extraneous checking removed.\n    /// </summary>\n    /// <typeparam name=\"T\"></typeparam>\n    [Serializable]\n    public class UncheckedList<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection\n    {\n\n       private const int _defaultCapacity = 4;\n\n        private T[] _items;\n        private int _size;\n        private int _version;\n        [NonSerialized]\n        private Object _syncRoot;\n\n        private static readonly T[] _emptyArray = new T[0];\n\n        // Constructs a UncheckedList. The list is initially empty and has a capacity\n        // of zero. Upon adding the first element to the list the capacity is\n        // increased to _defaultCapacity, and then increased in multiples of two\n        // as required.\n        public UncheckedList()\n        {\n            _items = _emptyArray;\n        }\n\n        // Constructs a UncheckedList with a given initial capacity. The list is\n        // initially empty, but will have room for the given number of elements\n        // before any reallocations are required.\n        // \n        public UncheckedList(int capacity)\n        {\n            if (capacity == 0)\n                _items = _emptyArray;\n            else\n                _items = new T[capacity];\n        }\n\n        // Constructs a UncheckedList, copying the contents of the given collection. The\n        // size and capacity of the new list will both be equal to the size of the\n        // given collection.\n        // \n        public UncheckedList(IEnumerable<T> collection)\n        {\n            ICollection<T> c = collection as ICollection<T>;\n            if (c != null)\n            {\n                int count = c.Count;\n                if (count == 0)\n                {\n                    _items = _emptyArray;\n                }\n                else\n                {\n                    _items = new T[count];\n                    c.CopyTo(_items, 0);\n                    _size = count;\n                }\n            }\n            else\n            {\n                _size = 0;\n                _items = _emptyArray;\n                AddEnumerable(collection);\n            }\n        }\n\n        // Gets and sets the capacity of this list.  The capacity is the size of\n        // the internal array used to hold items.  When set, the internal \n        // array of the list is reallocated to the given capacity.\n        // \n        public int Capacity\n        {\n            get\n            {\n                return _items.Length;\n            }\n            set\n            {\n                if (value != _items.Length)\n                {\n                    if (value > 0)\n                    {\n                        T[] newItems = new T[value];\n                        if (_size > 0)\n                        {\n                            Array.Copy(_items, 0, newItems, 0, _size);\n                        }\n                        _items = newItems;\n                    }\n                    else\n                    {\n                        _items = _emptyArray;\n                    }\n                }\n            }\n        }\n\n        // Read-only property describing how many elements are in the UncheckedList.\n        public int Count\n        {\n            get\n            {\n                return _size;\n            }\n        }\n\n        bool System.Collections.IList.IsFixedSize\n        {\n            get { return false; }\n        }\n\n\n        // Is this UncheckedList read-only?\n        bool ICollection<T>.IsReadOnly\n        {\n            get { return false; }\n        }\n\n        bool System.Collections.IList.IsReadOnly\n        {\n            get { return false; }\n        }\n\n        // Is this UncheckedList synchronized (thread-safe)?\n        bool System.Collections.ICollection.IsSynchronized\n        {\n            get { return false; }\n        }\n\n        // Synchronization root for this object.\n        Object System.Collections.ICollection.SyncRoot\n        {\n            get\n            {\n                if (_syncRoot == null)\n                {\n                    System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);\n                }\n                return _syncRoot;\n            }\n        }\n        // Sets or Gets the element at the given index.\n        // \n        public T this[int index]\n        {\n            get\n            {\n                return _items[index];\n            }\n\n            set\n            {\n                _items[index] = value;\n                _version++;\n            }\n        }\n\n        private static bool IsCompatibleObject(object value)\n        {\n            // Non-null values are fine.  Only accept nulls if T is a class or Nullable<U>.\n            // Note that default(T) is not equal to null for value types except when T is Nullable<U>. \n            return ((value is T) || (value == null && default(T) == null));\n        }\n\n        Object System.Collections.IList.this[int index]\n        {\n            get\n            {\n                return this[index];\n            }\n            set\n            {\n                try\n                {\n                    this[index] = (T)value;\n                }\n                catch (InvalidCastException)\n                {\n                }\n            }\n        }\n\n        // Adds the given object to the end of this list. The size of the list is\n        // increased by one. If required, the capacity of the list is doubled\n        // before adding the new element.\n        public void Add(T item)\n        {\n            var array = _items;\n            var size = _size;\n            _version++;\n            if ((uint)size < (uint)array.Length)\n            {\n                _size = size + 1;\n                array[size] = item;\n            }\n            else\n            {\n                AddWithResize(item);\n            }\n        }\n\n        // Non-inline from UncheckedList.Add to improve its code quality as uncommon path\n        private void AddWithResize(T item)\n        {\n            var size = _size;\n            EnsureCapacity(size + 1);\n            _size = size + 1;\n            _items[size] = item;\n        }\n\n        int System.Collections.IList.Add(Object item)\n        {\n            try\n            {\n                Add((T)item);\n            }\n            catch (InvalidCastException)\n            {\n            }\n\n            return Count - 1;\n        }\n\n\n        // Adds the elements of the given collection to the end of this list. If\n        // required, the capacity of the list is increased to twice the previous\n        // capacity or the new size, whichever is larger.\n        //\n        public void AddRange(IEnumerable<T> collection)\n        {\n            InsertRange(_size, collection);\n        }\n\n        public ReadOnlyCollection<T> AsReadOnly()\n        {\n            return new ReadOnlyCollection<T>(this);\n        }\n\n        // Searches a section of the list for a given element using a binary search\n        // algorithm. Elements of the list are compared to the search value using\n        // the given IComparer interface. If comparer is null, elements of\n        // the list are compared to the search value using the IComparable\n        // interface, which in that case must be implemented by all elements of the\n        // list and the given search value. This method assumes that the given\n        // section of the list is already sorted; if this is not the case, the\n        // result will be incorrect.\n        //\n        // The method returns the index of the given value in the list. If the\n        // list does not contain the given value, the method returns a negative\n        // integer. The bitwise complement operator (~) can be applied to a\n        // negative result to produce the index of the first element (if any) that\n        // is larger than the given search value. This is also the index at which\n        // the search value should be inserted into the list in order for the list\n        // to remain sorted.\n        // \n        // The method uses the Array.BinarySearch method to perform the\n        // search.\n        // \n        public int BinarySearch(int index, int count, T item, IComparer<T> comparer)\n        {\n            if (index < 0) return -1;\n            return Array.BinarySearch<T>(_items, index, count, item, comparer);\n        }\n\n        public int BinarySearch(T item)\n        {\n            return BinarySearch(0, Count, item, null);\n        }\n\n        public int BinarySearch(T item, IComparer<T> comparer)\n        {\n            return BinarySearch(0, Count, item, comparer);\n        }\n\n\n        // Clears the contents of UncheckedList.\n        public void Clear()\n        {\n            if (!typeof(T).IsValueType)\n            {\n                int size = _size;\n                _size = 0;\n                _version++;\n                if (size > 0)\n                {\n                    Array.Clear(_items, 0, size); // Clear the elements so that the gc can reclaim the references.\n                }\n            }\n            else\n            {\n                _size = 0;\n                _version++;\n            }\n        }\n\n        // Contains returns true if the specified element is in the UncheckedList.\n        // It does a linear, O(n) search.  Equality is determined by calling\n        // EqualityComparer<T>.Default.Equals().\n\n        public bool Contains(T item)\n        {\n            // PERF: IndexOf calls Array.IndexOf, which internally\n            // calls EqualityComparer<T>.Default.IndexOf, which\n            // is specialized for different types. This\n            // boosts performance since instead of making a\n            // virtual method call each iteration of the loop,\n            // via EqualityComparer<T>.Default.Equals, we\n            // only make one virtual call to EqualityComparer.IndexOf.\n\n            return _size != 0 && IndexOf(item) != -1;\n        }\n\n        bool System.Collections.IList.Contains(Object item)\n        {\n            if (IsCompatibleObject(item))\n            {\n                return Contains((T)item);\n            }\n            return false;\n        }\n\n        public UncheckedList<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter)\n        {\n            UncheckedList<TOutput> list = new UncheckedList<TOutput>(_size);\n            for (int i = 0; i < _size; i++)\n            {\n                list._items[i] = converter(_items[i]);\n            }\n            list._size = _size;\n            return list;\n        }\n\n        // Copies this UncheckedList into array, which must be of a \n        // compatible array type.  \n        //\n        public void CopyTo(T[] array)\n        {\n            CopyTo(array, 0);\n        }\n\n        // Copies this UncheckedList into array, which must be of a \n        // compatible array type.  \n        //\n        void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)\n        {\n            try\n            {\n                // Array.Copy will check for NULL.\n                Array.Copy(_items, 0, array, arrayIndex, _size);\n            }\n            catch (ArrayTypeMismatchException)\n            {\n            }\n        }\n\n        // Copies a section of this list to the given array at the given index.\n        // \n        // The method uses the Array.Copy method to copy the elements.\n        // \n        public void CopyTo(int index, T[] array, int arrayIndex, int count)\n        {\n            // Delegate rest of error checking to Array.Copy.\n            Array.Copy(_items, index, array, arrayIndex, count);\n        }\n\n        public void CopyTo(T[] array, int arrayIndex)\n        {\n            // Delegate rest of error checking to Array.Copy.\n            Array.Copy(_items, 0, array, arrayIndex, _size);\n        }\n\n        // Ensures that the capacity of this list is at least the given minimum\n        // value. If the current capacity of the list is less than min, the\n        // capacity is increased to twice the current capacity or to min,\n        // whichever is larger.\n        private void EnsureCapacity(int min)\n        {\n            if (_items.Length < min)\n            {\n                int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2;\n                // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.\n                // Note that this check works even when _items.Length overflowed thanks to the (uint) cast\n                if ((uint) newCapacity > Int32.MaxValue) newCapacity = Int32.MaxValue;\n                if (newCapacity < min) newCapacity = min;\n                Capacity = newCapacity;\n            }\n        }\n\n        public bool Exists(Predicate<T> match)\n        {\n            return FindIndex(match) != -1;\n        }\n\n        public T Find(Predicate<T> match)\n        {\n            for (int i = 0; i < _size; i++)\n            {\n                if (match(_items[i]))\n                {\n                    return _items[i];\n                }\n            }\n            return default(T);\n        }\n\n        public UncheckedList<T> FindAll(Predicate<T> match)\n        {\n            UncheckedList<T> list = new UncheckedList<T>();\n            for (int i = 0; i < _size; i++)\n            {\n                if (match(_items[i]))\n                {\n                    list.Add(_items[i]);\n                }\n            }\n            return list;\n        }\n\n        public int FindIndex(Predicate<T> match)\n        {\n            return FindIndex(0, _size, match);\n        }\n\n        public int FindIndex(int startIndex, Predicate<T> match)\n        {\n            return FindIndex(startIndex, _size - startIndex, match);\n        }\n\n        public int FindIndex(int startIndex, int count, Predicate<T> match)\n        {\n            int endIndex = startIndex + count;\n            for (int i = startIndex; i < endIndex; i++)\n            {\n                if (match(_items[i])) return i;\n            }\n            return -1;\n        }\n\n        public T FindLast(Predicate<T> match)\n        {\n            for (int i = _size - 1; i >= 0; i--)\n            {\n                if (match(_items[i]))\n                {\n                    return _items[i];\n                }\n            }\n            return default(T);\n        }\n\n        public int FindLastIndex(Predicate<T> match)\n        {\n            return FindLastIndex(_size - 1, _size, match);\n        }\n\n        public int FindLastIndex(int startIndex, Predicate<T> match)\n        {\n            return FindLastIndex(startIndex, startIndex + 1, match);\n        }\n\n        public int FindLastIndex(int startIndex, int count, Predicate<T> match)\n        {\n            int endIndex = startIndex - count;\n            for (int i = startIndex; i > endIndex; i--)\n            {\n                if (match(_items[i]))\n                {\n                    return i;\n                }\n            }\n            return -1;\n        }\n\n        public void ForEach(Action<T> action)\n        {\n            int version = _version;\n\n            for (int i = 0; i < _size; i++)\n            {\n                if (version != _version)\n                {\n                    break;\n                }\n                action(_items[i]);\n            }\n        }\n\n        // Returns an enumerator for this list with the given\n        // permission for removal of elements. If modifications made to the list \n        // while an enumeration is in progress, the MoveNext and \n        // GetObject methods of the enumerator will throw an exception.\n        //\n        public Enumerator GetEnumerator()\n        {\n            return new Enumerator(this);\n        }\n\n        IEnumerator<T> IEnumerable<T>.GetEnumerator()\n        {\n            return new Enumerator(this);\n        }\n\n        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n        {\n            return new Enumerator(this);\n        }\n\n        public UncheckedList<T> GetRange(int index, int count)\n        {\n            UncheckedList<T> list = new UncheckedList<T>(count);\n            Array.Copy(_items, index, list._items, 0, count);\n            list._size = count;\n            return list;\n        }\n\n\n        // Returns the index of the first occurrence of a given value in a range of\n        // this list. The list is searched forwards from beginning to end.\n        // The elements of the list are compared to the given value using the\n        // Object.Equals method.\n        // \n        // This method uses the Array.IndexOf method to perform the\n        // search.\n        // \n        public int IndexOf(T item)\n        {\n            return Array.IndexOf(_items, item, 0, _size);\n        }\n\n        int System.Collections.IList.IndexOf(Object item)\n        {\n            if (IsCompatibleObject(item))\n            {\n                return IndexOf((T)item);\n            }\n            return -1;\n        }\n\n        // Returns the index of the first occurrence of a given value in a range of\n        // this list. The list is searched forwards, starting at index\n        // index and ending at count number of elements. The\n        // elements of the list are compared to the given value using the\n        // Object.Equals method.\n        // \n        // This method uses the Array.IndexOf method to perform the\n        // search.\n        // \n        public int IndexOf(T item, int index)\n        {\n            return Array.IndexOf(_items, item, index, _size - index);\n        }\n\n        // Returns the index of the first occurrence of a given value in a range of\n        // this list. The list is searched forwards, starting at index\n        // index and upto count number of elements. The\n        // elements of the list are compared to the given value using the\n        // Object.Equals method.\n        // \n        // This method uses the Array.IndexOf method to perform the\n        // search.\n        // \n        public int IndexOf(T item, int index, int count)\n        {\n            return Array.IndexOf(_items, item, index, count);\n        }\n\n        // Inserts an element into this list at a given index. The size of the list\n        // is increased by one. If required, the capacity of the list is doubled\n        // before inserting the new element.\n        // \n        public void Insert(int index, T item)\n        {\n            if (_size == _items.Length) EnsureCapacity(_size + 1);\n            if (index < _size)\n            {\n                Array.Copy(_items, index, _items, index + 1, _size - index);\n            }\n            _items[index] = item;\n            _size++;\n            _version++;\n        }\n\n        void System.Collections.IList.Insert(int index, Object item)\n        {\n            try\n            {\n                Insert(index, (T)item);\n            }\n            catch (InvalidCastException)\n            {\n            }\n        }\n\n        // Inserts the elements of the given collection at a given index. If\n        // required, the capacity of the list is increased to twice the previous\n        // capacity or the new size, whichever is larger.  Ranges may be added\n        // to the end of the list by setting index to the UncheckedList's size.\n        //\n        public void InsertRange(int index, IEnumerable<T> collection)\n        {\n            ICollection<T> c = collection as ICollection<T>;\n            if (c != null)\n            {    // if collection is ICollection<T>\n                int count = c.Count;\n                if (count > 0)\n                {\n                    EnsureCapacity(_size + count);\n                    if (index < _size)\n                    {\n                        Array.Copy(_items, index, _items, index + count, _size - index);\n                    }\n\n                    // If we're inserting a UncheckedList into itself, we want to be able to deal with that.\n                    if (this == c)\n                    {\n                        // Copy first part of _items to insert location\n                        Array.Copy(_items, 0, _items, index, index);\n                        // Copy last part of _items back to inserted location\n                        Array.Copy(_items, index + count, _items, index * 2, _size - index);\n                    }\n                    else\n                    {\n                        c.CopyTo(_items, index);\n                    }\n                    _size += count;\n                }\n            }\n            else if (index < _size)\n            {\n                // We're inserting a lazy enumerable. Call Insert on each of the constituent items.\n                using (IEnumerator<T> en = collection.GetEnumerator())\n                {\n                    while (en.MoveNext())\n                    {\n                        Insert(index++, en.Current);\n                    }\n                }\n            }\n            else\n            {\n                // We're adding a lazy enumerable because the index is at the end of this list.\n                AddEnumerable(collection);\n            }\n            _version++;\n        }\n\n        // Returns the index of the last occurrence of a given value in a range of\n        // this list. The list is searched backwards, starting at the end \n        // and ending at the first element in the list. The elements of the list \n        // are compared to the given value using the Object.Equals method.\n        // \n        // This method uses the Array.LastIndexOf method to perform the\n        // search.\n        // \n        public int LastIndexOf(T item)\n        {\n            if (_size == 0)\n            {  // Special case for empty list\n                return -1;\n            }\n            else\n            {\n                return LastIndexOf(item, _size - 1, _size);\n            }\n        }\n\n        // Returns the index of the last occurrence of a given value in a range of\n        // this list. The list is searched backwards, starting at index\n        // index and ending at the first element in the list. The \n        // elements of the list are compared to the given value using the \n        // Object.Equals method.\n        // \n        // This method uses the Array.LastIndexOf method to perform the\n        // search.\n        // \n        public int LastIndexOf(T item, int index)\n        {\n            return LastIndexOf(item, index, index + 1);\n        }\n\n        // Returns the index of the last occurrence of a given value in a range of\n        // this list. The list is searched backwards, starting at index\n        // index and upto count elements. The elements of\n        // the list are compared to the given value using the Object.Equals\n        // method.\n        // \n        // This method uses the Array.LastIndexOf method to perform the\n        // search.\n        // \n        public int LastIndexOf(T item, int index, int count)\n        {\n            if (_size == 0)\n            {  // Special case for empty list\n                return -1;\n            }\n\n            return Array.LastIndexOf(_items, item, index, count);\n        }\n\n        // Removes the element at the given index. The size of the list is\n        // decreased by one.\n        // \n        public bool Remove(T item)\n        {\n            int index = IndexOf(item);\n            if (index >= 0)\n            {\n                RemoveAt(index);\n                return true;\n            }\n\n            return false;\n        }\n\n        void System.Collections.IList.Remove(Object item)\n        {\n            if (IsCompatibleObject(item))\n            {\n                Remove((T)item);\n            }\n        }\n\n        // This method removes all items which matches the predicate.\n        // The complexity is O(n).   \n        public int RemoveAll(Predicate<T> match)\n        {\n            int freeIndex = 0;   // the first free slot in items array\n\n            // Find the first item which needs to be removed.\n            while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++;\n            if (freeIndex >= _size) return 0;\n\n            int current = freeIndex + 1;\n            while (current < _size)\n            {\n                // Find the first item which needs to be kept.\n                while (current < _size && match(_items[current])) current++;\n\n                if (current < _size)\n                {\n                    // copy item to the free slot.\n                    _items[freeIndex++] = _items[current++];\n                }\n            }\n\n            if (!typeof(T).IsValueType)\n            {\n                Array.Clear(_items, freeIndex, _size - freeIndex); // Clear the elements so that the gc can reclaim the references.\n            }\n\n            int result = _size - freeIndex;\n            _size = freeIndex;\n            _version++;\n            return result;\n        }\n\n        // Removes the element at the given index. The size of the list is\n        // decreased by one.\n        // \n        public void RemoveAt(int index)\n        {\n            _size--;\n            if (index < _size)\n            {\n                Array.Copy(_items, index + 1, _items, index, _size - index);\n            }\n            if (!typeof(T).IsValueType)\n            {\n                _items[_size] = default(T);\n            }\n            _version++;\n        }\n\n        // Removes a range of elements from this list.\n        // \n        public void RemoveRange(int index, int count)\n        {\n            if (count > 0)\n            {\n                int i = _size;\n                _size -= count;\n                if (index < _size)\n                {\n                    Array.Copy(_items, index + count, _items, index, _size - index);\n                }\n\n                _version++;\n                if (!typeof(T).IsValueType)\n                {\n                    Array.Clear(_items, _size, count);\n                }\n            }\n        }\n\n        // Reverses the elements in this list.\n        public void Reverse()\n        {\n            Reverse(0, Count);\n        }\n\n        // Reverses the elements in a range of this list. Following a call to this\n        // method, an element in the range given by index and count\n        // which was previously located at index i will now be located at\n        // index index + (index + count - i - 1).\n        // \n        public void Reverse(int index, int count)\n        {\n            if (count > 1)\n            {\n                Array.Reverse(_items, index, count);\n            }\n            _version++;\n        }\n\n        // Sorts the elements in this list.  Uses the default comparer and \n        // Array.Sort.\n        public void Sort()\n        {\n            Sort(0, Count, null);\n        }\n\n        // Sorts the elements in this list.  Uses Array.Sort with the\n        // provided comparer.\n        public void Sort(IComparer<T> comparer)\n        {\n            Sort(0, Count, comparer);\n        }\n\n        // Sorts the elements in a section of this list. The sort compares the\n        // elements to each other using the given IComparer interface. If\n        // comparer is null, the elements are compared to each other using\n        // the IComparable interface, which in that case must be implemented by all\n        // elements of the list.\n        // \n        // This method uses the Array.Sort method to sort the elements.\n        // \n        public void Sort(int index, int count, IComparer<T> comparer)\n        {\n            if (count > 1)\n            {\n                Array.Sort<T>(_items, index, count, comparer);\n            }\n            _version++;\n        }\n\n        public void Sort(Comparison<T> comparison)\n        {\n            throw new NotImplementedException();\n            /*if (_size > 1)\n            {\n                ArraySortHelper<T>.Sort(_items, 0, _size, comparison);\n            }\n            _version++;*/\n        }\n\n        // ToArray returns an array containing the contents of the UncheckedList.\n        // This requires copying the UncheckedList, which is an O(n) operation.\n        public T[] ToArray()\n        {\n            if (_size == 0)\n            {\n                return _emptyArray;\n            }\n\n            T[] array = new T[_size];\n            Array.Copy(_items, 0, array, 0, _size);\n            return array;\n        }\n\n        // Sets the capacity of this list to the size of the list. This method can\n        // be used to minimize a list's memory overhead once it is known that no\n        // new elements will be added to the list. To completely clear a list and\n        // release all memory referenced by the list, execute the following\n        // statements:\n        // \n        // list.Clear();\n        // list.TrimExcess();\n        // \n        public void TrimExcess()\n        {\n            int threshold = (int)(((double)_items.Length) * 0.9);\n            if (_size < threshold)\n            {\n                Capacity = _size;\n            }\n        }\n\n        public bool TrueForAll(Predicate<T> match)\n        {\n            for (int i = 0; i < _size; i++)\n            {\n                if (!match(_items[i]))\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        private void AddEnumerable(IEnumerable<T> enumerable)\n        {\n            Debug.Assert(enumerable != null);\n            Debug.Assert(!(enumerable is ICollection<T>), \"We should have optimized for this beforehand.\");\n\n            using (IEnumerator<T> en = enumerable.GetEnumerator())\n            {\n                _version++; // Even if the enumerable has no items, we can update _version.\n\n                while (en.MoveNext())\n                {\n                    // Capture Current before doing anything else. If this throws\n                    // an exception, we want to make a clean break.\n                    T current = en.Current;\n\n                    if (_size == _items.Length)\n                    {\n                        EnsureCapacity(_size + 1);\n                    }\n\n                    _items[_size++] = current;\n                }\n            }\n        }\n\n        public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator\n        {\n            private UncheckedList<T> list;\n            private int index;\n            private int version;\n            private T current;\n\n            internal Enumerator(UncheckedList<T> list)\n            {\n                this.list = list;\n                index = 0;\n                version = list._version;\n                current = default(T);\n            }\n\n            public void Dispose()\n            {\n            }\n\n            public bool MoveNext()\n            {\n                UncheckedList<T> localUncheckedList = list;\n\n                if (version == localUncheckedList._version && ((uint)index < (uint)localUncheckedList._size))\n                {\n                    current = localUncheckedList._items[index];\n                    index++;\n                    return true;\n                }\n                return MoveNextRare();\n            }\n\n            private bool MoveNextRare()\n            {\n                index = list._size + 1;\n                current = default(T);\n                return false;\n            }\n\n            public T Current\n            {\n                get\n                {\n                    return current;\n                }\n            }\n\n            Object System.Collections.IEnumerator.Current\n            {\n                get\n                {\n                    return Current;\n                }\n            }\n\n            void System.Collections.IEnumerator.Reset()\n            {\n                index = 0;\n                current = default(T);\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/ILRuntime/Reflection/Extensions.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing Mono.Cecil;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\n\nnamespace ILRuntime.Reflection\n{\n    static class Extensions\n    {\n        public static object CreateInstance(this CustomAttribute attribute, IType at, Runtime.Enviorment.AppDomain appdomain)\n        {\n            object ins;\n            List<IType> param = null;\n            if (at is ILType)\n            {\n                var it = (ILType)at;\n                if (!attribute.HasConstructorArguments)\n                    ins = it.Instantiate(true);\n                else\n                {\n                    ins = it.Instantiate(false);\n                    if (param == null)\n                        param = new List<IType>();\n                    param.Clear();\n                    object[] p = new object[attribute.ConstructorArguments.Count];\n                    for (int j = 0; j < attribute.ConstructorArguments.Count; j++)\n                    {\n                        var ca = attribute.ConstructorArguments[j];\n                        param.Add(appdomain.GetType(ca.Type, null, null));\n                        p[j] = ca.Value;\n                    }\n                    var ctor = it.GetConstructor(param);\n                    appdomain.Invoke(ctor, ins, p);\n                }\n\n                if (attribute.HasProperties)\n                {\n                    object[] p = new object[1];\n                    foreach (var j in attribute.Properties)\n                    {\n                        p[0] = j.Argument.Value;\n                        var setter = it.GetMethod(\"set_\" + j.Name, 1);\n                        appdomain.Invoke(setter, ins, p);\n                    }\n                }\n            }\n            else\n            {\n                param = new List<IType>();\n                object[] p = null;\n                if (attribute.HasConstructorArguments)\n                {\n                    p = new object[attribute.ConstructorArguments.Count];\n                    for (int j = 0; j < attribute.ConstructorArguments.Count; j++)\n                    {\n                        var ca = attribute.ConstructorArguments[j];\n                        param.Add(appdomain.GetType(ca.Type, null, null));\n                        p[j] = ca.Value;\n                    }\n                }\n                ins = ((CLRMethod)at.GetConstructor(param)).ConstructorInfo.Invoke(p);\n                if (attribute.HasProperties)\n                {\n                    foreach (var j in attribute.Properties)\n                    {\n                        var prop = at.TypeForCLR.GetProperty(j.Name);\n                        prop.SetValue(ins, j.Argument.Value, null);\n                    }\n                }\n            }\n\n            return ins;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Reflection/ILRuntimeConstructorInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Globalization;\n\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeConstructorInfo : ConstructorInfo\n    {\n        ILMethod method;\n        ILRuntimeParameterInfo[] parameters;\n        public ILRuntimeConstructorInfo(ILMethod m)\n        {\n            method = m;\n            parameters = new ILRuntimeParameterInfo[m.ParameterCount];\n            for(int i = 0; i < m.ParameterCount; i++)\n            {\n                parameters[i] = new ILRuntimeParameterInfo(m.Parameters[i]);\n            }\n        }\n\n        internal ILMethod ILMethod { get { return method; } }\n        public override MethodAttributes Attributes\n        {\n            get\n            {\n                return MethodAttributes.Public;\n            }\n        }\n\n        public override Type DeclaringType\n        {\n            get\n            {\n                return method.DeclearingType.ReflectionType;\n            }\n        }\n\n        public override RuntimeMethodHandle MethodHandle\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return method.Name;\n            }\n        }\n\n        public override Type ReflectedType\n        {\n            get\n            {\n                return method.DeclearingType.ReflectionType;\n            }\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override MethodImplAttributes GetMethodImplementationFlags()\n        {\n            throw new NotImplementedException();\n        }\n\n        public override ParameterInfo[] GetParameters()\n        {\n            return parameters;\n        }\n\n        public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)\n        {\n            var res = ((ILType)method.DeclearingType).Instantiate(false);\n            method.DeclearingType.AppDomain.Invoke(method, res, parameters);\n            return res;\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)\n        {\n            var res = ((ILType)method.DeclearingType).Instantiate(false);\n            method.DeclearingType.AppDomain.Invoke(method, res, parameters);\n            return res;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Reflection/ILRuntimeFieldInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Globalization;\n\nusing Mono.Cecil;\nusing ILRuntime.CLR.Utils;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeFieldInfo : FieldInfo\n    {\n        System.Reflection.FieldAttributes attr;\n        ILRuntimeType dType;\n        ILType ilType;\n        IType fieldType;\n        bool isStatic;\n        int fieldIdx;\n        string name;\n        FieldDefinition definition;\n        Runtime.Enviorment.AppDomain appdomain;\n        object[] customAttributes;\n        Type[] attributeTypes;\n\n        public IType ILFieldType { get { return fieldType; } }\n\n        public ILRuntimeFieldInfo(FieldDefinition def, ILRuntimeType declaredType, bool isStatic, int fieldIdx)\n        {\n            definition = def;\n            this.name = def.Name;\n            dType = declaredType;\n            ilType = dType.ILType;\n            appdomain = ilType.AppDomain;\n            this.isStatic = isStatic;\n            this.fieldIdx = fieldIdx; \n            if (isStatic)\n                attr |= System.Reflection.FieldAttributes.Static;\n            if (def.IsPublic)\n            {\n                attr |= System.Reflection.FieldAttributes.Public;\n            }\n            else\n                attr |= System.Reflection.FieldAttributes.Private;\n            fieldType = isStatic ? ilType.StaticFieldTypes[fieldIdx] : ilType.FieldTypes[fieldIdx];\n        }\n\n        public ILRuntimeFieldInfo(FieldDefinition def, ILRuntimeType declaredType, int fieldIdx, IType fieldType)\n        {\n            definition = def;\n            this.name = def.Name;\n            dType = declaredType;\n            ilType = dType.ILType;\n            appdomain = ilType.AppDomain;\n            this.isStatic = false;\n            this.fieldIdx = fieldIdx;\n            if (isStatic)\n                attr |= System.Reflection.FieldAttributes.Static;\n            if (def.IsPublic)\n            {\n                attr |= System.Reflection.FieldAttributes.Public;\n            }\n            else\n                attr |= System.Reflection.FieldAttributes.Private;\n            this.fieldType = fieldType;\n        }\n\n        void InitializeCustomAttribute()\n        {\n            customAttributes = new object[definition.CustomAttributes.Count];\n            attributeTypes = new Type[customAttributes.Length];\n            for (int i = 0; i < definition.CustomAttributes.Count; i++)\n            {\n                var attribute = definition.CustomAttributes[i];\n                var at = appdomain.GetType(attribute.AttributeType, null, null);\n                try\n                {\n                    object ins = attribute.CreateInstance(at, appdomain);\n\n                    attributeTypes[i] = at.ReflectionType;\n                    customAttributes[i] = ins;\n                }\n                catch\n                {\n                    attributeTypes[i] = typeof(Attribute);\n                }\n            }\n        }\n\n        public override System.Reflection.FieldAttributes Attributes\n        {\n            get\n            {\n                return attr;\n            }\n        }\n\n        public override Type DeclaringType\n        {\n            get\n            {\n                return dType;\n            }\n        }\n\n        public override RuntimeFieldHandle FieldHandle\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override Type FieldType\n        {\n            get\n            {\n                return fieldType.ReflectionType;\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return name;\n            }\n        }\n\n        public override Type ReflectedType\n        {\n            get\n            {\n                return fieldType.ReflectionType;\n            }\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n\n            return customAttributes;\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            List<object> res = new List<object>();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    res.Add(customAttributes[i]);\n            }\n            return res.ToArray();\n        }\n\n        public override object GetValue(object obj)\n        {\n            unsafe\n            {\n                StackObject esp;\n                ILTypeInstance ins;\n                if (isStatic)\n                {\n                    ins = ilType.StaticInstance;\n                }\n                else\n                {\n                    if (obj is ILTypeInstance)\n                        ins = (ILTypeInstance)obj;\n                    else\n                        ins = ((CrossBindingAdaptorType)obj).ILInstance;\n                }\n                return fieldType.TypeForCLR.CheckCLRTypes(ins[fieldIdx]);\n            }\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    return true;\n            }\n            return false;\n        }\n\n        public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)\n        {\n            unsafe\n            {\n                StackObject esp;\n                if (value is CrossBindingAdaptorType)\n                    value = ((CrossBindingAdaptorType)value).ILInstance;\n                ILTypeInstance ins;\n                if (isStatic)\n                {\n                    ins = ilType.StaticInstance;\n                }\n                else\n                {\n                    if (obj is ILTypeInstance)\n                        ins = (ILTypeInstance)obj;\n                    else\n                        ins = ((CrossBindingAdaptorType)obj).ILInstance;\n                }\n                ins[fieldIdx] = value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Reflection/ILRuntimeMethodInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Globalization;\n\nusing ILRuntime.CLR.Method;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeMethodInfo : MethodInfo\n    {\n        ILMethod method;\n        ILRuntimeParameterInfo[] parameters;\n        Mono.Cecil.MethodDefinition definition;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n\n        object[] customAttributes;\n        Type[] attributeTypes;\n        public ILRuntimeMethodInfo(ILMethod m)\n        {\n            method = m;\n            definition = m.Definition;\n            appdomain = m.DeclearingType.AppDomain;\n            parameters = new ILRuntimeParameterInfo[m.ParameterCount];\n            for (int i = 0; i < m.ParameterCount; i++)\n            {\n                parameters[i] = new ILRuntimeParameterInfo(m.Parameters[i]);\n            }\n        }\n\n        void InitializeCustomAttribute()\n        {\n            customAttributes = new object[definition.CustomAttributes.Count];\n            attributeTypes = new Type[customAttributes.Length];\n            for (int i = 0; i < definition.CustomAttributes.Count; i++)\n            {\n                var attribute = definition.CustomAttributes[i];\n                var at = appdomain.GetType(attribute.AttributeType, null, null);\n                try\n                {\n                    object ins = attribute.CreateInstance(at, appdomain);\n\n                    attributeTypes[i] = at.ReflectionType;\n                    customAttributes[i] = ins;\n                }\n                catch\n                {\n                    attributeTypes[i] = typeof(Attribute);\n                }\n            }\n        }\n\n        internal ILMethod ILMethod { get { return method; } }\n        public override MethodAttributes Attributes\n        {\n            get\n            {\n                return MethodAttributes.Public;\n            }\n        }\n\n        public override Type DeclaringType\n        {\n            get\n            {\n                return method.DeclearingType.ReflectionType;\n            }\n        }\n\n        public override RuntimeMethodHandle MethodHandle\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return method.Name;\n            }\n        }\n\n        public override Type ReflectedType\n        {\n            get\n            {\n                return method.DeclearingType.ReflectionType;\n            }\n        }\n\n        public override ICustomAttributeProvider ReturnTypeCustomAttributes\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override MethodInfo GetBaseDefinition()\n        {\n            return this;\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n\n            return customAttributes;\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            List<object> res = new List<object>();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    res.Add(customAttributes[i]);\n            }\n            return res.ToArray();\n        }\n\n        public override MethodImplAttributes GetMethodImplementationFlags()\n        {\n            throw new NotImplementedException();\n        }\n\n        public override ParameterInfo[] GetParameters()\n        {\n            throw new NotImplementedException();\n        }\n\n        public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)\n        {\n            if (method.HasThis)\n            {\n                var res = appdomain.Invoke(method, obj, parameters);\n                return res;\n            }\n            else\n                return appdomain.Invoke(method, null, parameters);\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    return true;\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Reflection/ILRuntimeParameterInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Globalization;\n\nusing ILRuntime.CLR.TypeSystem;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeParameterInfo : ParameterInfo\n    {\n        IType type;\n\n        public ILRuntimeParameterInfo(IType type)\n        {\n            this.type = type;\n        }\n        public override Type ParameterType\n        {\n            get\n            {\n                return type.ReflectionType;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Reflection/ILRuntimePropertyInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Globalization;\n\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimePropertyInfo : PropertyInfo\n    {\n        ILMethod getter, setter;\n        ILType dType;\n        Mono.Cecil.PropertyDefinition definition;\n        ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n\n        object[] customAttributes;\n        Type[] attributeTypes;\n        static object[] param = new object[1];\n\n        public ILMethod Getter\n        {\n            get { return getter; }\n            set\n            {\n                getter = value;\n            }\n        }\n\n        public ILMethod Setter\n        {\n            get { return setter; }\n            set\n            {\n                setter = value;\n            }\n        }\n\n        public bool IsPublic\n        {\n            get\n            {\n                if (getter != null)\n                    return getter.Definition.IsPublic;\n                else\n                    return setter.Definition.IsPublic;\n            }\n        }\n\n        public bool IsStatic\n        {\n            get\n            {\n                if (getter != null)\n                    return getter.IsStatic;\n                else\n                    return setter.IsStatic;\n            }\n        }\n        public ILRuntimePropertyInfo(Mono.Cecil.PropertyDefinition definition, ILType dType)\n        {\n            this.definition = definition;\n            this.dType = dType;\n            appdomain = dType.AppDomain;\n        }\n\n        void InitializeCustomAttribute()\n        {\n            customAttributes = new object[definition.CustomAttributes.Count];\n            attributeTypes = new Type[customAttributes.Length];\n            for (int i = 0; i < definition.CustomAttributes.Count; i++)\n            {\n                var attribute = definition.CustomAttributes[i];\n                var at = appdomain.GetType(attribute.AttributeType, null, null);\n                try\n                {\n                    object ins = attribute.CreateInstance(at, appdomain);\n\n                    attributeTypes[i] = at.ReflectionType;\n                    customAttributes[i] = ins;\n                }\n                catch\n                {\n                    attributeTypes[i] = typeof(Attribute);\n                }\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return definition.Name;\n            }\n        }\n\n        public override Type ReflectedType\n        {\n            get\n            {\n                return dType.ReflectionType;\n            }\n        }\n\n        public override PropertyAttributes Attributes\n        {\n            get\n            {\n                return PropertyAttributes.None;\n            }\n        }\n\n        public override bool CanRead\n        {\n            get\n            {\n                return getter != null;\n            }\n        }\n\n        public override bool CanWrite\n        {\n            get\n            {\n                return setter != null;\n            }\n        }\n\n        public override Type PropertyType\n        {\n            get\n            {\n                if (getter != null)\n                    return getter.ReturnType.ReflectionType;\n                else\n                {\n                    return setter.Parameters[0].ReflectionType;\n                }\n            }\n        }\n\n        public override Type DeclaringType\n        {\n            get\n            {\n                return dType.ReflectionType;\n            }\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n\n            return customAttributes;\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            List<object> res = new List<object>();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    res.Add(customAttributes[i]);\n            }\n            return res.ToArray();\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    return true;\n            }\n            return false;\n        }\n\n        public override MethodInfo[] GetAccessors(bool nonPublic)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override MethodInfo GetGetMethod(bool nonPublic)\n        {\n            if (getter != null)\n                return getter.ReflectionMethodInfo;\n            return null;\n        }\n\n        public override ParameterInfo[] GetIndexParameters()\n        {\n            throw new NotImplementedException();\n        }\n\n        public override MethodInfo GetSetMethod(bool nonPublic)\n        {\n            if (setter != null)\n                return setter.ReflectionMethodInfo;\n            return null;\n        }\n\n        public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)\n        {\n            return appdomain.Invoke(getter, obj, null);\n        }\n\n        public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)\n        {\n            param[0] = value;\n            appdomain.Invoke(setter, obj, param);\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Reflection/ILRuntimeType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeType : Type\n    {\n        ILType type;\n        Runtime.Enviorment.AppDomain appdomain;\n        object[] customAttributes;\n        Type[] attributeTypes;\n        ILRuntimeFieldInfo[] fields;\n        ILRuntimePropertyInfo[] properties;\n        ILRuntimeMethodInfo[] methods;\n\n        public ILType ILType { get { return type; } }\n        \n        public ILRuntimeType(ILType t)\n        {\n            type = t;\n            appdomain = t.AppDomain;\n        }\n\n        void InitializeCustomAttribute()\n        {\n            customAttributes = new object[type.TypeDefinition.CustomAttributes.Count];\n            attributeTypes = new Type[customAttributes.Length];\n            for (int i = 0; i < type.TypeDefinition.CustomAttributes.Count; i++)\n            {\n                var attribute = type.TypeDefinition.CustomAttributes[i];\n                var at = appdomain.GetType(attribute.AttributeType, type, null);\n                try\n                {\n                    object ins = attribute.CreateInstance(at, appdomain);\n\n                    attributeTypes[i] = at.ReflectionType is ILRuntimeWrapperType ? at.TypeForCLR : at.ReflectionType;\n                    customAttributes[i] = ins;\n                }\n                catch\n                {\n                    attributeTypes[i] = typeof(Attribute);\n                }               \n            }\n\n        }\n\n        void InitializeProperties()\n        {\n            int cnt = type.TypeDefinition.HasProperties ? type.TypeDefinition.Properties.Count : 0;\n            properties = new ILRuntimePropertyInfo[cnt];\n            for (int i = 0; i < cnt; i++)\n            {\n                Mono.Cecil.PropertyDefinition pd = type.TypeDefinition.Properties[i];\n                ILRuntimePropertyInfo pi = new ILRuntimePropertyInfo(pd, type);\n                properties[i] = pi;\n                if (pd.GetMethod != null)\n                    pi.Getter = type.GetMethod(pd.GetMethod.Name, 0) as ILMethod;\n                if (pd.SetMethod != null)\n                    pi.Setter = type.GetMethod(pd.SetMethod.Name, 1) as ILMethod;\n            }\n        }\n\n        void InitializeMethods()\n        {\n            var methods = type.GetMethods();\n            this.methods = new ILRuntimeMethodInfo[methods.Count];\n            for(int i = 0; i < methods.Count; i++)\n            {\n                this.methods[i] = (ILRuntimeMethodInfo)((ILMethod)methods[i]).ReflectionMethodInfo;\n            }\n        }\n\n        void InitializeFields()\n        {\n            int staticCnt = type.StaticFieldTypes != null ? type.StaticFieldTypes.Length : 0;\n            fields = new ILRuntimeFieldInfo[type.TotalFieldCount + staticCnt];\n            for (int i = 0; i < type.TotalFieldCount; i++)\n            {\n                Mono.Cecil.FieldDefinition fd;\n                var t = type.GetField(i, out fd);\n                fields[i] = new ILRuntimeFieldInfo(fd, this, i, t);\n            }\n            for (int i = type.TotalFieldCount; i < type.TotalFieldCount + staticCnt; i++)\n            {\n                fields[i] = new ILRuntimeFieldInfo(type.StaticFieldDefinitions[i - type.TotalFieldCount], this, true, i - type.TotalFieldCount);\n            }\n        }\n\n        public override Assembly Assembly\n        {\n            get\n            {\n                return typeof(ILRuntimeType).Assembly;\n            }\n        }\n\n        public override string AssemblyQualifiedName\n        {\n            get\n            {\n                return type.FullName;\n            }\n        }\n\n        public override Type BaseType\n        {\n            get\n            {\n                return type.BaseType != null ? type.BaseType.ReflectionType : null;\n            }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                return type.FullName;\n            }\n        }\n\n        public override Guid GUID\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override Module Module\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return type.Name;\n            }\n        }\n\n        public override string Namespace\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public override Type UnderlyingSystemType\n        {\n            get\n            {\n                return typeof(ILTypeInstance);\n            }\n        }\n\n        public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)\n        {\n            var ctors = type.GetConstructors();\n            ConstructorInfo[] res = new ConstructorInfo[ctors.Count];\n            for(int i = 0; i < res.Length; i++)\n            {\n                res[i] = ctors[i].ReflectionConstructorInfo;\n            }\n            return res;\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n\n            return customAttributes;\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            List<object> res = new List<object>();\n            for(int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    res.Add(customAttributes[i]);\n            }\n            return res.ToArray();\n        }\n\n        public override Type GetElementType()\n        {\n            if (type.IsArray)\n            {\n                return type.ElementType.ReflectionType;\n            }\n            else\n                throw new NotImplementedException();\n        }\n\n        public override EventInfo GetEvent(string name, BindingFlags bindingAttr)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override EventInfo[] GetEvents(BindingFlags bindingAttr)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override FieldInfo GetField(string name, BindingFlags bindingAttr)\n        {\n            if (fields == null)\n                InitializeFields();\n            foreach(var i in fields)\n            {\n                if (i.Name == name)\n                    return i;\n            }\n            return null;\n        }\n\n        public override FieldInfo[] GetFields(BindingFlags bindingAttr)\n        {\n            if (fields == null)\n                InitializeFields();\n            bool isPublic = (bindingAttr & BindingFlags.Public) == BindingFlags.Public;\n            bool isPrivate = (bindingAttr & BindingFlags.NonPublic) == BindingFlags.NonPublic;\n            bool isStatic = (bindingAttr & BindingFlags.Static) == BindingFlags.Static;\n            bool isInstance = (bindingAttr & BindingFlags.Instance) == BindingFlags.Instance;\n            List<FieldInfo> res = new List<FieldInfo>();\n            foreach(var i in fields)\n            {\n                if (isPublic != i.IsPublic && isPrivate != !i.IsPublic)\n                    continue;\n                if ((isStatic != i.IsStatic) && (isInstance != !i.IsStatic))\n                    continue;\n                res.Add(i);\n            }\n            return res.ToArray();\n        }\n\n        public override Type GetInterface(string name, bool ignoreCase)\n        {\n            if (type.FirstCLRInterface != null)\n            {\n                if (type.FirstCLRInterface.Name == name)\n                    return type.FirstCLRInterface.TypeForCLR;\n                else\n                    return null;\n            }\n            else\n                return null;\n        }\n\n        public override Type[] GetInterfaces()\n        {\n            if (type.FirstCLRInterface != null)\n                return new Type[] { type.FirstCLRInterface.TypeForCLR };\n            else\n                return new Type[0];\n        }\n\n        public override MemberInfo[] GetMembers(BindingFlags bindingAttr)\n        {\n            if (methods == null)\n                InitializeMethods();\n            if (fields == null)\n                InitializeFields();\n            if (properties == null)\n                InitializeProperties();\n            MemberInfo[] res = new MemberInfo[methods.Length + fields.Length + properties.Length];\n            for (int i = 0; i < methods.Length; i++)\n            {\n                res[i] = methods[i];\n            }\n            for (int i = methods.Length; i < methods.Length + fields.Length; i++)\n            {\n                res[i] = fields[i - methods.Length];\n            }\n            for (int i = methods.Length + fields.Length; i < res.Length; i++)\n            {\n                res[i] = properties[i- methods.Length - fields.Length];\n            }\n\n            return res;\n        }\n\n        public override MethodInfo[] GetMethods(BindingFlags bindingAttr)\n        {\n            if (methods == null)\n                InitializeMethods();\n            return methods;\n        }\n\n        public override Type GetNestedType(string name, BindingFlags bindingAttr)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override Type[] GetNestedTypes(BindingFlags bindingAttr)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)\n        {\n            if (properties == null)\n                InitializeProperties();\n            bool isPublic = (bindingAttr & BindingFlags.Public) == BindingFlags.Public;\n            bool isPrivate = (bindingAttr & BindingFlags.NonPublic) == BindingFlags.NonPublic;\n            bool isStatic = (bindingAttr & BindingFlags.Static) == BindingFlags.Static;\n            bool isInstance = (bindingAttr & BindingFlags.Instance) == BindingFlags.Instance;\n            List<PropertyInfo> res = new List<PropertyInfo>();\n            foreach (var i in properties)\n            {\n                if (isPublic != i.IsPublic && isPrivate != !i.IsPublic)\n                    continue;\n                if ((isStatic != i.IsStatic) && (isInstance != !i.IsStatic))\n                    continue;\n                res.Add(i);\n            }\n            return res.ToArray();\n        }\n\n        public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            if (customAttributes == null)\n                InitializeCustomAttribute();\n            for (int i = 0; i < customAttributes.Length; i++)\n            {\n                if (attributeTypes[i] == attributeType)\n                    return true;\n            }\n            return false;\n        }\n\n        protected override TypeAttributes GetAttributeFlagsImpl()\n        {\n            TypeAttributes res = TypeAttributes.Public;\n            if (type.TypeDefinition.IsAbstract)\n                res |= TypeAttributes.Abstract;\n            if (!type.IsValueType)\n                res |= TypeAttributes.Class;\n            if (type.TypeDefinition.IsSealed)\n                res |= TypeAttributes.Sealed;\n            return res;\n        }\n\n        protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)\n        {\n            List<IType> param = new List<IType>();\n            for (int i = 0; i < types.Length; i++)\n            {\n                if (types[i] is ILRuntimeType)\n                    param.Add(((ILRuntimeType)types[i]).type);\n                else\n                {\n                    var t = appdomain.GetType(types[i]);\n                    if (t == null)\n                        t = appdomain.GetType(types[i].AssemblyQualifiedName);\n                    if (t == null)\n                        throw new TypeLoadException();\n                    param.Add(t);\n                }\n            }\n\n            var res = type.GetConstructor(param);\n\n            if (res != null)\n                return ((ILMethod)res).ReflectionConstructorInfo;\n            else\n                return null;\n        }\n\n        protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)\n        {\n            IMethod res;\n            if (types == null)\n                res = type.GetMethod(name);\n            else\n            {\n                List<IType> param = new List<IType>();\n                for (int i = 0; i < types.Length; i++)\n                {\n                    if (types[i] is ILRuntimeType)\n                        param.Add(((ILRuntimeType)types[i]).type);\n                    else\n                    {\n                        var t = appdomain.GetType(types[i]);\n                        if (t == null)\n                            t = appdomain.GetType(types[i].AssemblyQualifiedName);\n                        if (t == null)\n                            throw new TypeLoadException();\n                        param.Add(t);\n                    }\n                }\n                bool declearedOnly = (bindingAttr & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly;\n                res = type.GetMethod(name, param, null, null, declearedOnly);\n            }\n            if (res != null)\n                return ((ILMethod)res).ReflectionMethodInfo;\n            else\n                return null;\n        }\n\n        protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)\n        {\n            if (properties == null)\n                InitializeProperties();\n\n            foreach(var i in properties)\n            {\n                if (i.Name == name)\n                    return i;\n            }\n            return null;\n        }\n\n        protected override bool HasElementTypeImpl()\n        {\n            return false;\n        }\n\n        protected override bool IsArrayImpl()\n        {\n            return type.IsArray;\n        }\n\n        protected override bool IsByRefImpl()\n        {\n            return false;\n        }\n\n        protected override bool IsCOMObjectImpl()\n        {\n            return false;\n        }\n\n        protected override bool IsPointerImpl()\n        {\n            return false;\n        }\n\n        protected override bool IsPrimitiveImpl()\n        {\n            return false;\n        }\n        public override int GetHashCode()\n        {\n            return type.GetHashCode();\n        }\n        public override bool Equals(object o)\n        {\n            return o is ILRuntimeType ? ((ILRuntimeType)o).type == type : false;\n        }\n        public override bool IsGenericType\n        {\n            get\n            {\n                return type.HasGenericParameter;\n            }\n        }\n\n        public override bool IsGenericTypeDefinition\n        {\n            get\n            {\n                return type.HasGenericParameter;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Reflection/ILRuntimeWrapperType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Reflection\n{\n    public class ILRuntimeWrapperType : Type\n    {\n        CLRType type;\n        Type et;\n\n        public CLRType CLRType { get { return type; } }\n\n        public Type RealType { get { return et; } }\n\n        public override Guid GUID\n        {\n            get\n            {\n                return et.GUID;\n            }\n        }\n\n        public override Module Module\n        {\n            get\n            {\n                return et.Module;\n            }\n        }\n\n        public override Assembly Assembly\n        {\n            get\n            {\n                return et.Assembly;\n            }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                return et.FullName;\n            }\n        }\n\n        public override string Namespace\n        {\n            get\n            {\n                return et.Namespace;\n            }\n        }\n\n        public override string AssemblyQualifiedName\n        {\n            get\n            {\n                return et.AssemblyQualifiedName;\n            }\n        }\n\n        public override Type BaseType\n        {\n            get\n            {\n                return et.BaseType;\n            }\n        }\n\n        public override Type UnderlyingSystemType\n        {\n            get\n            {\n                return et.UnderlyingSystemType;\n            }\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return et.Name;\n            }\n        }\n\n        public ILRuntimeWrapperType(CLRType t)\n        {\n            type = t;\n            et = t.TypeForCLR;\n        }\n\n        public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)\n        {\n            return et.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);\n        }\n\n        protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)\n        {\n            return et.GetConstructor(bindingAttr, binder, callConvention, types, modifiers);\n        }\n\n        public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)\n        {\n            return et.GetConstructors(bindingAttr);\n        }\n\n        protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)\n        {\n            return et.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);\n        }\n\n        public override MethodInfo[] GetMethods(BindingFlags bindingAttr)\n        {\n            return et.GetMethods(bindingAttr);\n        }\n\n        public override FieldInfo GetField(string name, BindingFlags bindingAttr)\n        {\n            return et.GetField(name, bindingAttr);\n        }\n\n        public override FieldInfo[] GetFields(BindingFlags bindingAttr)\n        {\n            return et.GetFields(bindingAttr);\n        }\n\n        public override Type GetInterface(string name, bool ignoreCase)\n        {\n            return et.GetInterface(name, ignoreCase);\n        }\n\n        public override Type[] GetInterfaces()\n        {\n            return et.GetInterfaces();\n        }\n\n        public override EventInfo GetEvent(string name, BindingFlags bindingAttr)\n        {\n            return et.GetEvent(name, bindingAttr);\n        }\n\n        public override EventInfo[] GetEvents(BindingFlags bindingAttr)\n        {\n            return et.GetEvents(bindingAttr);\n        }\n\n        protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)\n        {\n            return et.GetProperty(name, bindingAttr, binder, returnType, types, modifiers);\n        }\n\n        public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)\n        {\n            return et.GetProperties(bindingAttr);\n        }\n\n        public override Type[] GetNestedTypes(BindingFlags bindingAttr)\n        {\n            return et.GetNestedTypes(bindingAttr);\n        }\n\n        public override int GetHashCode()\n        {\n            return type.GetHashCode();\n        }\n\n        public override Type GetNestedType(string name, BindingFlags bindingAttr)\n        {\n            return et.GetNestedType(name, bindingAttr);\n        }\n\n        public override MemberInfo[] GetMembers(BindingFlags bindingAttr)\n        {\n            return et.GetMembers(bindingAttr);\n        }\n\n        protected override TypeAttributes GetAttributeFlagsImpl()\n        {\n            return et.Attributes;\n        }\n\n        protected override bool IsArrayImpl()\n        {\n            return et.IsArray;\n        }\n\n        protected override bool IsByRefImpl()\n        {\n            return et.IsByRef;\n        }\n\n        protected override bool IsPointerImpl()\n        {\n            return et.IsPointer;\n        }\n\n        protected override bool IsPrimitiveImpl()\n        {\n            return et.IsPrimitive;\n        }\n\n        protected override bool IsCOMObjectImpl()\n        {\n            return et.IsCOMObject;\n        }\n\n        public override Type GetElementType()\n        {\n            return et.GetElementType();\n        }\n\n        protected override bool HasElementTypeImpl()\n        {\n            return et.HasElementType;\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            return et.GetCustomAttributes(inherit);\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            return et.GetCustomAttributes(attributeType, inherit);\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            return et.IsDefined(attributeType, inherit);\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Adaptors/CLRCrossBindingAdaptors.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Runtime.Adaptors\n{\n    class AttributeAdaptor : CrossBindingAdaptor\n    {\n        public override Type AdaptorType\n        {\n            get\n            {\n                return typeof(Adaptor);\n            }\n        }\n\n        public override Type BaseCLRType\n        {\n            get\n            {\n                return typeof(Attribute);\n            }\n        }\n\n        public override object CreateCLRInstance(Enviorment.AppDomain appdomain, ILTypeInstance instance)\n        {\n            return new Adaptor(appdomain, instance);\n        }\n\n        class Adaptor : Attribute, CrossBindingAdaptorType\n        {\n            ILTypeInstance instance;\n            ILRuntime.Runtime.Enviorment.AppDomain appdomain;\n\n            bool isToStringGot;\n            IMethod toString;\n\n            public Adaptor(ILRuntime.Runtime.Enviorment.AppDomain appdomain, ILTypeInstance instance)\n            {\n                this.appdomain = appdomain;\n                this.instance = instance;\n            }\n            public ILTypeInstance ILInstance\n            {\n                get\n                {\n                    return instance;\n                }\n            }\n\n            public override string ToString()\n            {\n                if (!isToStringGot)\n                {\n                    isToStringGot = true;\n                    IMethod m = appdomain.ObjectType.GetMethod(\"ToString\", 0);\n                    toString = instance.Type.GetVirtualMethod(m);\n                }\n                if (toString == null || toString is ILMethod)\n                {\n                    return instance.ToString();\n                }\n                else\n                    return instance.Type.FullName;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/CLRBinding/BindingCodeGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Other;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    public class BindingCodeGenerator\n    {\n        public static void GenerateBindingCode(List<Type> types, string outputPath, HashSet<MethodBase> excludeMethods = null, HashSet<FieldInfo> excludeFields = null)\n        {\n            if (!System.IO.Directory.Exists(outputPath))\n                System.IO.Directory.CreateDirectory(outputPath);\n            string[] oldFiles = System.IO.Directory.GetFiles(outputPath, \"*.cs\");\n            foreach (var i in oldFiles)\n            {\n                System.IO.File.Delete(i);\n            }\n            List<string> clsNames = new List<string>();\n            foreach (var i in types)\n            {\n                string clsName, realClsName;\n                bool isByRef;\n                if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)\n                    continue;\n                i.GetClassName(out clsName, out realClsName, out isByRef);\n                clsNames.Add(clsName);\n                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + \"/\" + clsName + \".cs\", false, Encoding.UTF8))\n                {\n                    sw.Write(@\"using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Reflection;\nusing ILRuntime.CLR.Utils;\n\nnamespace ILRuntime.Runtime.Generated\n{\n    unsafe class \");\n                    sw.WriteLine(clsName);\n                    sw.Write(@\"    {\n        public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)\n        {\n            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;\n            MethodBase method;\n            FieldInfo field;\n            Type[] args;\n            Type type = typeof(\");\n                    sw.Write(realClsName);\n                    sw.WriteLine(\");\");\n                    MethodInfo[] methods = i.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);\n                    FieldInfo[] fields = i.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);\n                    string registerMethodCode = i.GenerateMethodRegisterCode(methods, excludeMethods);\n                    string registerFieldCode = i.GenerateFieldRegisterCode(fields, excludeFields);\n                    string registerValueTypeCode = i.GenerateValueTypeRegisterCode(realClsName);\n                    string registerMiscCode = i.GenerateMiscRegisterCode(realClsName, true, true);\n                    string commonCode = i.GenerateCommonCode(realClsName);\n                    ConstructorInfo[] ctors = i.GetConstructors(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);\n                    string ctorRegisterCode = i.GenerateConstructorRegisterCode(ctors, excludeMethods);\n                    string methodWraperCode = i.GenerateMethodWraperCode(methods, realClsName, excludeMethods);\n                    string fieldWraperCode = i.GenerateFieldWraperCode(fields, realClsName, excludeFields);\n                    string cloneWraperCode = i.GenerateCloneWraperCode(fields, realClsName);\n                    string ctorWraperCode = i.GenerateConstructorWraperCode(ctors, realClsName, excludeMethods);\n                    sw.WriteLine(registerMethodCode);\n                    sw.WriteLine(registerFieldCode);\n                    sw.WriteLine(registerValueTypeCode);\n                    sw.WriteLine(registerMiscCode);\n                    sw.WriteLine(ctorRegisterCode);\n                    sw.WriteLine(\"        }\");\n                    sw.WriteLine();\n                    sw.WriteLine(commonCode);\n                    sw.WriteLine(methodWraperCode);\n                    sw.WriteLine(fieldWraperCode);\n                    sw.WriteLine(cloneWraperCode);\n                    sw.WriteLine(ctorWraperCode);\n                    sw.WriteLine(\"    }\");\n                    sw.WriteLine(\"}\");\n                    sw.Flush();\n                }\n            }\n\n            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + \"/CLRBindings.cs\", false, Encoding.UTF8))\n            {\n                sw.WriteLine(@\"using System;\nusing System.Collections.Generic;\nusing System.Reflection;\n\nnamespace ILRuntime.Runtime.Generated\n{\n    class CLRBindings\n    {\n        /// <summary>\n        /// Initialize the CLR binding, please invoke this AFTER CLR Redirection registration\n        /// </summary>\n        public static void Initialize(ILRuntime.Runtime.Enviorment.AppDomain app)\n        {\");\n                foreach (var i in clsNames)\n                {\n                    sw.Write(\"            \");\n                    sw.Write(i);\n                    sw.WriteLine(\".Register(app);\");\n                }\n\n                sw.WriteLine(@\"        }\n    }\n}\");\n            }\n        }\n\n        class CLRBindingGenerateInfo\n        {\n            public Type Type { get; set; }\n            public HashSet<MethodInfo> Methods { get; set; }\n            public HashSet<FieldInfo> Fields { get; set; }\n            public HashSet<ConstructorInfo> Constructors { get; set; }\n            public bool ArrayNeeded { get; set; }\n            public bool DefaultInstanceNeeded { get; set; }\n            public bool ValueTypeNeeded { get; set; }\n\n            public bool NeedGenerate\n            {\n                get\n                {\n                    if (Methods.Count == 0 && Constructors.Count == 0 && Fields.Count == 0 && !ArrayNeeded && !DefaultInstanceNeeded && !ValueTypeNeeded)\n                        return false;\n                    else\n                    {\n                        //Making CLRBinding for such types makes no sense\n                        if (Type == typeof(Delegate) || Type == typeof(System.Runtime.CompilerServices.RuntimeHelpers))\n                            return false;\n                        return true;\n                    }\n                }\n            }\n        }\n\n        public static void GenerateBindingCode(ILRuntime.Runtime.Enviorment.AppDomain domain, string outputPath)\n        {\n            if (domain == null)\n                return;\n            if (!System.IO.Directory.Exists(outputPath))\n                System.IO.Directory.CreateDirectory(outputPath);\n            Dictionary<Type, CLRBindingGenerateInfo> infos = new Dictionary<Type, CLRBindingGenerateInfo>(new ByReferenceKeyComparer<Type>());\n            CrawlAppdomain(domain, infos);\n            string[] oldFiles = System.IO.Directory.GetFiles(outputPath, \"*.cs\");\n            foreach (var i in oldFiles)\n            {\n                System.IO.File.Delete(i);\n            }\n\n            HashSet<MethodBase> excludeMethods = null;\n            HashSet<FieldInfo> excludeFields = null;\n            List<string> clsNames = new List<string>();\n            foreach (var info in infos)\n            {\n                if (!info.Value.NeedGenerate)\n                    continue;\n                Type i = info.Value.Type;\n                string clsName, realClsName;\n                bool isByRef;\n                if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)\n                    continue;\n                i.GetClassName(out clsName, out realClsName, out isByRef);\n                clsNames.Add(clsName);\n                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + \"/\" + clsName + \".cs\", false, Encoding.UTF8))\n                {\n                    sw.Write(@\"using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Reflection;\nusing ILRuntime.CLR.Utils;\n\nnamespace ILRuntime.Runtime.Generated\n{\n    unsafe class \");\n                    sw.WriteLine(clsName);\n                    sw.Write(@\"    {\n        public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)\n        {\n            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;\n            MethodBase method;\n            FieldInfo field;\n            Type[] args;\n            Type type = typeof(\");\n                    sw.Write(realClsName);\n                    sw.WriteLine(\");\");\n                    MethodInfo[] methods = info.Value.Methods.ToArray();\n                    FieldInfo[] fields = info.Value.Fields.ToArray();\n                    string registerMethodCode = i.GenerateMethodRegisterCode(methods, excludeMethods);\n                    string registerFieldCode = fields.Length > 0 ? i.GenerateFieldRegisterCode(fields, excludeFields) : null;\n                    string registerValueTypeCode = info.Value.ValueTypeNeeded ? i.GenerateValueTypeRegisterCode(realClsName) : null;\n                    string registerMiscCode = i.GenerateMiscRegisterCode(realClsName, info.Value.DefaultInstanceNeeded, info.Value.ArrayNeeded);\n                    string commonCode = i.GenerateCommonCode(realClsName);\n                    ConstructorInfo[] ctors = info.Value.Constructors.ToArray();\n                    string ctorRegisterCode = i.GenerateConstructorRegisterCode(ctors, excludeMethods);\n                    string methodWraperCode = i.GenerateMethodWraperCode(methods, realClsName, excludeMethods);\n                    string fieldWraperCode = fields.Length > 0 ? i.GenerateFieldWraperCode(fields, realClsName, excludeFields) : null;\n                    string cloneWraperCode = null;\n                    if (info.Value.ValueTypeNeeded)\n                    {\n                        //Memberwise clone should copy all fields\n                        var fs = i.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);\n                        cloneWraperCode = i.GenerateCloneWraperCode(fs, realClsName);\n                    }\n                    string ctorWraperCode = i.GenerateConstructorWraperCode(ctors, realClsName, excludeMethods);\n                    sw.WriteLine(registerMethodCode);\n                    if (fields.Length > 0)\n                        sw.WriteLine(registerFieldCode);\n                    if (info.Value.ValueTypeNeeded)\n                        sw.WriteLine(registerValueTypeCode);\n                    if (!string.IsNullOrEmpty(registerMiscCode))\n                        sw.WriteLine(registerMiscCode);\n                    sw.WriteLine(ctorRegisterCode);\n                    sw.WriteLine(\"        }\");\n                    sw.WriteLine();\n                    sw.WriteLine(commonCode);\n                    sw.WriteLine(methodWraperCode);\n                    if (fields.Length > 0)\n                        sw.WriteLine(fieldWraperCode);\n                    if (info.Value.ValueTypeNeeded)\n                        sw.WriteLine(cloneWraperCode);\n                    sw.WriteLine(ctorWraperCode);\n                    sw.WriteLine(\"    }\");\n                    sw.WriteLine(\"}\");\n                    sw.Flush();\n                }\n            }\n\n            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + \"/CLRBindings.cs\", false, Encoding.UTF8))\n            {\n                sw.WriteLine(@\"using System;\nusing System.Collections.Generic;\nusing System.Reflection;\n\nnamespace ILRuntime.Runtime.Generated\n{\n    class CLRBindings\n    {\n        /// <summary>\n        /// Initialize the CLR binding, please invoke this AFTER CLR Redirection registration\n        /// </summary>\n        public static void Initialize(ILRuntime.Runtime.Enviorment.AppDomain app)\n        {\");\n                foreach (var i in clsNames)\n                {\n                    sw.Write(\"            \");\n                    sw.Write(i);\n                    sw.WriteLine(\".Register(app);\");\n                }\n\n                sw.WriteLine(@\"        }\n    }\n}\");\n            }\n        }\n\n        static void CrawlAppdomain(ILRuntime.Runtime.Enviorment.AppDomain domain, Dictionary<Type, CLRBindingGenerateInfo> infos)\n        {\n            var arr = domain.LoadedTypes.Values.ToArray();\n            //Prewarm\n            foreach (var type in arr)\n            {\n                if (type is CLR.TypeSystem.ILType)\n                {\n                    if (type.HasGenericParameter)\n                        continue;\n                    var methods = type.GetMethods().ToList();\n                    foreach (var i in ((CLR.TypeSystem.ILType)type).GetConstructors())\n                        methods.Add(i);\n                    if (((CLR.TypeSystem.ILType)type).GetStaticConstroctor() != null)\n                        methods.Add(((CLR.TypeSystem.ILType)type).GetStaticConstroctor());\n                    foreach (var j in methods)\n                    {\n                        CLR.Method.ILMethod method = j as CLR.Method.ILMethod;\n                        if (method != null)\n                        {\n                            if (method.GenericParameterCount > 0 && !method.IsGenericInstance)\n                                continue;\n                            var body = method.Body;\n                        }\n                    }\n                }\n            }\n            arr = domain.LoadedTypes.Values.ToArray();\n            foreach (var type in arr)\n            {\n                if (type is CLR.TypeSystem.ILType)\n                {\n                    if (type.HasGenericParameter)\n                        continue;\n                    var methods = type.GetMethods().ToList();\n                    foreach (var i in ((CLR.TypeSystem.ILType)type).GetConstructors())\n                        methods.Add(i);\n\n                    foreach (var j in methods)\n                    {\n                        CLR.Method.ILMethod method = j as CLR.Method.ILMethod;\n                        if (method != null)\n                        {\n                            if (method.GenericParameterCount > 0 && !method.IsGenericInstance)\n                                continue;\n                            var body = method.Body;\n                            foreach (var ins in body)\n                            {\n                                switch (ins.Code)\n                                {\n                                    case Intepreter.OpCodes.OpCodeEnum.Newobj:\n                                        {\n                                            CLR.Method.CLRMethod m = domain.GetMethod(ins.TokenInteger) as CLR.Method.CLRMethod;\n                                            if (m != null)\n                                            {\n                                                if (m.DeclearingType.IsDelegate)\n                                                    continue;\n                                                Type t = m.DeclearingType.TypeForCLR;\n                                                CLRBindingGenerateInfo info;\n                                                if (!infos.TryGetValue(t, out info))\n                                                {\n                                                    info = CreateNewBindingInfo(t);\n                                                    infos[t] = info;\n                                                }\n                                                if (m.IsConstructor)\n                                                    info.Constructors.Add(m.ConstructorInfo);\n                                                else\n                                                    info.Methods.Add(m.MethodInfo);\n                                            }\n                                        }\n                                        break;\n                                    case Intepreter.OpCodes.OpCodeEnum.Ldfld:\n                                    case Intepreter.OpCodes.OpCodeEnum.Stfld:\n                                    case Intepreter.OpCodes.OpCodeEnum.Ldflda:\n                                    case Intepreter.OpCodes.OpCodeEnum.Ldsfld:\n                                    case Intepreter.OpCodes.OpCodeEnum.Ldsflda:\n                                    case Intepreter.OpCodes.OpCodeEnum.Stsfld:\n                                        {\n                                            var t = domain.GetType((int)(ins.TokenLong >> 32)) as CLR.TypeSystem.CLRType;\n                                            if(t != null)\n                                            {\n                                                var fi = t.GetField((int)ins.TokenLong);\n                                                if (fi != null && fi.IsPublic)\n                                                {\n                                                    CLRBindingGenerateInfo info;\n                                                    if (!infos.TryGetValue(t.TypeForCLR, out info))\n                                                    {\n                                                        info = CreateNewBindingInfo(t.TypeForCLR);\n                                                        infos[t.TypeForCLR] = info;\n                                                    }\n                                                    if(ins.Code == Intepreter.OpCodes.OpCodeEnum.Stfld || ins.Code == Intepreter.OpCodes.OpCodeEnum.Stsfld)\n                                                    {\n                                                        if (t.IsValueType)\n                                                        {\n                                                            info.ValueTypeNeeded = true;\n                                                            info.DefaultInstanceNeeded = true;\n                                                        }\n                                                    }\n                                                    if (t.TypeForCLR.CheckCanPinn() || !t.IsValueType)\n                                                        info.Fields.Add(fi);\n                                                }\n                                            }\n                                        }\n                                        break;\n                                    case Intepreter.OpCodes.OpCodeEnum.Ldtoken:\n                                        {\n                                            if (ins.TokenInteger == 0)\n                                            {\n                                                var t = domain.GetType((int)(ins.TokenLong >> 32)) as CLR.TypeSystem.CLRType;\n                                                if (t != null)\n                                                {\n                                                    var fi = t.GetField((int)ins.TokenLong);\n                                                    if (fi != null)\n                                                    {\n                                                        CLRBindingGenerateInfo info;\n                                                        if (!infos.TryGetValue(t.TypeForCLR, out info))\n                                                        {\n                                                            info = CreateNewBindingInfo(t.TypeForCLR);\n                                                            infos[t.TypeForCLR] = info;\n                                                        }\n                                                        info.Fields.Add(fi);\n                                                    }\n                                                }\n                                            }\n                                        }\n                                        break;\n                                    case Intepreter.OpCodes.OpCodeEnum.Newarr:\n                                        {\n                                            var t = domain.GetType(ins.TokenInteger) as CLR.TypeSystem.CLRType;\n                                            if(t != null)\n                                            {\n                                                CLRBindingGenerateInfo info;\n                                                if (!infos.TryGetValue(t.TypeForCLR, out info))\n                                                {\n                                                    info = CreateNewBindingInfo(t.TypeForCLR);\n                                                    infos[t.TypeForCLR] = info;\n                                                }\n                                                info.ArrayNeeded = true;\n                                            }\n                                        }\n                                        break;\n                                    case Intepreter.OpCodes.OpCodeEnum.Call:\n                                    case Intepreter.OpCodes.OpCodeEnum.Callvirt:\n                                        {\n                                            CLR.Method.CLRMethod m = domain.GetMethod(ins.TokenInteger) as CLR.Method.CLRMethod;\n                                            if (m != null)\n                                            {\n                                                //Cannot explicit call base class's constructor directly\n                                                if (m.IsConstructor)\n                                                    continue;\n                                                if (!m.MethodInfo.IsPublic)\n                                                    continue;\n                                                Type t = m.DeclearingType.TypeForCLR;\n                                                CLRBindingGenerateInfo info;\n                                                if (!infos.TryGetValue(t, out info))\n                                                {\n                                                    info = CreateNewBindingInfo(t);\n                                                    infos[t] = info;\n                                                }\n\n                                                info.Methods.Add(m.MethodInfo);\n                                            }\n                                        }\n                                        break;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        static CLRBindingGenerateInfo CreateNewBindingInfo(Type t)\n        {\n            CLRBindingGenerateInfo info = new CLRBindingGenerateInfo();\n            info.Type = t;\n            info.Methods = new HashSet<MethodInfo>();\n            info.Fields = new HashSet<FieldInfo>();\n            info.Constructors = new HashSet<ConstructorInfo>();\n\n            return info;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/CLRBinding/BindingGeneratorExtensions.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class BindingGeneratorExtensions\n    {\n        internal static bool ShouldSkipField(this Type type, FieldInfo i)\n        {\n            if (i.IsPrivate)\n                return true;\n            //EventHandler is currently not supported\n            if (i.IsSpecialName)\n            {\n                return true;\n            }\n            if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)\n                return true;\n            return false;\n        }\n\n        internal static bool ShouldSkipMethod(this Type type, MethodBase i)\n        {\n            if (i.IsPrivate)\n                return true;\n            if (i.IsGenericMethod)\n                return true;\n            //EventHandler is currently not supported\n            var param = i.GetParameters();\n            if (i.IsSpecialName)\n            {\n                string[] t = i.Name.Split('_');\n                if (t[0] == \"add\" || t[0] == \"remove\")\n                    return true;\n                if (t[0] == \"get\" || t[0] == \"set\")\n                {\n                    Type[] ts;\n                    if (t[1] == \"Item\")\n                    {\n                        var cnt = t[0] == \"set\" ? param.Length - 1 : param.Length;\n                        ts = new Type[cnt];\n                        for (int j = 0; j < cnt; j++)\n                        {\n                            ts[j] = param[j].ParameterType;\n                        }\n                    }\n                    else\n                        ts = new Type[0];\n                    var prop = type.GetProperty(t[1], ts);\n                    if (prop == null)\n                    {\n                        return true;\n                    }\n                    if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)\n                        return true;\n                }\n            }\n            if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)\n                return true;\n            foreach (var j in param)\n            {\n                if (j.ParameterType.IsPointer)\n                    return true;\n            }\n            return false;\n        }\n\n        internal static void AppendParameters(this ParameterInfo[] param, StringBuilder sb)\n        {\n            bool first = true;\n            foreach (var j in param)\n            {\n                if (first)\n                    first = false;\n                else\n                    sb.Append(\", \");\n                if (j.IsOut && j.ParameterType.IsByRef)\n                    sb.Append(\"out \");\n                else if (j.ParameterType.IsByRef)\n                    sb.Append(\"ref \");\n                sb.Append(j.Name);\n            }\n        }\n\n        internal static string GetRetrieveValueCode(this Type type, string realClsName)\n        {\n            if (type.IsByRef)\n                type = type.GetElementType();\n            if (type.IsPrimitive)\n            {\n                if (type == typeof(int))\n                {\n                    return \"ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(long))\n                {\n                    return \"*(long*)&ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(short))\n                {\n                    return \"(short)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(bool))\n                {\n                    return \"ptr_of_this_method->Value == 1\";\n                }\n                else if (type == typeof(ushort))\n                {\n                    return \"(ushort)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(float))\n                {\n                    return \"*(float*)&ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(double))\n                {\n                    return \"*(double*)&ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(byte))\n                {\n                    return \"(byte)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(sbyte))\n                {\n                    return \"(sbyte)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(uint))\n                {\n                    return \"(uint)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(char))\n                {\n                    return \"(char)ptr_of_this_method->Value\";\n                }\n                else if (type == typeof(ulong))\n                {\n                    return \"*(ulong*)&ptr_of_this_method->Value\";\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                return string.Format(\"({0})typeof({0}).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack))\", realClsName);\n            }\n        }\n\n        internal static void GetRefWriteBackValueCode(this Type type, StringBuilder sb, string paramName)\n        {\n            if (type.IsPrimitive)\n            {\n                if (type == typeof(int))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(long))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Long;\");\n                    sb.Append(\"                        *(long*)&___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(short))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(bool))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName + \" ? 1 : 0;\");\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(ushort))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(float))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Float;\");\n                    sb.Append(\"                        *(float*)&___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(double))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Double;\");\n                    sb.Append(\"                        *(double*)&___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(byte))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(sbyte))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(uint))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = (int)\" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(char))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Integer;\");\n                    sb.Append(\"                        ___dst->Value = (int)\" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else if (type == typeof(ulong))\n                {\n                    sb.AppendLine(\"                        ___dst->ObjectType = ObjectTypes.Long;\");\n                    sb.Append(\"                        *(ulong*)&___dst->Value = \" + paramName);\n                    sb.AppendLine(\";\");\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                if (!type.IsValueType)\n                {\n                    sb.Append(@\"                        object ___obj = \");\n                    sb.Append(paramName);\n                    sb.AppendLine(\";\");\n\n                    sb.AppendLine(@\"                        if (___obj is CrossBindingAdaptorType)\n                            ___obj = ((CrossBindingAdaptorType)___obj).ILInstance;\n                        __mStack[___dst->Value] = ___obj; \");\n                }\n                else\n                {\n                    sb.Append(\"                        __mStack[___dst->Value] = \");\n                    sb.Append(paramName);\n                    sb.AppendLine(\";\");\n                }\n            }\n        }\n\n        internal static void GetReturnValueCode(this Type type, StringBuilder sb)\n        {\n            if (type.IsPrimitive)\n            {\n                if (type == typeof(int))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(long))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Long;\");\n                    sb.AppendLine(\"            *(long*)&__ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(short))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(bool))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method ? 1 : 0;\");\n                }\n                else if (type == typeof(ushort))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(float))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Float;\");\n                    sb.AppendLine(\"            *(float*)&__ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(double))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Double;\");\n                    sb.AppendLine(\"            *(double*)&__ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(byte))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(sbyte))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = result_of_this_method;\");\n                }\n                else if (type == typeof(uint))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = (int)result_of_this_method;\");\n                }\n                else if (type == typeof(char))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Integer;\");\n                    sb.AppendLine(\"            __ret->Value = (int)result_of_this_method;\");\n                }\n                else if (type == typeof(ulong))\n                {\n                    sb.AppendLine(\"            __ret->ObjectType = ObjectTypes.Long;\");\n                    sb.AppendLine(\"            *(ulong*)&__ret->Value = result_of_this_method;\");\n                }\n                else\n                    throw new NotImplementedException();\n                sb.AppendLine(\"            return __ret + 1;\");\n\n            }\n            else\n            {\n                if (!type.IsSealed && type != typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance))\n                {\n                    sb.AppendLine(@\"            object obj_result_of_this_method = result_of_this_method;\n            if(obj_result_of_this_method is CrossBindingAdaptorType)\n            {    \n                return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance);\n            }\");\n                }\n                sb.AppendLine(\"            return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);\");\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/CLRBinding/CommonBindingGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class CommonBindingGenerator\n    {\n        internal static string GenerateMiscRegisterCode(this Type type, string typeClsName, bool defaultCtor, bool newArr)\n        {\n            StringBuilder sb = new StringBuilder();\n\n            if (defaultCtor && !type.IsPrimitive && !type.IsAbstract)\n            {\n                var constructorFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;\n                var hasDefaultConstructor = type.GetConstructor(constructorFlags, null, new Type[0], null) != null;\n\n                if (hasDefaultConstructor || type.IsValueType)\n                {\n                    sb.AppendLine(string.Format(\"            app.RegisterCLRCreateDefaultInstance(type, () => new {0}());\", typeClsName));\n                }\n            }\n\n            if (newArr)\n            {\n                if (!type.IsAbstract || !type.IsSealed)\n                {\n                    sb.AppendLine(string.Format(\"            app.RegisterCLRCreateArrayInstance(type, s => new {0}[s]);\", typeClsName));\n                }\n            }\n\n            return sb.ToString();\n        }\n        internal static string GenerateCommonCode(this Type type, string typeClsName)\n        {\n            if (!type.IsValueType)\n                return \"\";\n            StringBuilder sb = new StringBuilder();\n            if (type.IsPrimitive)\n            {\n                sb.AppendLine(string.Format(\"        static {0} GetInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack)\", typeClsName));\n                sb.AppendLine(\"        {\");\n                if (type.IsPrimitive || type.IsValueType)\n                    sb.AppendLine(\"            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);\");\n                sb.AppendLine(string.Format(\"            {0} instance_of_this_method;\", typeClsName));\n                sb.Append(@\"            switch(ptr_of_this_method->ObjectType)\n            {\n                case ObjectTypes.FieldReference:\n                    {\n                        var instance_of_fieldReference = __mStack[ptr_of_this_method->Value];\n                        if(instance_of_fieldReference is ILTypeInstance)\n                        {\n                            instance_of_this_method = (\");\n                sb.Append(typeClsName);\n                sb.Append(\")\");\n                if(type == typeof(bool))\n                {\n                    sb.Append(\"((int)\");\n                }\n                sb.Append(\"((ILTypeInstance)instance_of_fieldReference)[ptr_of_this_method->ValueLow]\");\n                if (type == typeof(bool))\n                {\n                    sb.Append(\" == 1);\");\n                }\n                else\n                    sb.Append(\";\");\n                sb.Append(@\"\n                        }\n                        else\n                        {\n                            var t = __domain.GetType(instance_of_fieldReference.GetType()) as CLRType;\n                            instance_of_this_method = (\");\n                sb.Append(typeClsName);\n                sb.Append(\")t.GetFieldValue(ptr_of_this_method->ValueLow, instance_of_fieldReference);\");\n                sb.Append(@\"\n                        }\n                    }\n                    break;\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = __domain.GetType(ptr_of_this_method->Value);\n                        if(t is ILType)\n                        {\n                            instance_of_this_method = (\");\n                sb.Append(typeClsName);\n                sb.Append(\")\");\n                if (type == typeof(bool))\n                {\n                    sb.Append(\"((int)\");\n                }\n                sb.Append(\"((ILType)t).StaticInstance[ptr_of_this_method->ValueLow]\");\n                if (type == typeof(bool))\n                {\n                    sb.Append(\" == 1);\");\n                }\n                else\n                    sb.Append(\";\");\n                sb.Append(@\"\n                        }\n                        else\n                        {\n                            instance_of_this_method = (\");\n                sb.Append(typeClsName);\n                sb.Append(@\")((CLRType)t).GetFieldValue(ptr_of_this_method->ValueLow, null);\n                        }\n                    }\n                    break;\n                case ObjectTypes.ArrayReference:\n                    {\n                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as \");\n                sb.Append(typeClsName);\n                sb.AppendLine(@\"[];\n                        instance_of_this_method = instance_of_arrayReference[ptr_of_this_method->ValueLow];                        \n                    }\n                    break;\n                default:\");\n                sb.AppendLine(string.Format(\"                    instance_of_this_method = {0};\", type.GetRetrieveValueCode(typeClsName)));\n                sb.AppendLine(@\"                    break;\n            }\n            return instance_of_this_method;\");\n                sb.AppendLine(\"        }\");\n            }\n            if (!type.IsPrimitive && !type.IsAbstract)\n            {\n                sb.AppendLine(string.Format(\"        static void WriteBackInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack, ref {0} instance_of_this_method)\", typeClsName));\n                sb.AppendLine(\"        {\");\n                sb.AppendLine(@\"            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);\n            switch(ptr_of_this_method->ObjectType)\n            {\n                case ObjectTypes.Object:\n                    {\n                        __mStack[ptr_of_this_method->Value] = instance_of_this_method;\");\n                sb.Append(@\"                    }\n                    break;\n                case ObjectTypes.FieldReference:\n                    {\n                        var ___obj = __mStack[ptr_of_this_method->Value];\n                        if(___obj is ILTypeInstance)\n                        {\n                            ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method\");\n                sb.Append(@\";\n                        }\n                        else\n                        {\n                            var t = __domain.GetType(___obj.GetType()) as CLRType;\n                            t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, instance_of_this_method\");\n                sb.Append(@\");\n                        }\n                    }\n                    break;\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = __domain.GetType(ptr_of_this_method->Value);\n                        if(t is ILType)\n                        {\n                            ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method\");\n                sb.Append(@\";\n                        }\n                        else\n                        {\n                            ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, instance_of_this_method\");\n                sb.Append(@\");\n                        }\n                    }\n                    break;\n                 case ObjectTypes.ArrayReference:\n                    {\n                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as \");\n                sb.Append(typeClsName);\n                sb.AppendLine(@\"[];\n                        instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method;\n                    }\n                    break;\n            }\");\n                sb.AppendLine(@\"        }\");\n            }\n            return sb.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/CLRBinding/ConstructorBindingGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class ConstructorBindingGenerator\n    {\n        internal static string GenerateConstructorRegisterCode(this Type type, ConstructorInfo[] methods, HashSet<MethodBase> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n            int idx = 0;\n            foreach (var i in methods)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipMethod(i))\n                    continue;\n                var param = i.GetParameters();\n                StringBuilder sb2 = new StringBuilder();\n                sb2.Append(\"{\");\n                bool first = true;\n                foreach (var j in param)\n                {\n                    if (first)\n                        first = false;\n                    else\n                        sb2.Append(\", \");\n                    sb2.Append(\"typeof(\");\n                    string tmp, clsName;\n                    bool isByRef;\n                    j.ParameterType.GetClassName(out tmp, out clsName, out isByRef);\n                    sb2.Append(clsName);\n                    sb2.Append(\")\");\n                    if (isByRef)\n                        sb2.Append(\".MakeByRefType()\");\n                }\n                sb2.Append(\"}\");\n                sb.AppendLine(string.Format(\"            args = new Type[]{0};\", sb2));\n                sb.AppendLine(\"            method = type.GetConstructor(flag, null, args, null);\");\n                sb.AppendLine(string.Format(\"            app.RegisterCLRMethodRedirection(method, Ctor_{0});\",idx));\n\n                idx++;\n            }\n            return sb.ToString();\n        }\n\n        internal static string GenerateConstructorWraperCode(this Type type, ConstructorInfo[] methods, string typeClsName, HashSet<MethodBase> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n\n            int idx = 0;\n            foreach (var i in methods)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipMethod(i) || i.IsStatic)\n                    continue;\n                var param = i.GetParameters();\n                int paramCnt = param.Length;\n                sb.AppendLine(string.Format(\"        static StackObject* Ctor_{0}(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\", idx));\n                sb.AppendLine(\"        {\");\n                sb.AppendLine(\"            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\");\n                sb.AppendLine(\"            StackObject* ptr_of_this_method;\");\n                sb.AppendLine(string.Format(\"            StackObject* __ret = ILIntepreter.Minus(__esp, {0});\", paramCnt));\n                for (int j = param.Length; j > 0; j--)\n                {\n                    var p = param[j - 1];\n                    sb.AppendLine(string.Format(\"            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});\", param.Length - j + 1));\n                    string tmp, clsName;\n                    bool isByRef;\n                    p.ParameterType.GetClassName(out tmp, out clsName, out isByRef);\n                    if (isByRef)\n                        sb.AppendLine(\"            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);\");\n                    sb.AppendLine(string.Format(\"            {0} {1} = {2};\", clsName, p.Name, p.ParameterType.GetRetrieveValueCode(clsName)));\n                    if (!isByRef && !p.ParameterType.IsPrimitive)\n                        sb.AppendLine(\"            __intp.Free(ptr_of_this_method);\");\n                }\n                sb.AppendLine();\n                sb.Append(\"            var result_of_this_method = \");\n                {\n                    string tmp, clsName;\n                    bool isByRef;\n                    type.GetClassName(out tmp, out clsName, out isByRef);\n                    sb.Append(string.Format(\"new {0}(\", clsName));\n                    param.AppendParameters(sb);\n                    sb.AppendLine(\");\");\n\n                }\n                sb.AppendLine();\n                if (type.IsValueType)\n                {\n                    sb.AppendLine(@\"            if(!isNewObj)\n            {\n                __ret--;\n                WriteBackInstance(__domain, __ret, __mStack, ref result_of_this_method);\n                return __ret;\n            }\");\n                }\n\n                //Ref/Out\n                for (int j = param.Length; j > 0; j--)\n                {\n                    var p = param[j - 1];\n                    if (!p.ParameterType.IsByRef)\n                        continue;\n                    string tmp, clsName;\n                    bool isByRef;\n                    p.ParameterType.GetElementType().GetClassName(out tmp, out clsName, out isByRef);\n                    sb.AppendLine(string.Format(\"            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});\", param.Length - j + 1));\n                    sb.AppendLine(@\"            switch(ptr_of_this_method->ObjectType)\n            {\n                case ObjectTypes.StackObjectReference:\n                    {\n                        var ___dst = *(StackObject**)&ptr_of_this_method->Value;\");\n                    p.ParameterType.GetElementType().GetRefWriteBackValueCode(sb, p.Name);\n                    sb.Append(@\"                    }\n                    break;\n                case ObjectTypes.FieldReference:\n                    {\n                        var ___obj = __mStack[ptr_of_this_method->Value];\n                        if(___obj is ILTypeInstance)\n                        {\n                            ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.Append(@\";\n                        }\n                        else\n                        {\n                            var t = __domain.GetType(___obj.GetType()) as CLRType;\n                            t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, \");\n                    sb.Append(p.Name);\n                    sb.Append(@\");\n                        }\n                    }\n                    break;\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = __domain.GetType(ptr_of_this_method->Value);\n                        if(t is ILType)\n                        {\n                            ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.Append(@\";\n                        }\n                        else\n                        {\n                            ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, \");\n                    sb.Append(p.Name);\n                    sb.Append(@\");\n                        }\n                    }\n                    break;\n                 case ObjectTypes.ArrayReference:\n                    {\n                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as \");\n                    sb.Append(clsName);\n                    sb.Append(@\"[];\n                        instance_of_arrayReference[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.AppendLine(@\";\n                    }\n                    break;\n            }\");\n                    sb.AppendLine();\n                }\n                sb.AppendLine(\"            return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);\");\n\n                sb.AppendLine(\"        }\");\n                sb.AppendLine();\n                idx++;\n            }\n\n            return sb.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/CLRBinding/FieldBindingGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class FieldBindingGenerator\n    {\n        internal static string GenerateFieldRegisterCode(this Type type, FieldInfo[] fields, HashSet<FieldInfo> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n            int idx = 0;\n            foreach (var i in fields)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipField(i))\n                    continue;\n                if (i.IsSpecialName)\n                    continue;\n\n                sb.AppendLine(string.Format(\"            field = type.GetField(\\\"{0}\\\", flag);\", i.Name));\n                sb.AppendLine(string.Format(\"            app.RegisterCLRFieldGetter(field, get_{0}_{1});\", i.Name, idx));\n                if (!i.IsInitOnly && !i.IsLiteral)\n                {\n                    sb.AppendLine(string.Format(\"            app.RegisterCLRFieldSetter(field, set_{0}_{1});\", i.Name, idx));\n                }\n\n                idx++;\n            }\n            return sb.ToString();\n        }\n\n        internal static string GenerateFieldWraperCode(this Type type, FieldInfo[] fields, string typeClsName, HashSet<FieldInfo> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n\n            int idx = 0;\n            foreach (var i in fields)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipField(i))\n                    continue;\n                sb.AppendLine(string.Format(\"        static object get_{0}_{1}(ref object o)\", i.Name, idx));\n                sb.AppendLine(\"        {\");\n                if (i.IsStatic)\n                {\n                    sb.AppendLine(string.Format(\"            return {0}.{1};\", typeClsName, i.Name));\n                }\n                else\n                {\n                    sb.AppendLine(string.Format(\"            return (({0})o).{1};\", typeClsName, i.Name));\n                }\n                sb.AppendLine(\"        }\");\n\n                if (!i.IsInitOnly && !i.IsLiteral)\n                {\n                    sb.AppendLine(string.Format(\"        static void set_{0}_{1}(ref object o, object v)\", i.Name, idx));\n                    sb.AppendLine(\"        {\");\n                    string clsName, realClsName;\n                    bool isByRef;\n                    i.FieldType.GetClassName(out clsName, out realClsName, out isByRef);\n                    if (i.IsStatic)\n                    {\n                        sb.AppendLine(string.Format(\"            {0}.{1} = ({2})v;\", typeClsName, i.Name, realClsName));\n                    }\n                    else\n                    {\n                        if (CheckCanPinn(type))\n                        {\n                            sb.AppendLine(\"            var h = GCHandle.Alloc(o, GCHandleType.Pinned);\");\n                            sb.AppendLine(string.Format(\"            {0}* p = ({0} *)(void *)h.AddrOfPinnedObject();\", typeClsName));\n                            sb.AppendLine(string.Format(\"            p->{0} = ({1})v;\", i.Name, realClsName));\n                            sb.AppendLine(\"            h.Free();\");\n                        }\n                        else\n                        {\n                            sb.AppendLine(string.Format(\"            (({0})o).{1} = ({2})v;\", typeClsName, i.Name, realClsName));\n                        }\n                    }\n                    sb.AppendLine(\"        }\");\n                }\n                idx++;\n            }\n\n            return sb.ToString();\n        }\n\n        internal static bool CheckCanPinn(this Type type)\n        {\n            if (type.IsValueType)\n            {\n                FieldInfo[] fi = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n                bool res = true;\n                foreach(var i in fi)\n                {\n                    if(!i.FieldType.IsPrimitive)\n                    {\n                        res = false;\n                        break;\n                    }\n                }\n\n                return res;\n            }\n            else\n                return false;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/CLRBinding/MethodBindingGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class MethodBindingGenerator\n    {\n        internal static string GenerateMethodRegisterCode(this Type type, MethodInfo[] methods, HashSet<MethodBase> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n            int idx = 0;\n            foreach (var i in methods)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipMethod(i))\n                    continue;\n                bool isProperty = i.IsSpecialName;\n                var param = i.GetParameters();\n                StringBuilder sb2 = new StringBuilder();\n                sb2.Append(\"{\");\n                bool first = true;\n                foreach (var j in param)\n                {\n                    if (first)\n                        first = false;\n                    else\n                        sb2.Append(\", \");\n                    sb2.Append(\"typeof(\");\n                    string tmp, clsName;\n                    bool isByRef;\n                    j.ParameterType.GetClassName(out tmp, out clsName, out isByRef);\n                    sb2.Append(clsName);\n                    sb2.Append(\")\");\n                    if (isByRef)\n                        sb2.Append(\".MakeByRefType()\");\n                }\n                sb2.Append(\"}\");\n                sb.AppendLine(string.Format(\"            args = new Type[]{0};\", sb2));\n                sb.AppendLine(string.Format(\"            method = type.GetMethod(\\\"{0}\\\", flag, null, args, null);\", i.Name));\n                sb.AppendLine(string.Format(\"            app.RegisterCLRMethodRedirection(method, {0}_{1});\", i.Name, idx));\n\n                idx++;\n            }\n            return sb.ToString();\n        }\n\n        internal static string GenerateMethodWraperCode(this Type type, MethodInfo[] methods, string typeClsName, HashSet<MethodBase> excludes)\n        {\n            StringBuilder sb = new StringBuilder();\n\n            int idx = 0;\n            foreach (var i in methods)\n            {\n                if (excludes != null && excludes.Contains(i))\n                    continue;\n                if (type.ShouldSkipMethod(i))\n                    continue;\n                bool isProperty = i.IsSpecialName;\n                var param = i.GetParameters();\n                int paramCnt = param.Length;\n                if (!i.IsStatic)\n                    paramCnt++;\n                sb.AppendLine(string.Format(\"        static StackObject* {0}_{1}(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)\", i.Name, idx));\n                sb.AppendLine(\"        {\");\n                sb.AppendLine(\"            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;\");\n                sb.AppendLine(\"            StackObject* ptr_of_this_method;\");\n                sb.AppendLine(string.Format(\"            StackObject* __ret = ILIntepreter.Minus(__esp, {0});\", paramCnt));\n                for (int j = param.Length; j > 0; j--)\n                {\n                    var p = param[j - 1];\n                    sb.AppendLine(string.Format(\"            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});\", param.Length - j + 1));\n                    string tmp, clsName;\n                    bool isByRef;\n                    p.ParameterType.GetClassName(out tmp, out clsName, out isByRef);\n                    if (isByRef)\n                        sb.AppendLine(\"            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);\");\n                    sb.AppendLine(string.Format(\"            {0} {1} = {2};\", clsName, p.Name, p.ParameterType.GetRetrieveValueCode(clsName)));\n                    if (!isByRef && !p.ParameterType.IsPrimitive)\n                        sb.AppendLine(\"            __intp.Free(ptr_of_this_method);\");\n                }\n                if (!i.IsStatic)\n                {\n                    sb.AppendLine(string.Format(\"            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});\", paramCnt));\n                    if (type.IsPrimitive)\n                        sb.AppendLine(string.Format(\"            {0} instance_of_this_method = GetInstance(__domain, ptr_of_this_method, __mStack);\", typeClsName));\n                    else\n                    {\n                        if (type.IsValueType)\n                            sb.AppendLine(\"            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);\");\n                        sb.AppendLine(string.Format(\"            {0} instance_of_this_method;\", typeClsName));\n                        sb.AppendLine(string.Format(\"            instance_of_this_method = {0};\", type.GetRetrieveValueCode(typeClsName)));\n                        if (!type.IsValueType)\n                            sb.AppendLine(\"            __intp.Free(ptr_of_this_method);\");\n                    }\n                }\n                sb.AppendLine();\n                if (i.ReturnType != typeof(void))\n                {\n                    sb.Append(\"            var result_of_this_method = \");\n                }\n                else\n                    sb.Append(\"            \");\n                if (i.IsStatic)\n                {\n                    if (isProperty)\n                    {\n                        string[] t = i.Name.Split('_');\n                        string propType = t[0];\n\n                        if (propType == \"get\")\n                        {\n                            bool isIndexer = param.Length > 0;\n                            if (isIndexer)\n                            {\n                                sb.AppendLine(string.Format(\"{1}[{0}];\", param[0].Name, typeClsName));\n                            }\n                            else\n                                sb.AppendLine(string.Format(\"{1}.{0};\", t[1], typeClsName));\n                        }\n                        else if (propType == \"set\")\n                        {\n                            bool isIndexer = param.Length > 1;\n                            if (isIndexer)\n                            {\n                                sb.AppendLine(string.Format(\"{2}[{0}] = {1};\", param[0].Name, param[1].Name, typeClsName));\n                            }\n                            else\n                                sb.AppendLine(string.Format(\"{2}.{0} = {1};\", t[1], param[0].Name, typeClsName));\n                        }\n                        else if (propType == \"op\")\n                        {\n                            switch (t[1])\n                            {\n                                case \"Equality\":\n                                    sb.AppendLine(string.Format(\"{0} == {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"Inequality\":\n                                    sb.AppendLine(string.Format(\"{0} != {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"Addition\":\n                                    sb.AppendLine(string.Format(\"{0} + {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"Subtraction\":\n                                    sb.AppendLine(string.Format(\"{0} - {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"Multiply\":\n                                    sb.AppendLine(string.Format(\"{0} * {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"Division\":\n                                    sb.AppendLine(string.Format(\"{0} / {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"GreaterThan\":\n                                    sb.AppendLine(string.Format(\"{0} > {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"GreaterThanOrEqual\":\n                                    sb.AppendLine(string.Format(\"{0} >= {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"LessThan\":\n                                    sb.AppendLine(string.Format(\"{0} < {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"LessThanOrEqual\":\n                                    sb.AppendLine(string.Format(\"{0} <= {1};\", param[0].Name, param[1].Name));\n                                    break;\n                                case \"UnaryNegation\":\n                                    sb.AppendLine(string.Format(\"-{0};\", param[0].Name));\n                                    break;\n                                case \"Implicit\":\n                                case \"Explicit\":\n                                    {\n                                        string tmp, clsName;\n                                        bool isByRef;\n                                        i.ReturnType.GetClassName(out tmp, out clsName, out isByRef);\n                                        sb.AppendLine(string.Format(\"({1}){0};\", param[0].Name, clsName));\n                                    }\n                                    break;\n                                default:\n                                    throw new NotImplementedException(i.Name);\n                            }\n                        }\n                        else\n                            throw new NotImplementedException();\n                    }\n                    else\n                    {\n                        sb.Append(string.Format(\"{0}.{1}(\", typeClsName, i.Name));\n                        param.AppendParameters(sb);\n                        sb.AppendLine(\");\");\n                    }\n                }\n                else\n                {\n                    if (isProperty)\n                    {\n                        string[] t = i.Name.Split('_');\n                        string propType = t[0];\n\n                        if (propType == \"get\")\n                        {\n                            bool isIndexer = param.Length > 0;\n                            if (isIndexer)\n                            {\n                                sb.AppendLine(string.Format(\"instance_of_this_method[{0}];\", param[0].Name));\n                            }\n                            else\n                                sb.AppendLine(string.Format(\"instance_of_this_method.{0};\", t[1]));\n                        }\n                        else if (propType == \"set\")\n                        {\n                            bool isIndexer = param.Length > 1;\n                            if (isIndexer)\n                            {\n                                sb.AppendLine(string.Format(\"instance_of_this_method[{0}] = {1};\", param[0].Name, param[1].Name));\n                            }\n                            else\n                                sb.AppendLine(string.Format(\"instance_of_this_method.{0} = {1};\", t[1], param[0].Name));\n                        }\n                        else\n                            throw new NotImplementedException();\n                    }\n                    else\n                    {\n                        sb.Append(string.Format(\"instance_of_this_method.{0}(\", i.Name));\n                        param.AppendParameters(sb);\n                        sb.AppendLine(\");\");\n                    }\n                }\n                sb.AppendLine();\n\n\n                if (!i.IsStatic && type.IsValueType && !type.IsPrimitive)//need to write back value type instance\n                {\n                    sb.AppendLine(\"            WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);\");\n                    sb.AppendLine();\n                }\n                //Ref/Out\n                for (int j = param.Length; j > 0; j--)\n                {\n                    var p = param[j - 1];\n                    if (!p.ParameterType.IsByRef)\n                        continue;\n                    string tmp, clsName;\n                    bool isByRef;\n                    p.ParameterType.GetElementType().GetClassName(out tmp, out clsName, out isByRef);\n                    sb.AppendLine(string.Format(\"            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});\", param.Length - j + 1));\n                    sb.AppendLine(@\"            switch(ptr_of_this_method->ObjectType)\n            {\n                case ObjectTypes.StackObjectReference:\n                    {\n                        var ___dst = *(StackObject**)&ptr_of_this_method->Value;\");\n                    p.ParameterType.GetElementType().GetRefWriteBackValueCode(sb, p.Name);\n                    sb.Append(@\"                    }\n                    break;\n                case ObjectTypes.FieldReference:\n                    {\n                        var ___obj = __mStack[ptr_of_this_method->Value];\n                        if(___obj is ILTypeInstance)\n                        {\n                            ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.Append(@\";\n                        }\n                        else\n                        {\n                            var t = __domain.GetType(___obj.GetType()) as CLRType;\n                            t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, \");\n                    sb.Append(p.Name);\n                    sb.Append(@\");\n                        }\n                    }\n                    break;\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = __domain.GetType(ptr_of_this_method->Value);\n                        if(t is ILType)\n                        {\n                            ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.Append(@\";\n                        }\n                        else\n                        {\n                            ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, \");\n                    sb.Append(p.Name);\n                    sb.Append(@\");\n                        }\n                    }\n                    break;\n                 case ObjectTypes.ArrayReference:\n                    {\n                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as \");\n                    sb.Append(clsName);\n                    sb.Append(@\"[];\n                        instance_of_arrayReference[ptr_of_this_method->ValueLow] = \");\n                    sb.Append(p.Name);\n                    sb.AppendLine(@\";\n                    }\n                    break;\n            }\");\n                    sb.AppendLine();\n                }\n                if (i.ReturnType != typeof(void))\n                {\n                    i.ReturnType.GetReturnValueCode(sb);\n                }\n                else\n                    sb.AppendLine(\"            return __ret;\");\n                sb.AppendLine(\"        }\");\n                sb.AppendLine();\n                idx++;\n            }\n\n            return sb.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/CLRBinding/ValueTypeBindingGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.CLRBinding\n{\n    static class ValueTypeBindingGenerator\n    {\n        internal static string GenerateValueTypeRegisterCode(this Type type, string typeClsName)\n        {\n            StringBuilder sb = new StringBuilder();\n\n            if (type.IsValueType && !type.IsPrimitive && !type.IsEnum)\n            {\n                sb.AppendLine(\"            app.RegisterCLRMemberwiseClone(type, PerformMemberwiseClone);\");\n            }\n            return sb.ToString();\n        }\n\n        internal static string GenerateCloneWraperCode(this Type type, FieldInfo[] fields, string typeClsName)\n        {\n            if (!type.IsValueType || type.IsPrimitive) return string.Empty;\n            StringBuilder sb = new StringBuilder();\n\n            sb.AppendLine(\"        static object PerformMemberwiseClone(ref object o)\");\n            sb.AppendLine(\"        {\");\n            sb.AppendLine(string.Format(\"            return new {0}\", typeClsName));\n            sb.AppendLine(\"            {\");\n\n            foreach (var i in fields)\n            {\n                if (i.IsStatic || i.IsInitOnly || i.IsLiteral) continue;\n                sb.AppendLine(string.Format(\"                {0} = (({1}) o).{0},\", i.Name, typeClsName));\n            }\n\n            sb.AppendLine(\"            };\");\n            sb.AppendLine(\"        }\");\n\n            return sb.ToString();\n\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/BreakPointContext.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nnamespace ILRuntime.Runtime.Debugger\n{\n    unsafe class BreakPointContext\n    {\n        public ILIntepreter Interpreter { get; set; }\n        public Exception Exception { get; set; }\n\n        public string DumpContext()\n        {\n            /*StringBuilder sb = new StringBuilder();\n            if (Exception != null)\n                sb.AppendLine(Exception.Message);\n            StackFrame[] frames = Interpreter.Stack.Frames.ToArray();\n            StackFrame topFrame = frames[0];\n            var m = topFrame.Method;\n            if (m.HasThis)\n            {\n                sb.AppendLine(\"this:\");\n                sb.AppendLine(DebugService.Instance.GetThisInfo(Interpreter));\n            }\n            sb.AppendLine(\"->\" + topFrame.Method.Definition.Body.Instructions[topFrame.Address.Value]);\n            sb.AppendLine(\"Local Variables:\");\n            sb.AppendLine(DebugService.Instance.GetLocalVariableInfo(Interpreter));\n\n            sb.Append(DebugService.Instance.GetStackTrance(Interpreter));\n            return sb.ToString();*/\n            return null;\n        }\n\n        string GetStackObjectValue(StackObject val, IList<object> mStack)\n        {\n            string v;\n            switch (val.ObjectType)\n            {\n                case ObjectTypes.Null:\n                    v = \"null\";\n                    break;\n                case ObjectTypes.Integer:\n                    v = val.Value.ToString();\n                    break;\n                case ObjectTypes.Object:\n                    {\n                        object obj = Interpreter.Stack.ManagedStack[val.Value];\n                        v = obj.ToString();\n                    }\n                    break;\n                default:\n                    v = \"Unknown type\";\n                    break;\n            }\n            return v;\n        }        \n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/BreakpointInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    class BreakpointInfo\n    {\n        public int BreakpointHashCode { get; set; }\n        public int MethodHashCode { get; set; }\n        public int StartLine { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/DebugMessageType.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public enum DebugMessageType\n    {\n        CSAttach,\n        SCAttachResult,\n        CSBindBreakpoint,\n        SCBindBreakpointResult,\n        SCModuleLoaded,\n        SCThreadStarted,\n        SCThreadEnded,\n        SCBreakpointHit,\n        CSDeleteBreakpoint,\n        CSExecute,\n        CSStep,\n        SCStepComplete,\n        CSResolveVariable,\n        SCResolveVariableResult\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/DebugService.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\n\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.CLR.Utils;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public class DebugService\n    {\n        BreakPointContext curBreakpoint;\n        DebuggerServer server;\n        Runtime.Enviorment.AppDomain domain;\n        Dictionary<int, LinkedList<BreakpointInfo>> activeBreakpoints = new Dictionary<int, LinkedList<BreakpointInfo>>();\n        Dictionary<int, BreakpointInfo> breakpointMapping = new Dictionary<int, BreakpointInfo>();\n        AutoResetEvent evt = new AutoResetEvent(false);\n        \n        public Action<string> OnBreakPoint;\n\n        public Enviorment.AppDomain AppDomain { get { return domain; } }\n\n        public AutoResetEvent BlockEvent { get { return evt; } }\n\n        public bool IsDebuggerAttached\n        {\n            get\n            {\n#if DEBUG\n                return (server != null && server.IsAttached);\n#else\n                return false;\n#endif\n            }\n        }\n\n        public DebugService(Runtime.Enviorment.AppDomain domain)\n        {\n            this.domain = domain;\n        }\n\n        /// <summary>\n        /// Start Debugger Server\n        /// </summary>\n        /// <param name=\"port\">Port to listen on</param>\n        public void StartDebugService(int port)\n        {\n#if DEBUG\n            server = new Debugger.DebuggerServer(this);\n            server.Port = port;\n            server.Start();\n#endif\n        }\n\n        /// <summary>\n        /// Stop Debugger Server\n        /// </summary>\n        public void StopDebugService()\n        {\n#if DEBUG\n            server.Stop();\n            server = null;\n#endif\n        }\n\n        /// <summary>\n        /// 中断运行\n        /// </summary>\n        /// <param name=\"intpreter\"></param>\n        /// <param name=\"ex\"></param>\n        /// <returns>如果挂的有调试器则返回true</returns>\n        internal bool Break(ILIntepreter intpreter, Exception ex = null)\n        {\n            BreakPointContext ctx = new BreakPointContext();\n            ctx.Interpreter = intpreter;\n            ctx.Exception = ex;\n\n            curBreakpoint = ctx;\n\n            if (OnBreakPoint != null)\n            {\n                OnBreakPoint(ctx.DumpContext());\n                return true;\n            }\n            return false;\n        }\n\n        public string GetStackTrance(ILIntepreter intepreper)\n        {\n            StringBuilder sb = new StringBuilder();\n            ILRuntime.CLR.Method.ILMethod m;\n            StackFrame[] frames = intepreper.Stack.Frames.ToArray();\n            Mono.Cecil.Cil.Instruction ins = null;\n            if (frames[0].Address != null)\n            {\n                ins = frames[0].Method.Definition.Body.Instructions[frames[0].Address.Value];\n                sb.AppendLine(ins.ToString());\n            }\n            for (int i = 0; i < frames.Length; i++)\n            {\n                var f = frames[i];\n                m = f.Method;\n                string document = \"\";\n                if (f.Address != null)\n                {\n                    ins = m.Definition.Body.Instructions[f.Address.Value];\n                    var seq = FindSequencePoint(ins);\n                    if (seq != null)\n                    {\n                        document = string.Format(\"{0}:Line {1}\", seq.Document.Url, seq.StartLine);\n                    }\n                }\n                sb.AppendFormat(\"at {0} {1}\\r\\n\", m, document);\n            }\n\n            return sb.ToString();\n        }\n\n        public unsafe string GetThisInfo(ILIntepreter intepreter)\n        {\n            var topFrame = intepreter.Stack.Frames.Peek();\n            var arg = Minus(topFrame.LocalVarPointer, topFrame.Method.ParameterCount);\n            if (topFrame.Method.HasThis)\n                arg--;\n            if (arg->ObjectType == ObjectTypes.StackObjectReference)\n            {\n                arg = *(StackObject**)&arg->Value;\n            }\n            ILTypeInstance instance = arg->ObjectType != ObjectTypes.Null ? intepreter.Stack.ManagedStack[arg->Value] as ILTypeInstance : null;\n            if (instance == null)\n                return \"null\";\n            var fields = instance.Type.TypeDefinition.Fields;\n            int idx = 0;\n            StringBuilder sb = new StringBuilder();\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var f = fields[i];\n                if (f.IsStatic)\n                    continue;\n                var field = instance.Fields[idx];\n                var v = StackObject.ToObject(&field, intepreter.AppDomain, instance.ManagedObjects);\n                if (v == null)\n                    v = \"null\";\n                string name = f.Name;\n                sb.AppendFormat(\"{0} {1} = {2}\", f.FieldType.Name, name, v);\n                if ((idx % 3 == 0 && idx != 0) || idx == instance.Fields.Length - 1)\n                    sb.AppendLine();\n                else\n                    sb.Append(\", \");\n                idx++;\n            }\n            return sb.ToString();\n        }\n\n        public unsafe string GetLocalVariableInfo(ILIntepreter intepreter)\n        {\n            StackFrame topFrame = intepreter.Stack.Frames.Peek();\n            var m = topFrame.Method;\n            StringBuilder sb = new StringBuilder();\n            for (int i = 0; i < m.LocalVariableCount; i++)\n            {\n                var lv = m.Definition.Body.Variables[i];\n                var val = Add(topFrame.LocalVarPointer, i);\n                var v = StackObject.ToObject(val, intepreter.AppDomain, intepreter.Stack.ManagedStack);\n                if (v == null)\n                    v = \"null\";\n                string name = string.IsNullOrEmpty(lv.Name) ? \"v\" + lv.Index : lv.Name;\n                sb.AppendFormat(\"{0} {1} = {2}\", lv.VariableType.Name, name, v);\n                if ((i % 3 == 0 && i != 0) || i == m.LocalVariableCount - 1)\n                    sb.AppendLine();\n                else\n                    sb.Append(\", \");\n            }\n            return sb.ToString();\n        }\n\n        internal static Mono.Cecil.Cil.SequencePoint FindSequencePoint(Mono.Cecil.Cil.Instruction ins)\n        {\n            Mono.Cecil.Cil.Instruction cur = ins;\n            while (cur.SequencePoint == null && cur.Previous != null)\n                cur = cur.Previous;\n\n            return cur.SequencePoint;\n        }\n\n        unsafe StackObject* Add(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a + sizeof(StackObject) * b);\n        }\n\n        unsafe StackObject* Minus(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a - sizeof(StackObject) * b);\n        }\n\n        internal void NotifyModuleLoaded(string moduleName)\n        {\n            if (server != null && server.IsAttached)\n                server.NotifyModuleLoaded(moduleName);\n        }\n\n        internal void SetBreakPoint(int methodHash, int bpHash, int startLine)\n        {\n            lock (activeBreakpoints)\n            {\n                LinkedList<BreakpointInfo> lst;\n                if(!activeBreakpoints.TryGetValue(methodHash, out lst))\n                {\n                    lst = new LinkedList<Debugger.BreakpointInfo>();\n                    activeBreakpoints[methodHash] = lst;\n                }\n\n                BreakpointInfo bpInfo = new BreakpointInfo();\n                bpInfo.BreakpointHashCode = bpHash;\n                bpInfo.MethodHashCode = methodHash;\n                bpInfo.StartLine = startLine;\n\n                lst.AddLast(bpInfo);\n                breakpointMapping[bpHash] = bpInfo;\n            }\n        }\n\n        internal void DeleteBreakpoint(int bpHash)\n        {\n            lock (activeBreakpoints)\n            {\n                BreakpointInfo bpInfo;\n                if (breakpointMapping.TryGetValue(bpHash, out bpInfo))\n                {\n                    LinkedList<BreakpointInfo> lst;\n                    if(activeBreakpoints.TryGetValue(bpInfo.MethodHashCode, out lst))\n                    {\n                        lst.Remove(bpInfo);                        \n                    }\n                    breakpointMapping.Remove(bpHash);\n                }\n            }\n        }\n\n        internal void ExecuteThread(int threadHash)\n        {\n            lock (AppDomain.FreeIntepreters)\n            {\n                foreach(var i in AppDomain.Intepreters)\n                {\n                    //We should resume all threads on execute\n                    i.Value.ClearDebugState();\n                    i.Value.Resume();\n                }\n            }\n        }\n\n        internal unsafe void StepThread(int threadHash, StepTypes type)\n        {\n            lock (AppDomain.FreeIntepreters)\n            {\n                ILIntepreter intp;\n                if(AppDomain.Intepreters.TryGetValue(threadHash, out intp))\n                {\n                    intp.ClearDebugState();\n                    intp.CurrentStepType = type;\n                    intp.LastStepFrameBase = intp.Stack.Frames.Count > 0 ? intp.Stack.Frames.Peek().BasePointer : (StackObject*)0;\n                    intp.LastStepInstructionIndex = intp.Stack.Frames.Count > 0 ? intp.Stack.Frames.Peek().Address.Value : 0;\n\n                    intp.Resume();\n                }\n            }\n        }\n\n        unsafe internal void CheckShouldBreak(ILMethod method, ILIntepreter intp, int ip)\n        {\n            if (server != null && server.IsAttached)\n            {\n                int methodHash = method.GetHashCode();\n                lock (activeBreakpoints)\n                {\n                    LinkedList<BreakpointInfo> lst;\n                    bool bpHit = false;\n\n                    if (activeBreakpoints.TryGetValue(methodHash, out lst))\n                    {\n                        var sp = method.Definition.Body.Instructions[ip].SequencePoint;\n                        if (sp != null)\n                        {\n                            foreach (var i in lst)\n                            {\n                                if ((i.StartLine + 1) == sp.StartLine)\n                                {\n                                    DoBreak(intp, i.BreakpointHashCode, false);\n                                    bpHit = true;\n                                    break;\n                                }\n                            }\n                        }\n                    }\n\n                    if (!bpHit)\n                    {\n                        var sp = method.Definition.Body.Instructions[ip].SequencePoint;\n                        if (sp != null && IsSequenceValid(sp))\n                        {                            \n                            switch (intp.CurrentStepType)\n                            {\n                                case StepTypes.Into:\n                                    DoBreak(intp, 0, true);\n                                    break;\n                                case StepTypes.Over:\n                                    if (intp.Stack.Frames.Peek().BasePointer <= intp.LastStepFrameBase && ip != intp.LastStepInstructionIndex)\n                                    {\n                                        DoBreak(intp, 0, true);\n                                    }\n                                    break;\n                                case StepTypes.Out:\n                                    {\n                                        if (intp.Stack.Frames.Count > 0 && intp.Stack.Frames.Peek().BasePointer < intp.LastStepFrameBase)\n                                        {\n                                            DoBreak(intp, 0, true);\n                                        }\n                                    }\n                                    break;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        bool IsSequenceValid(Mono.Cecil.Cil.SequencePoint sp)\n        {\n            return sp.StartLine != sp.EndLine || sp.StartColumn != sp.EndColumn;\n        }\n\n        void DoBreak(ILIntepreter intp, int bpHash, bool isStep)\n        {\n            KeyValuePair<int, StackFrameInfo[]>[] frames = new KeyValuePair<int, StackFrameInfo[]>[AppDomain.Intepreters.Count];\n            frames[0] = new KeyValuePair<int, StackFrameInfo[]>(intp.GetHashCode(), GetStackFrameInfo(intp));\n            int idx = 1;\n            foreach (var j in AppDomain.Intepreters)\n            {\n                if (j.Value != intp)\n                {\n                    j.Value.ShouldBreak = true;\n                    frames[idx++] = new KeyValuePair<int, Debugger.StackFrameInfo[]>(j.Value.GetHashCode(), GetStackFrameInfo(j.Value));\n                }\n            }\n            if (!isStep)\n                server.SendSCBreakpointHit(intp.GetHashCode(), bpHash, frames);\n            else\n                server.SendSCStepComplete(intp.GetHashCode(), frames);\n            //Breakpoint hit\n            intp.Break();\n        }\n\n        unsafe StackFrameInfo[] GetStackFrameInfo(ILIntepreter intp)\n        {\n            StackFrame[] frames = intp.Stack.Frames.ToArray();\n            Mono.Cecil.Cil.Instruction ins = null;\n            ILMethod m;\n            StackFrameInfo[] frameInfos = new StackFrameInfo[frames.Length];\n\n            for (int j = 0; j < frames.Length; j++)\n            {\n                StackFrameInfo info = new Debugger.StackFrameInfo();\n                var f = frames[j];\n                m = f.Method;\n                info.MethodName = m.ToString();\n\n                if (f.Address != null)\n                {\n                    ins = m.Definition.Body.Instructions[f.Address.Value];\n                    var seq = FindSequencePoint(ins);\n                    if (seq != null)\n                    {\n                        info.DocumentName = seq.Document.Url;\n                        info.StartLine = seq.StartLine - 1;\n                        info.StartColumn = seq.StartColumn - 1;\n                        info.EndLine = seq.EndLine - 1;\n                        info.EndColumn = seq.EndColumn - 1;\n                    }\n                }\n                StackFrame topFrame = f;\n                m = topFrame.Method;\n                int argumentCount = m.ParameterCount;\n                if (m.HasThis)\n                    argumentCount++;\n                info.LocalVariables = new VariableInfo[argumentCount + m.LocalVariableCount];\n                for(int i = 0; i < argumentCount; i++)\n                {\n                    int argIdx = m.HasThis ? i - 1 : i;\n                    var arg = Minus(topFrame.LocalVarPointer, argumentCount);\n                    string name = null;\n                    object v = null;\n                    string typeName = null;\n                    var val = Add(arg, i);\n                    v =  StackObject.ToObject(val, intp.AppDomain, intp.Stack.ManagedStack);\n                    if (v == null)\n                        v = \"null\";\n                    if (argIdx >= 0)\n                    {\n                        var lv = m.Definition.Parameters[argIdx];\n                        name = string.IsNullOrEmpty(lv.Name) ? \"arg\" + lv.Index : lv.Name;\n                        typeName = lv.ParameterType.FullName;\n                        if (v != null)\n                            v = m.Parameters[argIdx].TypeForCLR.CheckCLRTypes(v);\n                    }\n                    else\n                    {\n                        name = \"this\";\n                        typeName = m.DeclearingType.FullName;\n                    }\n\n                    VariableInfo vinfo = new Debugger.VariableInfo();\n                    vinfo.Address = (long)val;\n                    vinfo.Name = name;\n                    vinfo.Value = v.ToString();\n                    vinfo.TypeName = typeName;\n                    vinfo.Expandable = GetValueExpandable(val, intp.Stack.ManagedStack);\n\n                    info.LocalVariables[i] = vinfo;\n                }\n                for (int i = argumentCount; i < info.LocalVariables.Length; i++)\n                {\n                    var locIdx = i - argumentCount;\n                    var lv = m.Definition.Body.Variables[locIdx];\n                    var val = Add(topFrame.LocalVarPointer, locIdx);\n                    var v = StackObject.ToObject(val, intp.AppDomain, intp.Stack.ManagedStack);\n                    if (v == null)\n                        v = \"null\";\n                    else\n                        v = intp.AppDomain.GetType(lv.VariableType, m.DeclearingType, m).TypeForCLR.CheckCLRTypes(v);\n                    string name = string.IsNullOrEmpty(lv.Name) ? \"v\" + lv.Index : lv.Name;\n                    VariableInfo vinfo = new Debugger.VariableInfo();\n                    vinfo.Address = (long)val;\n                    vinfo.Name = name;\n                    vinfo.Value = v.ToString();\n                    vinfo.TypeName = lv.VariableType.FullName;\n                    vinfo.Expandable = GetValueExpandable(val, intp.Stack.ManagedStack);\n                    info.LocalVariables[i] = vinfo;\n                }\n                frameInfos[j] = info;\n            }\n            return frameInfos;\n        }\n\n        internal VariableInfo ResolveVariable(VariableReference parent, string name)\n        {\n            return null;\n        }\n\n        unsafe bool GetValueExpandable(StackObject* esp, IList<object> mStack)\n        {\n            if (esp->ObjectType < ObjectTypes.Object)\n                return false;\n            else\n            {\n                var obj = mStack[esp->Value];\n                if (obj == null)\n                    return false;\n                if (obj is ILTypeInstance)\n                    return true;\n                else if (obj.GetType().IsPrimitive)\n                    return false;\n                else\n                    return true;\n\n            }\n        }\n\n        internal void ThreadStarted(ILIntepreter intp)\n        {\n            if (server != null && server.IsAttached)\n            {\n                server.SendSCThreadStarted(intp.GetHashCode());\n            }\n        }\n\n        internal void ThreadEnded(ILIntepreter intp)\n        {\n            if (server != null && server.IsAttached)\n            {\n                server.SendSCThreadEnded(intp.GetHashCode());\n            }\n        }\n\n        internal void Detach()\n        {\n            activeBreakpoints.Clear();\n            breakpointMapping.Clear();\n            foreach (var j in AppDomain.Intepreters)\n            {\n                j.Value.ClearDebugState();\n                j.Value.Resume();\n            }\n        }\n\n        internal unsafe void DumpStack(StackObject* esp, RuntimeStack stack)\n        {\n#if !UNITY_5 && !UNITY_2017 && !UNITY_4\n            var start = stack.StackBase;\n            var end = esp + 10;\n            var frames = stack.Frames;\n            var mStack = stack.ManagedStack;\n            var valuePointerEnd = stack.ValueTypeStackPointer;\n            HashSet<long> leakVObj = new HashSet<long>();\n            for (var i = stack.ValueTypeStackBase; i > stack.ValueTypeStackPointer;)\n            {\n                leakVObj.Add((long)i);\n                i = Minus(i, i->ValueLow + 1);\n            }\n            for (var i = start; i <= end; i++)\n            {\n                StringBuilder sb = new StringBuilder();\n                ILMethod localMethod = null, baseMethod = null;\n                bool isLocal = false;\n                bool isBase = false;\n                int localIdx = 0;\n                if (i == esp)\n                    sb.Append(\"->\");\n                foreach (var j in frames)\n                {\n                    if (i >= j.LocalVarPointer && i < j.BasePointer)\n                    {\n                        isLocal = true;\n                        localIdx = (int)(i - j.LocalVarPointer);\n                        localMethod = j.Method;\n                    }\n                    else if (i == j.BasePointer)\n                    {\n                        isBase = true;\n                        baseMethod = j.Method;\n                    }\n                }\n                sb.Append(string.Format(\"(0x{0:X8}) Type:{1} \", (long)i, i->ObjectType));\n                GetStackObjectText(sb, i, mStack, valuePointerEnd);\n                if (i < esp)\n                {\n                    if (i->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                        VisitValueTypeReference(*(StackObject**)&i->Value, leakVObj);\n                }\n                if (isLocal)\n                {\n                    sb.Append(string.Format(\"|Loc:{0}\", localIdx));\n                    if (localIdx == 0)\n                    {\n                        sb.Append(\" Method:\");\n                        sb.Append(localMethod.ToString());\n                    }\n                }\n                if (isBase)\n                {\n                    sb.Append(\"|Base\");\n                    sb.Append(\" Method:\");\n                    sb.Append(baseMethod.ToString());\n                }\n\n                System.Diagnostics.Debug.Print(sb.ToString());\n            }\n\n            for (var i = stack.ValueTypeStackBase; i > stack.ValueTypeStackPointer;)\n            {\n                var vt = domain.GetType(i->Value);\n                var cnt = i->ValueLow;\n                bool leak = leakVObj.Contains((long)i);\n                System.Diagnostics.Debug.Print(\"----------------------------------------------\");\n                System.Diagnostics.Debug.Print(string.Format(\"{2}(0x{0:X8}){1}\", (long)i, vt, leak ? \"*\" : \"\"));\n                for (int j = 0; j < cnt; j++)\n                {\n                    StringBuilder sb = new StringBuilder();\n                    var ptr = Minus(i, j + 1);\n                    sb.Append(string.Format(\"(0x{0:X8}) Type:{1} \", (long)ptr, ptr->ObjectType));\n                    GetStackObjectText(sb, ptr, mStack, valuePointerEnd);\n                    System.Diagnostics.Debug.Print(sb.ToString());\n                }\n                i = Minus(i, i->ValueLow + 1);\n            }\n            System.Diagnostics.Debug.Print(\"Managed Objects:\");\n            for (int i = 0; i < mStack.Count; i++)\n            {\n                System.Diagnostics.Debug.Print(string.Format(\"({0}){1}\", i, mStack[i]));\n            }\n#endif\n        }\n\n        unsafe void GetStackObjectText(StringBuilder sb, StackObject* esp, IList<object> mStack, StackObject* valueTypeEnd)\n        {\n            string text = \"null\";\n            switch (esp->ObjectType)\n            {\n                case ObjectTypes.StackObjectReference:\n                    {\n                        sb.Append(string.Format(\"Value:0x{0:X8}\", (long)*(StackObject**)&esp->Value));\n                    }\n                    break;\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        object obj = null;\n                        var dst = *(StackObject**)&esp->Value;\n                        if (dst > valueTypeEnd)\n                            obj = StackObject.ToObject(esp, domain, mStack);\n                        if (obj != null)\n                            text = obj.ToString();\n\n                        text += string.Format(\"({0})\", domain.GetType(dst->Value));\n                    }\n                    sb.Append(string.Format(\"Value:0x{0:X8} Text:{1} \", (long)*(StackObject**)&esp->Value, text));\n                    break;\n                default:\n                    {\n                        if (esp->ObjectType >= ObjectTypes.Null && esp->ObjectType <= ObjectTypes.ArrayReference)\n                        {\n                            if (esp->ObjectType < ObjectTypes.Object || esp->Value < mStack.Count)\n                            {\n                                var obj = StackObject.ToObject(esp, domain, mStack);\n                                if (obj != null)\n                                    text = obj.ToString();\n                            }\n                        }\n\n                        sb.Append(string.Format(\"Value:{0} ValueLow:{1} Text:{2} \", esp->Value, esp->ValueLow, text));\n                    }\n                    break;\n\n            }\n        }\n\n        unsafe void VisitValueTypeReference(StackObject* esp, HashSet<long> leak)\n        {\n            leak.Remove((long)esp);\n            for (int i = 0; i < esp->ValueLow; i++)\n            {\n                var ptr = Minus(esp, i + 1);\n                if (ptr->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                {\n                    VisitValueTypeReference(*(StackObject**)&ptr->Value, leak);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/DebugSocket.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\nusing System.Net.Sockets;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public class DebugSocket\n    {\n        private Socket _socket = null;\n        private bool _ready = false;\n        bool connectFailed = false;\n        private const int MAX_BUFF_SIZE = 256 * 1024;\n        private const int HEAD_SIZE = 8;\n        private byte[] _headBuffer = new byte[HEAD_SIZE];\n        private byte[] _sendBuffer = new byte[64 * 1024];\n        //private MemoryPoolSafe<Package> _packagePool = new MemoryPoolSafe<Package>();\n        //private Package _currPackage = null;\n        private System.IO.MemoryStream _sendStream = null;\n        BinaryWriter bw;\n        const int RECV_BUFFER_SIZE = 1024;\n        private MemoryStream recvBuffer = new MemoryStream();\n        private int lastMsgLength = -1;\n\n        private byte[] socketAsyncBuffer = new byte[RECV_BUFFER_SIZE];\n        private SocketAsyncEventArgs saeArgs;\n        private object socketLockObj = new object();\n        private byte[] _sendHeaderBuffer = new byte[HEAD_SIZE];\n\n        public bool Disconnected { get { return _socket == null || !_socket.Connected; } }\n        public Action OnConnect { get; set; }\n\n        public Action OnConnectFailed { get; set; }\n        public Action OnClose { get; set; }\n\n        public Action<DebugMessageType, byte[]> OnReciveMessage { get; set; }\n\n\n        public DebugSocket()\n        {\n            _sendStream = new System.IO.MemoryStream(_sendBuffer);\n            bw = new BinaryWriter(_sendStream);\n        }\n        public DebugSocket(Socket _socket)\n            : this()\n        {\n            this._socket = _socket;\n            BeginReceive();\n            _ready = true;\n        }\n        public void Connect(string ip, int port)\n        {\n            Close();\n            Socket socket;\n            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n            socket.BeginConnect(ip, port, new AsyncCallback(onConnected), this);\n            _socket = socket;\n            _ready = false;\n        }\n\n        private void AsyncRecv_Completed(object sender, SocketAsyncEventArgs e)\n        {\n            if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)\n            {\n                try\n                {\n                    ReceivePayload(e.Buffer, e.BytesTransferred);\n                }\n                catch (Exception ex)\n                {\n                    Close();\n                    return;\n                }\n            }\n            else\n            {\n                Close();\n                return;\n            }\n\n            try\n            {\n                //继续接受数据\n                if (!_socket.ReceiveAsync(saeArgs))\n                {\n                    AsyncRecv_Completed(null, saeArgs);\n                }\n            }\n            catch (Exception ex)\n            {\n                Close();\n                throw ex;\n            }\n        }\n\n        private void ReceivePayload(byte[] data, int length)\n        {\n            if (_socket == null)\n                return;\n            if (!_socket.Connected)\n            {\n                Close();\n                return;\n            }\n            //接受数据并拼接成message\n            byte[] msgBuff;\n            //写入缓存\n            recvBuffer.Position = recvBuffer.Length;\n            recvBuffer.Write(data, 0, length);\n            //如果长度有错，返回\n            if (lastMsgLength < 0 && recvBuffer.Length < 4)\n            {\n                msgBuff = null;\n                return;\n            }\n\n            recvBuffer.Position = 0;\n            BinaryReader br = new BinaryReader(recvBuffer);\n            //读取消息长度\n            if (lastMsgLength < 0)\n            {\n                lastMsgLength = br.ReadInt32() - 4;\n                if (lastMsgLength > MAX_BUFF_SIZE)\n                {\n                    Close();\n                    throw new Exception(\"Too long package length!\");\n                }\n            }\n            int remaining = (int)(recvBuffer.Length - recvBuffer.Position);\n            //消息已经完整\n            while (remaining >= lastMsgLength && lastMsgLength > 0)\n            {\n\n                //读取一条消息\n                int type = br.ReadInt32();\n                msgBuff = br.ReadBytes(lastMsgLength - 4);\n\n                if (OnReciveMessage != null)\n                    OnReciveMessage((DebugMessageType)type, msgBuff);\n\n                lastMsgLength = -1;\n                remaining = (int)(recvBuffer.Length - recvBuffer.Position);\n                //保留剩余数据\n                if (remaining >= 4)\n                {\n                    lastMsgLength = br.ReadInt32() - 4;\n                    remaining -= 4;\n                    if (lastMsgLength > MAX_BUFF_SIZE)\n                    {\n                        Close();\n                        throw new Exception(\"Too long package length!\");\n                    }\n                }\n            }\n\n            remaining = (int)(recvBuffer.Length - recvBuffer.Position);\n            if (remaining > 0)\n            {\n                byte[] buffer = recvBuffer.GetBuffer();\n                Array.Copy(buffer, recvBuffer.Position, buffer, 0, remaining);\n            }\n            recvBuffer.Position = 0;\n            recvBuffer.SetLength(remaining);\n        }\n        private void onConnected(IAsyncResult result)\n        {\n            if (_socket.Connected)\n            {\n                _socket.EndConnect(result);\n\n                BeginReceive();\n                if (OnConnect != null)\n                    OnConnect();\n                //ReceiveOnce();\n            }\n            else\n            {\n                if (OnConnectFailed != null)\n                    OnConnectFailed();\n            }\n        }\n\n        void BeginReceive()\n        {\n            saeArgs = new SocketAsyncEventArgs();\n            saeArgs.Completed += AsyncRecv_Completed;\n            saeArgs.SetBuffer(socketAsyncBuffer, 0, socketAsyncBuffer.Length);\n            _socket.ReceiveAsync(saeArgs);\n            _ready = true;\n        }\n\n        //len type msg\n        public void Send(DebugMessageType type, byte[] buffer, int len)\n        {\n            if (!_ready)\n                return;\n\n            //timeStamp = UnityEngine.Time.realtimeSinceStartup;\n            _sendStream.Position = 0;\n            bw.Write(len + HEAD_SIZE);\n            bw.Write((int)type);\n            bw.Write(buffer, 0, len);\n            int totalLen = (int)_sendStream.Position;\n\n            RawSend(_socket, _sendBuffer, totalLen);\n            //_socket.Send(_sendBuffer, len, SocketFlags.None);\n        }\n\n        private void RawSend(Socket sock, byte[] buf, int end)\n        {\n            if (sock == null)\n                return;\n            if (end < 0)\n                end = buf.Length;\n            sock.Send(buf, end, SocketFlags.None);\n        }\n\n        public void Close()\n        {\n            if (_socket == null || !_ready)\n                return;\n            if (saeArgs != null)\n                saeArgs.Dispose();\n            _socket.Close();\n            _socket = null;\n            _ready = false;\n            if (OnClose != null)\n            {\n                OnClose();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/DebuggerServer/DebuggerServer.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Net.Sockets;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime.Debugger.Protocol;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public class DebuggerServer\n    {\n        public const int Version = 1;\n        TcpListener listener;\n        //HashSet<Session<T>> clients = new HashSet<Session<T>>();\n        bool isUp = false;\n        int maxNewConnections = 1;\n        int port;\n        Thread mainLoop;\n        DebugSocket clientSocket;\n        System.IO.MemoryStream sendStream = new System.IO.MemoryStream(64 * 1024);\n        System.IO.BinaryWriter bw;\n        DebugService ds;\n\n        /// <summary>\n        /// 服务器监听的端口\n        /// </summary>\n        public int Port { get { return port; } set { this.port = value; } }\n\n        public DebugSocket Client { get { return clientSocket; } }\n\n        public bool IsAttached { get { return clientSocket != null && !clientSocket.Disconnected; } }\n\n        public DebuggerServer(DebugService ds)\n        {\n            this.ds = ds;\n            bw = new System.IO.BinaryWriter(sendStream);\n        }\n\n        public virtual bool Start()\n        {\n            mainLoop = new Thread(new ThreadStart(this.NetworkLoop));\n            mainLoop.Start();\n\n            this.listener = new TcpListener(port);\n            try { listener.Start(); }\n            catch\n            {\n                return false;\n            }\n            isUp = true;\n            return true;\n        }\n\n        public virtual void Stop()\n        {\n            isUp = false;\n            if (this.listener != null)\n                this.listener.Stop();\n            mainLoop.Abort();\n            mainLoop = null;\n        }\n\n        void NetworkLoop()\n        {\n            while (true)\n            {\n                try\n                {\n                    // let new clients (max 10) connect\n                    if (isUp && clientSocket == null)\n                    {\n                        for (int i = 0; listener.Pending() && i < maxNewConnections; i++)\n                        {\n                            CreateNewSession(listener);\n                        }\n                    }\n                    System.Threading.Thread.Sleep(1);\n                }\n                catch (ThreadAbortException)\n                {\n                }\n                catch (Exception)\n                {\n                    \n                }\n            }\n        }\n\n        void CreateNewSession(TcpListener listener)\n        {\n            Socket sock = listener.AcceptSocket();\n            clientSocket = new DebugSocket(sock);           \n            clientSocket.OnReciveMessage = OnReceive;\n            clientSocket.OnClose = OnClose;\n            ClientConnected();\n        }\n\n        void ClientConnected()\n        {\n\n        }\n\n        void OnClose()\n        {\n            ds.Detach();\n            clientSocket = null;\n        }\n\n        void OnReceive(DebugMessageType type, byte[] buffer)\n        {\n            if (clientSocket == null || clientSocket.Disconnected)\n                return;\n            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);\n            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);\n\n            switch (type)\n            {\n                case DebugMessageType.CSAttach:\n                    {\n                        SendAttachResult();\n                    }\n                    break;\n                case DebugMessageType.CSBindBreakpoint:\n                    {\n                        CSBindBreakpoint msg = new Protocol.CSBindBreakpoint();\n                        msg.BreakpointHashCode = br.ReadInt32();\n                        msg.TypeName = br.ReadString();\n                        msg.MethodName = br.ReadString();\n                        msg.StartLine = br.ReadInt32();\n                        msg.EndLine = br.ReadInt32();\n                        TryBindBreakpoint(msg);\n                    }\n                    break;\n                case DebugMessageType.CSDeleteBreakpoint:\n                    {\n                        CSDeleteBreakpoint msg = new Protocol.CSDeleteBreakpoint();\n                        msg.BreakpointHashCode = br.ReadInt32();\n                        ds.DeleteBreakpoint(msg.BreakpointHashCode);\n                    }\n                    break;\n                case DebugMessageType.CSExecute:\n                    {\n                        CSExecute msg = new Protocol.CSExecute();\n                        msg.ThreadHashCode = br.ReadInt32();\n                        ds.ExecuteThread(msg.ThreadHashCode);\n                    }\n                    break;\n                case DebugMessageType.CSStep:\n                    {\n                        CSStep msg = new CSStep();\n                        msg.ThreadHashCode = br.ReadInt32();\n                        msg.StepType = (StepTypes)br.ReadByte();\n                        ds.StepThread(msg.ThreadHashCode, msg.StepType);\n                    }\n                    break;\n                case DebugMessageType.CSResolveVariable:\n                    {\n                        CSResolveVariable msg = new CSResolveVariable();\n                        msg.Name = br.ReadString();\n                        msg.Parent = ReadVariableReference(br);\n                        var info = ds.ResolveVariable(msg.Parent, msg.Name);\n                    }\n                    break;\n            }\n\n        }\n\n        VariableReference ReadVariableReference(System.IO.BinaryReader br)\n        {\n            VariableReference res = null;\n            if (br.ReadBoolean())\n            {\n                res = new Debugger.VariableReference();\n                res.Address = br.ReadInt64();\n                res.Type = (VariableTypes)br.ReadByte();\n                res.Offset = br.ReadInt32();\n                res.Parent = ReadVariableReference(br);\n            }\n            return res;\n        }\n\n        void SendAttachResult()\n        {\n            sendStream.Position = 0;\n            bw.Write((byte)AttachResults.OK);\n            bw.Write(Version);\n            DoSend(DebugMessageType.SCAttachResult);\n            lock (ds.AppDomain.FreeIntepreters)\n            {\n                foreach (var i in ds.AppDomain.Intepreters)\n                {\n                    SendSCThreadStarted(i.Key);\n                }\n            }\n        }\n\n        void DoSend(DebugMessageType type)\n        {\n            if (clientSocket != null && !clientSocket.Disconnected)\n                clientSocket.Send(type, sendStream.GetBuffer(), (int)sendStream.Position);\n        }\n\n        void TryBindBreakpoint(CSBindBreakpoint msg)\n        {\n            var domain = ds.AppDomain;\n            SCBindBreakpointResult res = new Protocol.SCBindBreakpointResult();\n            res.BreakpointHashCode = msg.BreakpointHashCode;\n            IType type;\n            if (domain.LoadedTypes.TryGetValue(msg.TypeName, out type))\n            {\n                if(type is ILType)\n                {\n                    ILType it = (ILType)type;\n                    ILMethod found = null;\n                    foreach(var i in it.GetMethods())\n                    {\n                        if(i.Name == msg.MethodName)\n                        {\n                            ILMethod ilm = (ILMethod)i;\n                            if (ilm.StartLine <= (msg.StartLine + 1) && ilm.EndLine >= (msg.StartLine + 1))\n                            {\n                                found = ilm;\n                                break;\n                            }\n                        }\n                    }\n                    if(found != null)\n                    {\n                        ds.SetBreakPoint(found.GetHashCode(), msg.BreakpointHashCode, msg.StartLine);\n                        res.Result = BindBreakpointResults.OK;\n                    }\n                    else\n                    {\n                        res.Result = BindBreakpointResults.CodeNotFound;\n                    }\n                }\n                else\n                {\n                    res.Result = BindBreakpointResults.TypeNotFound;\n                }\n            }\n            else\n            {\n                res.Result = BindBreakpointResults.TypeNotFound;\n            }\n            SendSCBindBreakpointResult(res);\n        }\n\n        void SendSCBindBreakpointResult(SCBindBreakpointResult msg)\n        {\n            sendStream.Position = 0;\n            bw.Write(msg.BreakpointHashCode);\n            bw.Write((byte)msg.Result);\n            DoSend(DebugMessageType.SCBindBreakpointResult);\n        }\n\n        internal void SendSCBreakpointHit(int intpHash, int bpHash, KeyValuePair<int, StackFrameInfo[]>[] info)\n        {\n            sendStream.Position = 0;\n            bw.Write(bpHash);\n            bw.Write(intpHash);\n            WriteStackFrames(info);\n            DoSend(DebugMessageType.SCBreakpointHit);\n        }\n\n        internal void SendSCStepComplete(int intpHash, KeyValuePair<int, StackFrameInfo[]>[] info)\n        {\n            sendStream.Position = 0;\n            bw.Write(intpHash);\n            WriteStackFrames(info);\n            DoSend(DebugMessageType.SCStepComplete);\n        }\n\n        void SendSCResolveVariableResult(VariableInfo info)\n        {\n            sendStream.Position = 0;\n            WriteVariableInfo(info);\n            DoSend(DebugMessageType.SCResolveVariableResult);\n        }\n\n        void WriteStackFrames(KeyValuePair<int, StackFrameInfo[]>[] info)\n        {\n            bw.Write(info.Length);\n            foreach (var i in info)\n            {\n                bw.Write(i.Key);\n                bw.Write(i.Value.Length);\n                foreach (var j in i.Value)\n                {\n                    bw.Write(j.MethodName);\n                    bw.Write(j.DocumentName);\n                    bw.Write(j.StartLine);\n                    bw.Write(j.StartColumn);\n                    bw.Write(j.EndLine);\n                    bw.Write(j.EndColumn);\n                    bw.Write(j.LocalVariables.Length);\n                    foreach (var k in j.LocalVariables)\n                    {\n                        WriteVariableInfo(k);\n                    }\n                }\n            }\n        }\n\n        void WriteVariableInfo(VariableInfo k)\n        {\n            bw.Write(k.Address);\n            bw.Write((byte)k.Type);\n            bw.Write(k.Offset);\n            bw.Write(k.Name);\n            bw.Write(k.Value);\n            bw.Write(k.TypeName);\n            bw.Write(k.Expandable);\n        }\n\n        internal void SendSCThreadStarted(int threadHash)\n        {\n            sendStream.Position = 0;\n            bw.Write(threadHash);\n            DoSend(DebugMessageType.SCThreadStarted);\n        }\n\n        internal void SendSCThreadEnded(int threadHash)\n        {\n            sendStream.Position = 0;\n            bw.Write(threadHash);\n            DoSend(DebugMessageType.SCThreadEnded);\n        }\n\n        public void NotifyModuleLoaded(string modulename)\n        {\n            sendStream.Position = 0;\n            bw.Write(modulename);\n            DoSend(DebugMessageType.SCModuleLoaded);\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/CSBindBreakpoint.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class CSBindBreakpoint\n    {\n        public int BreakpointHashCode { get; set; }\n        public string TypeName { get; set; }\n        public string MethodName { get; set; }\n        public int StartLine { get; set; }\n        public int EndLine { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/CSDeleteBreakpoint.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class CSDeleteBreakpoint\n    {\n        public int BreakpointHashCode { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/CSExecute.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class CSExecute\n    {\n        public int ThreadHashCode { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/CSResolveVariable.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class CSResolveVariable\n    {\n        public string Name { get; set; }\n        public VariableReference Parent { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/CSStep.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class CSStep\n    {\n        public int ThreadHashCode { get; set; }\n        public StepTypes StepType { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/SCAttachResult.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public enum AttachResults\n    {\n        OK,\n        AlreadyAttached,\n    }\n    public class SCAttachResult\n    {\n        public AttachResults Result { get; set; }\n        public int DebugServerVersion { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/SCBindBreakpointResult.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public enum BindBreakpointResults\n    {\n        OK,\n        TypeNotFound,\n        CodeNotFound,\n    }\n    public class SCBindBreakpointResult\n    {\n        public int BreakpointHashCode { get; set; }\n        public BindBreakpointResults Result { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/SCBreakpointHit.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class SCBreakpointHit\n    {\n        public int BreakpointHashCode { get; set; }\n        public int ThreadHashCode { get; set; }\n        public KeyValuePair<int, StackFrameInfo[]>[] StackFrame { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/SCModuleLoaded.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class SCModuleLoaded\n    {\n        public string ModuleName { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/SCResolveVariableResult.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class SCResolveVariableResult\n    {\n        public VariableInfo Info { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/SCStepComplete.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class SCStepComplete\n    {\n        public int ThreadHashCode { get; set; }\n        public KeyValuePair<int, StackFrameInfo[]>[] StackFrame { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/Protocol/SCThreadStarted.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger.Protocol\n{\n    public class SCThreadStarted\n    {\n        public int ThreadHashCode { get; set; }\n    }\n    public class SCThreadEnded\n    {\n        public int ThreadHashCode { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/StackFrameInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public class StackFrameInfo\n    {\n        public string MethodName { get; set; }\n        public string DocumentName { get; set; }\n        public int StartLine { get; set; }\n        public int StartColumn { get; set; }\n        public int EndLine { get; set; }\n        public int EndColumn { get; set; }\n        public VariableInfo[] LocalVariables { get; set; }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/StepTypes.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public enum StepTypes\n    {\n        None,\n        Into,\n        Over,\n        Out,\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Debugger/VariableInfo.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Debugger\n{\n    public enum VariableTypes\n    {\n        Normal,\n        FieldReference,\n        Error,\n    }\n\n    public class VariableReference\n    {\n        public long Address { get; set; }\n        public VariableTypes Type { get; set; }\n        public int Offset { get; set; }\n        public VariableReference Parent { get; set; }\n    }\n\n    public class VariableInfo\n    {\n        public long Address { get; set; }\n        public VariableTypes Type { get; set; }\n        public string Name { get; set; }\n        public string TypeName { get; set; }\n        public string Value { get; set; }\n        public bool Expandable { get; set; }\n        public int Offset { get; set;}\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Enviorment/AppDomain.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\nusing Mono.Cecil;\nusing System.Reflection;\nusing Mono.Cecil.Cil;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.Utils;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Debugger;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Other;\nnamespace ILRuntime.Runtime.Enviorment\n{\n    public unsafe delegate StackObject* CLRRedirectionDelegate(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj);\n    public delegate object CLRFieldGetterDelegate(ref object target);\n    public delegate void CLRFieldSetterDelegate(ref object target, object value);\n    public delegate object CLRMemberwiseCloneDelegate(ref object target);\n    public delegate object CLRCreateDefaultInstanceDelegate();\n    public delegate object CLRCreateArrayInstanceDelegate(int size);\n\n    public class AppDomain\n    {\n        Queue<ILIntepreter> freeIntepreters = new Queue<ILIntepreter>();\n        Dictionary<int, ILIntepreter> intepreters = new Dictionary<int, ILIntepreter>();\n        Dictionary<Type, CrossBindingAdaptor> crossAdaptors = new Dictionary<Type, CrossBindingAdaptor>(new ByReferenceKeyComparer<Type>());\n        Dictionary<Type, ValueTypeBinder> valueTypeBinders = new Dictionary<Type, ValueTypeBinder>();\n        ThreadSafeDictionary<string, IType> mapType = new ThreadSafeDictionary<string, IType>();\n        Dictionary<Type, IType> clrTypeMapping = new Dictionary<Type, IType>(new ByReferenceKeyComparer<Type>());\n        ThreadSafeDictionary<int, IType> mapTypeToken = new ThreadSafeDictionary<int, IType>();\n        ThreadSafeDictionary<int, IMethod> mapMethod = new ThreadSafeDictionary<int, IMethod>();\n        ThreadSafeDictionary<long, string> mapString = new ThreadSafeDictionary<long, string>();\n        Dictionary<System.Reflection.MethodBase, CLRRedirectionDelegate> redirectMap = new Dictionary<System.Reflection.MethodBase, CLRRedirectionDelegate>();\n        Dictionary<System.Reflection.FieldInfo, CLRFieldGetterDelegate> fieldGetterMap = new Dictionary<System.Reflection.FieldInfo, CLRFieldGetterDelegate>();\n        Dictionary<System.Reflection.FieldInfo, CLRFieldSetterDelegate> fieldSetterMap = new Dictionary<System.Reflection.FieldInfo, CLRFieldSetterDelegate>();\n        Dictionary<Type, CLRMemberwiseCloneDelegate> memberwiseCloneMap = new Dictionary<Type, CLRMemberwiseCloneDelegate>(new ByReferenceKeyComparer<Type>());\n        Dictionary<Type, CLRCreateDefaultInstanceDelegate> createDefaultInstanceMap = new Dictionary<Type, CLRCreateDefaultInstanceDelegate>(new ByReferenceKeyComparer<Type>());\n        Dictionary<Type, CLRCreateArrayInstanceDelegate> createArrayInstanceMap = new Dictionary<Type, CLRCreateArrayInstanceDelegate>(new ByReferenceKeyComparer<Type>());\n        IType voidType, intType, longType, boolType, floatType, doubleType, objectType;\n        DelegateManager dMgr;\n        Assembly[] loadedAssemblies;\n        Dictionary<string, byte[]> references = new Dictionary<string, byte[]>();\n        DebugService debugService;\n\n        /// <summary>\n        /// Determine if invoking unbinded CLR method(using reflection) is allowed\n        /// </summary>\n        public bool AllowUnboundCLRMethod { get; set; }\n\n#if UNITY_EDITOR\n        public int UnityMainThreadID { get; set; }\n#endif\n        public unsafe AppDomain()\n        {\n            AllowUnboundCLRMethod = true;\n            loadedAssemblies = System.AppDomain.CurrentDomain.GetAssemblies();\n            var mi = typeof(System.Runtime.CompilerServices.RuntimeHelpers).GetMethod(\"InitializeArray\");\n            RegisterCLRMethodRedirection(mi, CLRRedirections.InitializeArray);\n            foreach (var i in typeof(System.Activator).GetMethods())\n            {\n                if (i.Name == \"CreateInstance\" && i.IsGenericMethodDefinition)\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.CreateInstance);\n                }\n                else if(i.Name == \"CreateInstance\" && i.GetParameters().Length == 1)\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.CreateInstance2);\n                }\n            }\n            foreach (var i in typeof(System.Type).GetMethods())\n            {\n                if (i.Name == \"GetType\" && i.IsStatic)\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.GetType);\n                }\n                if(i.Name==\"Equals\" && i.GetParameters()[0].ParameterType == typeof(Type))\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.TypeEquals);\n                }\n            }\n            foreach (var i in typeof(System.Delegate).GetMethods())\n            {\n                if (i.Name == \"Combine\" && i.GetParameters().Length == 2)\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.DelegateCombine);\n                }\n                if(i.Name == \"Remove\")\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.DelegateRemove);\n                }\n                if(i.Name == \"op_Equality\")\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.DelegateEqulity);\n                }\n                if(i.Name == \"op_Inequality\")\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.DelegateInequlity);\n                }\n            }\n            foreach(var i in typeof(MethodBase).GetMethods())\n            {\n                if(i.Name == \"Invoke\" && i.GetParameters().Length == 2)\n                {\n                    RegisterCLRMethodRedirection(i, CLRRedirections.MethodInfoInvoke);\n                }\n            }\n            mi = typeof(System.Type).GetMethod(\"GetTypeFromHandle\");\n            RegisterCLRMethodRedirection(mi, CLRRedirections.GetTypeFromHandle);\n            mi = typeof(object).GetMethod(\"GetType\");\n            RegisterCLRMethodRedirection(mi, CLRRedirections.ObjectGetType);\n            dMgr = new DelegateManager(this);\n            dMgr.RegisterDelegateConvertor<Action>((dele) =>\n            {\n                return dele;\n            });\n\n            RegisterCrossBindingAdaptor(new Adaptors.AttributeAdaptor());\n\n            debugService = new Debugger.DebugService(this);\n        }\n\n        public IType VoidType { get { return voidType; } }\n        public IType IntType { get { return intType; } }\n        public IType LongType { get { return longType; } }\n        public IType BoolType { get { return boolType; } }\n        public IType FloatType { get { return floatType; } }\n        public IType DoubleType { get { return doubleType; } }\n        public IType ObjectType { get { return objectType; } }\n\n        /// <summary>\n        /// Attention, this property isn't thread safe\n        /// </summary>\n        public Dictionary<string, IType> LoadedTypes { get { return mapType.InnerDictionary; } }\n        internal Dictionary<MethodBase, CLRRedirectionDelegate> RedirectMap { get { return redirectMap; } }\n        internal Dictionary<FieldInfo, CLRFieldGetterDelegate> FieldGetterMap { get { return fieldGetterMap; } }\n        internal Dictionary<FieldInfo, CLRFieldSetterDelegate> FieldSetterMap { get { return fieldSetterMap; } }\n        internal Dictionary<Type, CLRMemberwiseCloneDelegate> MemberwiseCloneMap { get { return memberwiseCloneMap; } }\n        internal Dictionary<Type, CLRCreateDefaultInstanceDelegate> CreateDefaultInstanceMap { get { return createDefaultInstanceMap; } }\n        internal Dictionary<Type, CLRCreateArrayInstanceDelegate> CreateArrayInstanceMap { get { return createArrayInstanceMap; } }\n        internal Dictionary<Type, CrossBindingAdaptor> CrossBindingAdaptors { get { return crossAdaptors; } }\n        internal Dictionary<Type, ValueTypeBinder> ValueTypeBinders { get { return valueTypeBinders; } }\n        public DebugService DebugService { get { return debugService; } }\n        internal Dictionary<int, ILIntepreter> Intepreters { get { return intepreters; } }\n        internal Queue<ILIntepreter> FreeIntepreters { get { return freeIntepreters; } }\n\n        public DelegateManager DelegateManager { get { return dMgr; } }\n\n        \n        /// <summary>\n        /// 加载Assembly 文件，从指定的路径\n        /// </summary>\n        /// <param name=\"path\">路径</param>\n        public void LoadAssemblyFile(string path)\n        {\n            FileInfo file = new FileInfo(path);\n\n            if (!file.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"Assembly File not find!:\\r\\n{0}\", path));\n            }\n            else\n            {\n                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))\n                {\n                    LoadAssembly(fs);\n\n                    fs.Dispose();\n                }\n            }\n        }\n\n#if USE_MDB || USE_PDB\n        /// <summary>\n        /// 加载Assembly 文件和PDB文件或MDB文件，从指定的路径（PDB和MDB文件按默认命名方式，并且和Assembly文件处于同一目录中\n        /// </summary>\n        /// <param name=\"path\">路径</param>\n        public void LoadAssemblyFileAndSymbol(string path)\n        {\n            FileInfo file = new FileInfo(path);\n\n            if (!file.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"Assembly File not find!:\\r\\n{0}\", path));\n            }\n            else\n            {\n                var dlldir = file.DirectoryName;\n                var assname = Path.GetFileNameWithoutExtension(file.Name);\n                var pdbpath = string.Format(\"{0}/{1}.pdb\",dlldir,assname);\n                var mdbpath = string.Format(\"{0}/{1}.mdb\", dlldir, assname);\n\n                string symbolPath = \"\";\n\n                bool isPDB = true;\n                if (File.Exists(pdbpath))\n                {\n                    symbolPath = pdbpath;\n                }\n                else if (File.Exists(mdbpath))\n                {\n                    symbolPath = mdbpath;\n                    isPDB = false;\n                }\n\n\n                if (string.IsNullOrEmpty(symbolPath))\n                {\n                    throw new FileNotFoundException(string.Format(\"symbol file not find!:\\r\\ncheck:\\r\\n{0}\\r\\n{1}\\r\\n\", pdbpath,mdbpath));\n                }\n\n                using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))\n                {                  \n                    \n                    using (var pdbfs = new System.IO.FileStream(symbolPath, FileMode.Open))\n                    {\n                        if (isPDB)\n                        {\n                            LoadAssemblyPDB(fs, pdbfs);\n                        }\n                        else\n                        {\n                            LoadAssemblyMDB(fs, pdbfs);\n                        }\n                    }\n                }\n            }\n        }\n#endif\n\n#if USE_PDB\n        /// <summary>\n        /// 加载Assembly 文件和PDB文件，两者都从指定的路径\n        /// </summary>\n        /// <param name=\"assemblyFilePath\">Assembly 文件路径</param>\n        /// <param name=\"symbolFilePath\">symbol文件路径</param>\n        public void LoadAssemblyFileAndPDB(string assemblyFilePath,string symbolFilePath)\n        {\n            FileInfo assfile = new FileInfo(assemblyFilePath);\n            FileInfo pdbfile = new FileInfo(symbolFilePath);\n            if (!assfile.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"Assembly File not find!:\\r\\n{0}\", assemblyFilePath));\n            }\n\n            if (!pdbfile.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"symbol file not find!:\\r\\n{0}\", symbolFilePath));\n            }\n\n            using (FileStream fs = new FileStream(assfile.FullName, FileMode.Open, FileAccess.Read))\n            {\n\n                using (var pdbfs = new System.IO.FileStream(pdbfile.FullName, FileMode.Open))\n                {\n                    LoadAssemblyPDB(fs, pdbfs);\n                }\n            }\n\n        }\n\n        /// <summary>\n        ///  从流加载Assembly,以及symbol符号文件(pdb)\n        /// </summary>\n        /// <param name=\"stream\">Assembly Stream</param>\n        /// <param name=\"symbol\">PDB Stream</param>\n        public void LoadAssemblyPDB(System.IO.Stream stream, System.IO.Stream symbol)\n        {\n            LoadAssembly(stream, symbol, new Mono.Cecil.Pdb.PdbReaderProvider());\n        }\n\n#endif\n\n#if USE_MDB\n        /// <summary>\n        /// 加载Assembly 文件和MDB文件，两者都从指定的路径\n        /// </summary>\n        /// <param name=\"assemblyFilePath\">Assembly 文件路径</param>\n        /// <param name=\"symbolFilePath\">symbol文件路径</param>\n        public void LoadAssemblyFileAndMDB(string assemblyFilePath, string symbolFilePath)\n        {\n            FileInfo assfile = new FileInfo(assemblyFilePath);\n            FileInfo pdbfile = new FileInfo(symbolFilePath);\n            if (!assfile.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"Assembly File not find!:\\r\\n{0}\", assemblyFilePath));\n            }\n\n            if (!pdbfile.Exists)\n            {\n                throw new FileNotFoundException(string.Format(\"symbol file not find!:\\r\\n{0}\", symbolFilePath));\n            }\n\n            using (FileStream fs = new FileStream(assfile.FullName, FileMode.Open, FileAccess.Read))\n            {\n\n                using (var pdbfs = new System.IO.FileStream(pdbfile.FullName, FileMode.Open))\n                {\n                    LoadAssemblyMDB(fs, pdbfs);\n                }\n            }\n        }\n\n        /// <summary>\n        ///  从流加载Assembly,以及symbol符号文件(Mdb)\n        /// </summary>\n        /// <param name=\"stream\">Assembly Stream</param>\n        /// <param name=\"symbol\">PDB Stream</param>\n        public void LoadAssemblyMDB(System.IO.Stream stream, System.IO.Stream symbol)\n        {\n            LoadAssembly(stream, symbol, new Mono.Cecil.Mdb.MdbReaderProvider());\n        }\n#endif\n        /// <summary>\n        /// 从流加载Assembly 不加载symbol符号文件\n        /// </summary>\n        /// <param name=\"stream\">Dll数据流</param>\n        public void LoadAssembly(System.IO.Stream stream)\n        {\n            LoadAssembly(stream, null, null);\n        }        \n\n        /// <summary>\n        /// 从流加载Assembly,以及symbol符号文件(pdb)\n        /// </summary>\n        /// <param name=\"stream\">Assembly Stream</param>\n        /// <param name=\"symbol\">symbol Stream</param>\n        /// <param name=\"symbolReader\">symbol 读取器</param>\n        public void LoadAssembly(System.IO.Stream stream, System.IO.Stream symbol, ISymbolReaderProvider symbolReader)\n        {\n            var module = ModuleDefinition.ReadModule(stream); //从MONO中加载模块\n\n            if (symbolReader != null && symbol != null) \n            {\n                module.ReadSymbols(symbolReader.GetSymbolReader(module, symbol)); //加载符号表\n            }\n\n            if (module.HasAssemblyReferences) //如果此模块引用了其他模块\n            {\n                foreach (var ar in module.AssemblyReferences)\n                {\n                    /*if (moduleref.Contains(ar.Name) == false)\n                        moduleref.Add(ar.Name);\n                    if (moduleref.Contains(ar.FullName) == false)\n                        moduleref.Add(ar.FullName);*/\n                }\n            }\n\n            if (module.HasTypes)\n            {\n                List<ILType> types = new List<ILType>();\n\n                foreach (var t in module.GetTypes()) //获取所有此模块定义的类型\n                {\n                    ILType type = new ILType(t, this);\n\n                    mapType[t.FullName] = type;\n                    types.Add(type);\n\n                }\n            }\n\n            if (voidType == null)\n            {\n                voidType = GetType(\"System.Void\");\n                intType = GetType(\"System.Int32\");\n                longType = GetType(\"System.Int64\");\n                boolType = GetType(\"System.Boolean\");\n                floatType = GetType(\"System.Single\");\n                doubleType = GetType(\"System.Double\");\n                objectType = GetType(\"System.Object\");\n            }\n            module.AssemblyResolver.ResolveFailure += AssemblyResolver_ResolveFailure;\n#if DEBUG\n            debugService.NotifyModuleLoaded(module.Name);\n#endif\n        }\n\n        /// <summary>\n        /// External reference should be added to the AppDomain by the method\n        /// </summary>\n        /// <param name=\"name\">Assembly name, without .dll</param>\n        /// <param name=\"content\">file content</param>\n        public void AddReferenceBytes(string name, byte[] content)\n        {\n            references[name] = content;\n        }\n\n        private AssemblyDefinition AssemblyResolver_ResolveFailure(object sender, AssemblyNameReference reference)\n        {\n            byte[] content;\n            if (references.TryGetValue(reference.Name, out content))\n            {\n                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(content))\n                {\n                    return AssemblyDefinition.ReadAssembly(ms);\n                }\n            }\n            else\n                return null;\n        }\n\n        public void RegisterCLRMethodRedirection(MethodBase mi, CLRRedirectionDelegate func)\n        {\n            if (!redirectMap.ContainsKey(mi))\n                redirectMap[mi] = func;\n        }\n\n        public void RegisterCLRFieldGetter(FieldInfo f, CLRFieldGetterDelegate getter)\n        {\n            if (!fieldGetterMap.ContainsKey(f))\n                fieldGetterMap[f] = getter;\n        }\n\n        public void RegisterCLRFieldSetter(FieldInfo f, CLRFieldSetterDelegate setter)\n        {\n            if (!fieldSetterMap.ContainsKey(f))\n                fieldSetterMap[f] = setter;\n        }\n\n        public void RegisterCLRMemberwiseClone(Type t, CLRMemberwiseCloneDelegate memberwiseClone)\n        {\n            if (!memberwiseCloneMap.ContainsKey(t))\n                memberwiseCloneMap[t] = memberwiseClone;\n        }\n\n        public void RegisterCLRCreateDefaultInstance(Type t, CLRCreateDefaultInstanceDelegate createDefaultInstance)\n        {\n            if (!createDefaultInstanceMap.ContainsKey(t))\n                createDefaultInstanceMap[t] = createDefaultInstance;\n        }\n\n        public void RegisterCLRCreateArrayInstance(Type t, CLRCreateArrayInstanceDelegate createArray)\n        {\n            if (!createArrayInstanceMap.ContainsKey(t))\n                createArrayInstanceMap[t] = createArray;\n        }\n\n        public void RegisterValueTypeBinder(Type t, ValueTypeBinder binder)\n        {\n            if (!valueTypeBinders.ContainsKey(t))\n            {\n                valueTypeBinders[t] = binder;\n                binder.RegisterCLRRedirection(this);\n            }\n        }\n\n        /// <summary>\n        /// 更近类型名称返回类型\n        /// </summary>\n        /// <param name=\"fullname\">类型全名 命名空间.类型名</param>\n        /// <returns></returns>\n        public IType GetType(string fullname)\n        {\n            IType res;\n            if (fullname == null)\n            {\n                return null;\n            }\n\n            if (mapType.TryGetValue(fullname, out res))\n                return res;\n\n\n            string baseType;\n            List<string> genericParams;\n            bool isArray;\n\n            ParseGenericType(fullname, out baseType, out genericParams, out isArray);\n\n\n            bool isByRef = baseType.EndsWith(\"&\");\n            if (isByRef)\n                baseType = baseType.Substring(0, baseType.Length - 1);\n            if (genericParams != null || isArray || isByRef)\n            {\n                IType bt = GetType(baseType);\n                if (bt == null)\n                {\n                    bt = GetType(baseType.Replace(\"/\", \"+\"));\n                }\n\n                if (bt == null)\n                    return null;\n                if (genericParams != null)\n                {\n                    KeyValuePair<string, IType>[] genericArguments = new KeyValuePair<string, IType>[genericParams.Count];\n                    for (int i = 0; i < genericArguments.Length; i++)\n                    {\n                        string key = \"!\" + i;\n                        IType val = GetType(genericParams[i]);\n                        if (val == null)\n                            return null;\n                        genericArguments[i] = new KeyValuePair<string, IType>(key, val);\n                    }\n                    bt = bt.MakeGenericInstance(genericArguments);\n                    mapType[bt.FullName] = bt;\n                    mapTypeToken[bt.GetHashCode()] = bt;\n                    StringBuilder sb = new StringBuilder();\n                    sb.Append(baseType);\n                    sb.Append('<');\n                    for (int i = 0; i < genericParams.Count; i++)\n                    {\n                        if (i > 0)\n                            sb.Append(\",\");\n                        if (genericParams[i].Contains(\",\"))\n                            sb.Append(genericParams[i].Substring(0, genericParams[i].IndexOf(',')));\n                        else\n                            sb.Append(genericParams[i]);\n                    }\n                    sb.Append('>');\n                    var asmName = sb.ToString();\n                    if (bt.FullName != asmName)\n                        mapType[asmName] = bt;\n                }\n\n                if (isArray)\n                {\n                    bt = bt.MakeArrayType();\n                    mapType[bt.FullName] = bt;\n                    mapTypeToken[bt.GetHashCode()] = bt;\n                    if (!isByRef)\n                    {\n                        mapType[fullname] = bt;\n                        return bt;\n                    }\n                }\n\n                if (isByRef)\n                {\n                    res = bt.MakeByRefType();\n                    mapType[fullname] = res;\n                    mapType[res.FullName] = res;\n                    mapTypeToken[res.GetHashCode()] = res;\n                    return res;\n                }\n                else\n                {\n                    mapType[fullname] = bt;\n                    return bt;\n                }\n            }\n            else\n            {\n                Type t = Type.GetType(fullname);\n                if (t != null)\n                {\n                    if (!clrTypeMapping.TryGetValue(t, out res))\n                    {\n                        res = new CLRType(t, this);\n                        clrTypeMapping[t] = res;\n                    }\n                    mapType[fullname] = res;\n                    mapType[res.FullName] = res;\n                    mapType[t.AssemblyQualifiedName] = res;\n                    mapTypeToken[res.GetHashCode()] = res;\n                    return res;\n                }\n            }\n            return null;\n        }\n\n        internal static void ParseGenericType(string fullname, out string baseType, out List<string> genericParams, out bool isArray)\n        {\n            StringBuilder sb = new StringBuilder();\n            int depth = 0;\n            baseType = \"\";\n            genericParams = null;\n            if (fullname.Length >2 && fullname.Substring(fullname.Length - 2) == \"[]\")\n            {\n                fullname = fullname.Substring(0, fullname.Length - 2);\n                isArray = true;\n            }\n            else\n                isArray = false;\n            if (fullname.Contains('<') || fullname.Contains('['))\n            {\n                foreach (var i in fullname)\n                {\n                    if (i == '<' || i == '[')\n                    {\n                        depth++;\n                        if (depth == 1)\n                        {\n                            baseType = sb.ToString();\n                            sb.Length = 0;\n                            genericParams = new List<string>();\n                            continue;\n                        }\n                    }\n                    if (i == ',' && depth == 1)\n                    {\n                        string name = sb.ToString();\n                        if (name.StartsWith(\"[\"))\n                            name = name.Substring(1, name.Length - 2);\n                        if (!string.IsNullOrEmpty(name))\n                            genericParams.Add(name);\n                        sb.Length = 0;\n                        continue;\n                    }\n                    if (i == '>' || i == ']')\n                    {\n                        depth--;\n                        if (depth == 0)\n                        {\n                            string name = sb.ToString();\n                            if (name.StartsWith(\"[\"))\n                                name = name.Substring(1, name.Length - 2);\n                            if (!string.IsNullOrEmpty(name))\n                                genericParams.Add(name);\n                            else\n                            {\n                                if (!isArray)\n                                {\n                                    isArray = true;\n                                }\n                                else\n                                {\n                                    baseType += \"[]\";\n                                }\n                            }\n                            sb.Length = 0;\n                            continue;\n                        }\n                    }\n                    sb.Append(i);\n                }\n                if (sb.Length > 0)\n                {\n                    baseType += sb.ToString();\n                }\n                if (genericParams != null && genericParams.Count == 0)\n                    genericParams = null;\n            }\n            else\n                baseType = fullname;\n        }\n\n        string GetAssemblyName(IMetadataScope scope)\n        {\n            return scope is AssemblyNameReference ? ((AssemblyNameReference)scope).FullName : null;\n        }\n\n        internal IType GetType(object token, IType contextType, IMethod contextMethod)\n        {\n            int hash = token.GetHashCode();\n            IType res;\n            if (mapTypeToken.TryGetValue(hash, out res))\n                return res;\n            Mono.Cecil.ModuleDefinition module = null;\n            KeyValuePair<string, IType>[] genericArguments = null;\n            string typename = null;\n            string scope = null;\n            bool dummyGenericInstance = false;\n            if (token is Mono.Cecil.TypeDefinition)\n            {\n                Mono.Cecil.TypeDefinition _def = (token as Mono.Cecil.TypeDefinition);\n                module = _def.Module;\n                typename = _def.FullName;\n                scope = GetAssemblyName(_def.Scope);\n            }\n            else if (token is Mono.Cecil.TypeReference)\n            {\n                Mono.Cecil.TypeReference _ref = (token as Mono.Cecil.TypeReference);\n                if (_ref.IsGenericParameter)\n                {\n                    IType t = null;\n                    if (contextType != null)\n                    {\n                        t = contextType.FindGenericArgument(_ref.Name);\n                    }\n                    if (t == null && contextMethod != null && contextMethod is ILMethod)\n                    {\n                        t = ((ILMethod)contextMethod).FindGenericArgument(_ref.Name);\n                    }\n                    return t;\n                }\n                if (_ref.IsByReference)\n                {\n                    var et = _ref.GetElementType();\n                    bool valid = !et.IsGenericParameter;\n                    var t = GetType(et, contextType, contextMethod);\n                    if (t != null)\n                    {\n                        res = t.MakeByRefType();\n                        if (res is ILType && valid)\n                        {\n                            ///Unify the TypeReference\n                            ((ILType)res).TypeReference = _ref;\n                        }\n                        if (valid)\n                            mapTypeToken[hash] = res;\n                        if (!string.IsNullOrEmpty(res.FullName))\n                            mapType[res.FullName] = res;\n                        return res;\n                    }\n                    return null;\n                }\n                if (_ref.IsArray)\n                {\n                    var t = GetType(_ref.GetElementType(), contextType, contextMethod);\n                    if (t != null)\n                    {\n                        res = t.MakeArrayType();\n                        if (res is ILType)\n                        {\n                            ///Unify the TypeReference\n                            ((ILType)res).TypeReference = _ref;\n                        }\n                        mapTypeToken[hash] = res;\n                        if (!string.IsNullOrEmpty(res.FullName))\n                            mapType[res.FullName] = res;\n                        return res;\n                    }\n                    return t;\n                }\n                module = _ref.Module;\n                if (_ref.IsGenericInstance)\n                {\n                    GenericInstanceType gType = (GenericInstanceType)_ref;\n                    typename = gType.ElementType.FullName;\n                    scope = GetAssemblyName(gType.ElementType.Scope);\n                    TypeReference tr = gType.ElementType;\n                    genericArguments = new KeyValuePair<string, IType>[gType.GenericArguments.Count];\n                    for (int i = 0; i < genericArguments.Length; i++)\n                    {\n                        string key = tr.GenericParameters[i].Name;\n                        IType val;\n                        if (gType.GenericArguments[i].IsGenericParameter)\n                        {\n                            val = contextType.FindGenericArgument(gType.GenericArguments[i].Name);\n                            dummyGenericInstance = true;\n                            if (val == null)\n                            {\n                                if (contextMethod != null && contextMethod is ILMethod)\n                                {\n                                    val = ((ILMethod)contextMethod).FindGenericArgument(gType.GenericArguments[i].Name);\n                                }\n                                else\n                                    return null;\n                            }\n                        }\n                        else\n                            val = GetType(gType.GenericArguments[i], contextType, contextMethod);\n                        if (val != null && val.HasGenericParameter)\n                            dummyGenericInstance = true;\n                        if (val != null)\n                            genericArguments[i] = new KeyValuePair<string, IType>(key, val);\n                        else\n                        {\n                            genericArguments = null;\n                            break;\n                        }\n                    }\n                }\n                else\n                {\n                    typename = _ref.FullName;\n                    scope = GetAssemblyName(_ref.Scope);\n                }\n            }\n            else\n            {\n                throw new NotImplementedException();\n            }\n            res = GetType(typename);\n            if (res == null)\n            {\n                typename = typename.Replace(\"/\", \"+\");\n                res = GetType(typename);\n            }\n            if (res == null && scope != null)\n                res = GetType(typename + \", \" + scope);\n            if (res == null)\n            {\n                if (scope != null)\n                {\n                    string aname = scope.Split(',')[0];\n                    foreach (var i in loadedAssemblies)\n                    {\n                        if (aname == i.GetName().Name)\n                        {\n                            res = GetType(typename + \", \" + i.FullName);\n                            if (res != null)\n                                break;\n                        }\n                    }\n                }\n                if (res == null)\n                {\n                    foreach (var j in loadedAssemblies)\n                    {\n                        res = GetType(typename + \", \" + j.FullName);\n                        if (res != null)\n                            break;\n                    }\n                }\n                if (res != null && scope != null)\n                {\n                    mapType[typename + \", \" + scope] = res;\n                }\n            }\n            if (res == null)\n                throw new KeyNotFoundException(\"Cannot find Type:\" + typename);\n            if (genericArguments != null)\n            {\n                res = res.MakeGenericInstance(genericArguments);\n                if (!dummyGenericInstance && res is ILType)\n                {\n                    ((ILType)res).TypeReference = (TypeReference)token;\n                }\n                if (!string.IsNullOrEmpty(res.FullName))\n                {\n                    if (res is CLRType || !((ILType)res).TypeReference.HasGenericParameters)\n                        mapType[res.FullName] = res;\n                }\n            }\n            mapTypeToken[res.GetHashCode()] = res;\n            if (!dummyGenericInstance)\n                mapTypeToken[hash] = res;\n            return res;\n        }\n\n        public IType GetType(int hash)\n        {\n            IType res;\n            if (mapTypeToken.TryGetValue(hash, out res))\n                return res;\n            else\n                return null;\n        }\n\n        /// <summary>\n        /// 根据CLR类型获取 IL类型\n        /// </summary>\n        /// <param name=\"t\"></param>\n        /// <returns></returns>\n        public IType GetType(Type t)\n        {\n            IType res;\n            if (clrTypeMapping.TryGetValue(t, out res))\n                return res;\n            else\n                return GetType(t.AssemblyQualifiedName);\n        }\n\n        /// <summary>\n        /// Create a instance of the specified type, which is inherited from a CLR Type\n        /// </summary>\n        /// <typeparam name=\"T\">CLR Type</typeparam>\n        /// <param name=\"type\">Full Name of the type</param>\n        /// <param name=\"args\">Arguments for the constructor</param>\n        /// <returns></returns>\n        public T Instantiate<T>(string type, object[] args = null)\n        {\n            ILTypeInstance ins = Instantiate(type, args);\n            return (T)ins.CLRInstance;\n        }\n\n        /// <summary>\n        /// Create a instance of the specified type\n        /// </summary>\n        /// <param name=\"type\">Full Name of the type</param>\n        /// <param name=\"args\">Arguments for the constructor</param>\n        /// <returns></returns>\n        public ILTypeInstance Instantiate(string type, object[] args = null)\n        {\n            IType t;\n            if (mapType.TryGetValue(type, out t))\n            {\n                ILType ilType = t as ILType;\n                if(ilType != null)\n                {\n                    bool hasConstructor = args != null && args.Length != 0;\n                    var res = ilType.Instantiate(!hasConstructor);\n                    if (hasConstructor)\n                    {\n                        var ilm = ilType.GetConstructor(args.Length);\n                        Invoke(ilm, res, args);\n                    }\n                    return res;\n                }\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Invoke a method\n        /// </summary>\n        /// <param name=\"type\">Type's fullname</param>\n        /// <param name=\"method\">Method name</param>\n        /// <param name=\"p\">Parameters</param>\n        /// <returns></returns>\n        public object Invoke(string type, string method, object instance, params object[] p)\n        {\n            IType t = GetType(type);\n            if (t == null)\n                return null;\n            var m = t.GetMethod(method, p != null ? p.Length : 0);            \n            if (m != null)\n            {\n                for(int i = 0; i < m.ParameterCount; i++)\n                {\n                    if (p[i] == null)\n                        continue;\n                    if (!m.Parameters[i].TypeForCLR.IsAssignableFrom(p[i].GetType()))\n                    {\n                        throw new ArgumentException(\"Parameter type mismatch\");\n                    }\n                }\n                return Invoke(m, instance, p);\n            }\n            return null;\n        }\n\n        /// <summary>\n        /// Invoke a generic method\n        /// </summary>\n        /// <param name=\"type\">Type's fullname</param>\n        /// <param name=\"method\">Method name</param>\n        /// <param name=\"genericArguments\">Generic Arguments</param>\n        /// <param name=\"instance\">Object Instance of the method</param>\n        /// <param name=\"p\">Parameters</param>\n        /// <returns></returns>\n        public object InvokeGenericMethod(string type, string method, IType[] genericArguments, object instance, params object[] p)\n        {\n            IType t = GetType(type);\n            if (t == null)\n                return null;\n            var m = t.GetMethod(method, p.Length);\n\n            if (m != null)\n            {\n                m = m.MakeGenericMethod(genericArguments);\n                return Invoke(m, instance, p);\n            }\n            return null;\n        }\n\n        /// <summary>\n        /// Invokes a specific method\n        /// </summary>\n        /// <param name=\"m\">Method</param>\n        /// <param name=\"instance\">object instance</param>\n        /// <param name=\"p\">Parameters</param>\n        /// <returns></returns>\n        public object Invoke(IMethod m, object instance, params object[] p)\n        {\n            object res = null;\n            if (m is ILMethod)\n            {\n                ILIntepreter inteptreter = null;\n                lock (freeIntepreters)\n                {\n                    if (freeIntepreters.Count > 0)\n                    {\n                        inteptreter = freeIntepreters.Dequeue();\n                        //Clear debug state, because it may be in ShouldBreak State\n                        inteptreter.ClearDebugState();\n                    }\n                    else\n                    {\n                        inteptreter = new ILIntepreter(this);\n#if DEBUG\n                        intepreters[inteptreter.GetHashCode()] = inteptreter;\n                        debugService.ThreadStarted(inteptreter);\n#endif\n                    }\n                }\n                try\n                {\n                    res = inteptreter.Run((ILMethod)m, instance, p);\n                }\n                finally\n                {\n                    lock (freeIntepreters)\n                    {\n#if DEBUG\n                        if(inteptreter.CurrentStepType!= StepTypes.None)\n                        {\n                            //We should resume all other threads if we are currently doing stepping operation\n                            foreach(var i in intepreters)\n                            {\n                                if(i.Value != inteptreter)\n                                {\n                                    i.Value.ClearDebugState();\n                                    i.Value.Resume();\n                                }\n                            }\n                            inteptreter.ClearDebugState();\n                        }\n#endif\n                        inteptreter.Stack.ManagedStack.Clear();\n                        inteptreter.Stack.Frames.Clear();\n                        freeIntepreters.Enqueue(inteptreter);\n#if DEBUG\n                        //debugService.ThreadEnded(inteptreter);\n#endif\n\n                    }\n                }\n            }\n\n            return res;\n        }\n\n        internal IMethod GetMethod(object token, ILType contextType,ILMethod contextMethod, out bool invalidToken)\n        {\n            string methodname = null;\n            string typename = null;\n            List<IType> paramList = null;\n            int hashCode = token.GetHashCode();\n            IMethod method;\n            IType[] genericArguments = null;\n            IType returnType;\n            invalidToken = false;\n            bool isConstructor = false;\n            if (mapMethod.TryGetValue(hashCode, out method))\n                return method;\n            IType type = null;\n            if (token is Mono.Cecil.MethodReference)\n            {\n                Mono.Cecil.MethodReference _ref = (token as Mono.Cecil.MethodReference);\n                if (_ref.FullName == \"System.Void System.Object::.ctor()\")\n                {\n                    mapMethod[hashCode] = null;\n                    return null;\n                }\n                if (_ref.FullName == \"System.Void System.Attribute::.ctor()\")\n                {\n                    mapMethod[hashCode] = null;\n                    return null;\n                }\n                methodname = _ref.Name;\n                var typeDef = _ref.DeclaringType;\n\n                type = GetType(typeDef, contextType, contextMethod);\n                if (type == null)\n                    throw new KeyNotFoundException(\"Cannot find type:\" + typename);\n\n                if (token is Mono.Cecil.MethodDefinition)\n                {\n                    var def = _ref as MethodDefinition;\n                    isConstructor = def.IsConstructor;\n                }\n                else\n                    isConstructor = methodname == \".ctor\";\n\n                if (_ref.IsGenericInstance)\n                {\n                    GenericInstanceMethod gim = (GenericInstanceMethod)_ref;\n                    genericArguments = new IType[gim.GenericArguments.Count];\n                    for (int i = 0; i < genericArguments.Length; i++)\n                    {\n                        if (gim.GenericArguments[i].IsGenericParameter)\n                            invalidToken = true;\n                        var gt = GetType(gim.GenericArguments[i], contextType, contextMethod);\n                        if (gt == null)\n                        {\n                            gt = contextMethod.FindGenericArgument(gim.GenericArguments[i].Name);\n                            if (gt == null)//This means it contains unresolved generic arguments, which means it's not searching the generic instance\n                            {\n                                genericArguments = null;\n                                break;\n                            }\n                            else\n                                genericArguments[i] = gt;\n                        }\n                        else\n                            genericArguments[i] = gt;\n                    }\n                }\n                if (!invalidToken && typeDef.IsGenericInstance)\n                {\n                    GenericInstanceType gim = (GenericInstanceType)typeDef;\n                    for (int i = 0; i < gim.GenericArguments.Count; i++)\n                    {\n                        if (gim.GenericArguments[0].IsGenericParameter)\n                        {\n                            invalidToken = true;\n                            break;\n                        }\n                    }\n                }\n                paramList = _ref.GetParamList(this, contextType, contextMethod, genericArguments);\n                returnType = GetType(_ref.ReturnType, type, null);\n                if (returnType == null)\n                    returnType = GetType(_ref.ReturnType, contextType, null);\n            }\n            else\n            {\n                throw new NotImplementedException();\n                //Mono.Cecil.GenericInstanceMethod gmethod = _def as Mono.Cecil.GenericInstanceMethod;\n                //genlist = new MethodParamList(environment, gmethod);\n            }\n\n            if (isConstructor)\n                method = type.GetConstructor(paramList);\n            else\n            {\n                method = type.GetMethod(methodname, paramList, genericArguments, returnType, true);\n            }\n\n            if (method == null)\n            {\n                if (isConstructor && contextType.FirstCLRBaseType != null && contextType.FirstCLRBaseType is CrossBindingAdaptor && type.TypeForCLR == ((CrossBindingAdaptor)contextType.FirstCLRBaseType).BaseCLRType)\n                {\n                    method = contextType.BaseType.GetConstructor(paramList);\n                    if (method == null)\n                        throw new KeyNotFoundException(string.Format(\"Cannot find method:{0} in type:{1}, token={2}\", methodname, type.FullName, token));\n                    invalidToken = true;\n                    mapMethod[method.GetHashCode()] = method;\n                }\n                else\n                    throw new KeyNotFoundException(string.Format(\"Cannot find method:{0} in type:{1}, token={2}\", methodname, type.FullName, token));\n            }\n            if (!invalidToken)\n                mapMethod[hashCode] = method;\n            else\n                mapMethod[method.GetHashCode()] = method;\n            return method;\n        }\n\n        internal IMethod GetMethod(int tokenHash)\n        {\n            IMethod res;\n            if (mapMethod.TryGetValue(tokenHash, out res))\n                return res;\n\n            return null;\n        }\n\n        internal long GetStaticFieldIndex(object token, IType contextType, IMethod contextMethod)\n        {\n            FieldReference f = token as FieldReference;\n            var type = GetType(f.DeclaringType, contextType, contextMethod);\n\n            if (type is ILType)\n            {\n                var it = type as ILType;\n                int idx = it.GetFieldIndex(token);\n                long res = 0;\n                if (it.TypeReference.HasGenericParameters)\n                {\n                    mapTypeToken[type.GetHashCode()] = it;\n                    res = ((long)type.GetHashCode() << 32) | (uint)idx;\n                }\n                else\n                {\n                    res = ((long)it.TypeReference.GetHashCode() << 32) | (uint)idx;\n                }\n\n                return res;\n            }\n            else\n            {\n                int idx = type.GetFieldIndex(token);\n                long res = ((long)type.GetHashCode() << 32) | (uint)idx;\n\n                return res;\n            }\n        }\n\n        internal long CacheString(object token)\n        {\n            long oriHash = token.GetHashCode();\n            long hashCode = oriHash;\n            string str = (string)token;\n            lock (mapString)\n            {\n                bool isCollision = CheckStringCollision(hashCode, str);\n                long cnt = 0;\n                while (isCollision)\n                {\n                    cnt++;\n                    hashCode = cnt << 32 | oriHash;\n                    isCollision = CheckStringCollision(hashCode, str);\n                }\n                mapString[hashCode] = (string)token;\n            }\n            return hashCode;\n        }\n\n        bool CheckStringCollision(long hashCode, string newStr)\n        {\n            string oldVal;\n            if (mapString.TryGetValue(hashCode, out oldVal))\n                return oldVal != newStr;\n            return false;\n        }\n\n        internal string GetString(long hashCode)\n        {\n            string res = null;\n            if (mapString.TryGetValue(hashCode, out res))\n                return res;\n            return res;\n        }\n\n        public void RegisterCrossBindingAdaptor(CrossBindingAdaptor adaptor)\n        {\n            var bType = adaptor.BaseCLRType;\n            \n            if (bType != null)\n            {\n                if (!crossAdaptors.ContainsKey(bType))\n                {\n                    var t = adaptor.AdaptorType;\n                    var res = GetType(t);\n                    if (res == null)\n                    {\n                        res = new CLRType(t, this);\n                        mapType[res.FullName] = res;\n                        mapType[t.AssemblyQualifiedName] = res;\n                        clrTypeMapping[t] = res;\n                    }\n                    adaptor.RuntimeType = res;\n                    crossAdaptors[bType] = adaptor;\n                }\n                else\n                    throw new Exception(\"Crossbinding Adapter for \" + bType.FullName + \" is already added.\");\n            }\n            else\n            {\n                var bTypes = adaptor.BaseCLRTypes;\n                var t = adaptor.AdaptorType;\n                var res = GetType(t);\n                if (res == null)\n                {\n                    res = new CLRType(t, this);\n                    mapType[res.FullName] = res;\n                    mapType[t.AssemblyQualifiedName] = res;\n                    clrTypeMapping[t] = res;\n                }\n                adaptor.RuntimeType = res;\n\n                foreach (var i in bTypes)\n                {\n                    if (!crossAdaptors.ContainsKey(i))\n                    {\n                        crossAdaptors[i] = adaptor;\n                    }\n                    else\n                        throw new Exception(\"Crossbinding Adapter for \" + i.FullName + \" is already added.\");\n                }\n            } \n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Enviorment/CLRRedirections.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.Utils;\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Reflection;\n\nnamespace ILRuntime.Runtime.Enviorment\n{\n    unsafe static class CLRRedirections\n    {\n        public static StackObject* CreateInstance(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            IType[] genericArguments = method.GenericArguments;\n            if (genericArguments != null && genericArguments.Length == 1)\n            {\n                var t = genericArguments[0];\n                if (t is ILType)\n                {\n                    return ILIntepreter.PushObject(esp, mStack, ((ILType)t).Instantiate());\n                }\n                else\n                    return ILIntepreter.PushObject(esp, mStack, ((CLRType)t).CreateDefaultInstance());\n            }\n            else\n                throw new EntryPointNotFoundException();\n        }\n        /*public static object CreateInstance(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            if (genericArguments != null && genericArguments.Length == 1)\n            {\n                var t = genericArguments[0];\n                if (t is ILType)\n                {\n                    return ((ILType)t).Instantiate();\n                }\n                else\n                    return Activator.CreateInstance(t.TypeForCLR);\n            }\n            else\n                throw new EntryPointNotFoundException();\n        }*/\n\n        public static StackObject* CreateInstance2(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            var p = esp - 1;\n            var t = mStack[p->Value] as Type;\n            intp.Free(p);\n            if (t != null)\n            {\n                if (t is ILRuntimeType)\n                {\n                    return ILIntepreter.PushObject(p, mStack, ((ILRuntimeType)t).ILType.Instantiate());\n                }\n                else\n                    return ILIntepreter.PushObject(p, mStack, Activator.CreateInstance(t));\n            }\n            else\n                return ILIntepreter.PushNull(p);\n        }\n\n        /*public static object CreateInstance2(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var t = param[0] as Type;\n            if (t != null)\n            {\n                if (t is ILRuntimeType)\n                {\n                    return ((ILRuntimeType)t).ILType.Instantiate();\n                }\n                else\n                    return Activator.CreateInstance(t);\n            }\n            else\n                return null;\n        }*/\n\n        public static StackObject* GetType(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            var p = esp - 1;\n            AppDomain dommain = intp.AppDomain;\n            string fullname = (string)StackObject.ToObject(p, dommain, mStack); ;\n            intp.Free(p);\n            var t = intp.AppDomain.GetType(fullname);\n            if (t != null)\n                return ILIntepreter.PushObject(p, mStack, t.ReflectionType);\n            else\n                return ILIntepreter.PushNull(p);\n        }\n\n        public static StackObject* TypeEquals(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            var ret = ILIntepreter.Minus(esp, 2);\n            var p = esp - 1;\n            AppDomain dommain = intp.AppDomain;\n            var other = StackObject.ToObject(p, dommain, mStack);\n            intp.Free(p);\n            p = ILIntepreter.Minus(esp, 2);\n            var instance = StackObject.ToObject(p, dommain, mStack);\n            intp.Free(p);\n            if(instance is ILRuntimeType)\n            {\n                if (other is ILRuntimeType)\n                {\n                    if(((ILRuntimeType)instance).ILType == ((ILRuntimeType)other).ILType)\n                        return ILIntepreter.PushOne(ret);\n                    else\n                        return ILIntepreter.PushZero(ret);\n                }\n                else\n                    return ILIntepreter.PushZero(ret);\n            }\n            else\n            {\n                if(((Type)typeof(Type).CheckCLRTypes(instance)).Equals(((Type)typeof(Type).CheckCLRTypes(other))))\n                    return ILIntepreter.PushOne(ret);\n                else\n                    return ILIntepreter.PushZero(ret);\n            }\n        }\n\n        /*public static object GetType(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var t = ctx.AppDomain.GetType((string)param[0]);\n            if (t != null)\n                return t.ReflectionType;\n            else\n                return null;\n        }*/\n\n        public unsafe static StackObject* InitializeArray(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            var ret = esp - 1 - 1;\n            AppDomain domain = intp.AppDomain;\n            var param = esp - 1;\n            byte[] data = StackObject.ToObject(param, domain, mStack) as byte[];\n            intp.Free(param);\n            param = esp - 1 - 1;\n            object array = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            if (data == null)\n                return ret;\n            fixed (byte* p = data)\n            {\n                if (array is int[])\n                {\n                    int[] arr = array as int[];\n                    int* ptr = (int*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is byte[])\n                {\n                    byte[] arr = array as byte[];\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = p[i];\n                    }\n                }\n                else if (array is sbyte[])\n                {\n                    sbyte[] arr = array as sbyte[];\n                    sbyte* ptr = (sbyte*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is short[])\n                {\n                    short[] arr = array as short[];\n                    short* ptr = (short*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is ushort[])\n                {\n                    ushort[] arr = array as ushort[];\n                    ushort* ptr = (ushort*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is char[])\n                {\n                    char[] arr = array as char[];\n                    char* ptr = (char*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is uint[])\n                {\n                    uint[] arr = array as uint[];\n                    uint* ptr = (uint*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is Int64[])\n                {\n                    long[] arr = array as long[];\n                    long* ptr = (long*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is UInt64[])\n                {\n                    ulong[] arr = array as ulong[];\n                    ulong* ptr = (ulong*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is float[])\n                {\n                    float[] arr = array as float[];\n                    float* ptr = (float*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is double[])\n                {\n                    double[] arr = array as double[];\n                    double* ptr = (double*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is bool[])\n                {\n                    bool[] arr = array as bool[];\n                    bool* ptr = (bool*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else\n                {\n                    throw new NotImplementedException(\"array=\" + array.GetType());\n                }\n            }\n\n            return ret;\n        }\n\n        /*public unsafe static object InitializeArray(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            object array = param[0];\n            byte[] data = param[1] as byte[];\n            if (data == null)\n                return null;\n            fixed (byte* p = data)\n            {\n                if (array is int[])\n                {\n                    int[] arr = array as int[];\n                    int* ptr = (int*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is byte[])\n                {\n                    byte[] arr = array as byte[];\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = p[i];\n                    }\n                }\n                else if (array is sbyte[])\n                {\n                    sbyte[] arr = array as sbyte[];\n                    sbyte* ptr = (sbyte*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is short[])\n                {\n                    short[] arr = array as short[];\n                    short* ptr = (short*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is ushort[])\n                {\n                    ushort[] arr = array as ushort[];\n                    ushort* ptr = (ushort*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is char[])\n                {\n                    char[] arr = array as char[];\n                    char* ptr = (char*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is uint[])\n                {\n                    uint[] arr = array as uint[];\n                    uint* ptr = (uint*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is Int64[])\n                {\n                    long[] arr = array as long[];\n                    long* ptr = (long*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is UInt64[])\n                {\n                    ulong[] arr = array as ulong[];\n                    ulong* ptr = (ulong*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is float[])\n                {\n                    float[] arr = array as float[];\n                    float* ptr = (float*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is double[])\n                {\n                    double[] arr = array as double[];\n                    double* ptr = (double*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else if (array is bool[])\n                {\n                    bool[] arr = array as bool[];\n                    bool* ptr = (bool*)p;\n                    for (int i = 0; i < arr.Length; i++)\n                    {\n                        arr[i] = ptr[i];\n                    }\n                }\n                else\n                {\n                    throw new NotImplementedException(\"array=\" + array.GetType());\n                }\n            }\n\n            return null;\n        }*/\n\n        public unsafe static StackObject* DelegateCombine(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            //Don't ask me why not esp -2, unity won't return the right result\n            var ret = esp - 1 - 1;\n            AppDomain domain = intp.AppDomain;\n            var param = esp - 1;\n            object dele2 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = esp - 1 - 1;\n            object dele1 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n            \n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            var dele = ((IDelegateAdapter)dele1);\n                            //This means it's the original delegate which should be untouch\n                            if (!dele.IsClone)\n                            {\n                                dele = dele.Clone();\n                            }\n                            if(!((IDelegateAdapter)dele2).IsClone)\n                            {\n                                dele2 = ((IDelegateAdapter)dele2).Clone();\n                            }\n                            dele.Combine((IDelegateAdapter)dele2);\n                            return ILIntepreter.PushObject(ret, mStack, dele);\n                        }\n                        else\n                        {\n                            if (!((IDelegateAdapter)dele1).IsClone)\n                            {\n                                dele1 = ((IDelegateAdapter)dele1).Clone();\n                            }\n                            ((IDelegateAdapter)dele1).Combine((Delegate)dele2);\n                            return ILIntepreter.PushObject(ret, mStack, dele1);\n                        }\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return ILIntepreter.PushObject(ret, mStack, Delegate.Combine((Delegate)dele1, ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType())));\n                        else\n                            return ILIntepreter.PushObject(ret, mStack, Delegate.Combine((Delegate)dele1, (Delegate)dele2));\n                    }\n                }\n                else\n                    return ILIntepreter.PushObject(ret, mStack, dele1);\n            }\n            else\n                return ILIntepreter.PushObject(ret, mStack, dele2);\n        }\n\n        /*public unsafe static object DelegateCombine(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var esp = ctx.ESP;\n            var mStack = ctx.ManagedStack;\n            var domain = ctx.AppDomain;\n\n            //Don't ask me why not esp -2, unity won't return the right result\n            var dele1 = StackObject.ToObject((esp - 1 - 1), domain, mStack);\n            var dele2 = StackObject.ToObject((esp - 1), domain, mStack);\n\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            var dele = ((IDelegateAdapter)dele1);\n                            //This means it's the default delegate which should be singleton to support == operator\n                            if (dele.Next == null)\n                            {\n                                dele = dele.Instantiate(domain, dele.Instance, dele.Method);\n                            }\n                            dele.Combine((IDelegateAdapter)dele2);\n                            return dele;\n                        }\n                        else\n                        {\n                            ((IDelegateAdapter)dele1).Combine((Delegate)dele2);\n                            return dele1;\n                        }\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return Delegate.Combine((Delegate)dele1, ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType()));\n                        else\n                            return Delegate.Combine((Delegate)dele1, (Delegate)dele2);\n                    }\n                }\n                else\n                    return dele1;\n            }\n            else\n                return dele2;\n        }*/\n\n        public unsafe static StackObject* DelegateRemove(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            //Don't ask me why not esp -2, unity won't return the right result\n            var ret = esp - 1 - 1;\n            AppDomain domain = intp.AppDomain;\n            var param = esp - 1;\n            object dele2 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = esp - 1 - 1;\n            object dele1 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            if (((IDelegateAdapter)dele1).Equals((IDelegateAdapter)dele2))\n                                return ILIntepreter.PushObject(ret, mStack, ((IDelegateAdapter)dele1).Next);\n                            else\n                                ((IDelegateAdapter)dele1).Remove((IDelegateAdapter)dele2);\n                        }\n                        else\n                            ((IDelegateAdapter)dele1).Remove((Delegate)dele2);\n                        return ILIntepreter.PushObject(ret, mStack, dele1);\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return ILIntepreter.PushObject(ret, mStack, Delegate.Remove((Delegate)dele1, ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType())));\n                        else\n                            return ILIntepreter.PushObject(ret, mStack, Delegate.Remove((Delegate)dele1, (Delegate)dele2));\n                    }\n                }\n                else\n                    return ILIntepreter.PushObject(ret, mStack, dele1);\n            }\n            else\n                return ILIntepreter.PushNull(ret);\n        }\n\n        /*public unsafe static object DelegateRemove(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var esp = ctx.ESP;\n            var mStack = ctx.ManagedStack;\n            var domain = ctx.AppDomain;\n\n            var dele1 = StackObject.ToObject((esp - 1 - 1), domain, mStack);\n            var dele2 = StackObject.ToObject((esp - 1), domain, mStack);\n\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            if (dele1 == dele2)\n                                return ((IDelegateAdapter)dele1).Next;\n                            else\n                                ((IDelegateAdapter)dele1).Remove((IDelegateAdapter)dele2);\n                        }\n                        else\n                            ((IDelegateAdapter)dele1).Remove((Delegate)dele2);\n                        return dele1;\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return Delegate.Remove((Delegate)dele1, ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType()));\n                        else\n                            return Delegate.Remove((Delegate)dele1, (Delegate)dele2);\n                    }\n                }\n                else\n                    return dele1;\n            }\n            else\n                return null;\n        }*/\n\n        public unsafe static StackObject* DelegateEqulity(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            //Don't ask me why not esp -2, unity won't return the right result\n            var ret = esp - 1 - 1;\n            AppDomain domain = intp.AppDomain;\n            var param = esp - 1;\n            object dele2 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = esp - 1 - 1;\n            object dele1 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            bool res = false;\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            res = ((IDelegateAdapter)dele1).Equals((IDelegateAdapter)dele2);\n                        else\n                            res = ((IDelegateAdapter)dele1).Equals((Delegate)dele2);\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            res = (Delegate)dele1 == ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType());\n                        }\n                        else\n                            res = (Delegate)dele1 == (Delegate)dele2;\n                    }\n                }\n                else\n                    res = dele1 == null;\n            }\n            else\n                res = dele2 == null;\n\n            if (res)\n                return ILIntepreter.PushOne(ret);\n            else\n                return ILIntepreter.PushZero(ret);\n        }\n\n        /*public unsafe static object DelegateEqulity(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            //op_Equality,op_Inequality\n            var esp = ctx.ESP;\n            var mStack = ctx.ManagedStack;\n            var domain = ctx.AppDomain;\n\n            var dele1 = StackObject.ToObject((esp - 1 - 1), domain, mStack);\n            var dele2 = StackObject.ToObject((esp - 1), domain, mStack);\n\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return ((IDelegateAdapter)dele1).Equals((IDelegateAdapter)dele2);\n                        else\n                            return ((IDelegateAdapter)dele1).Equals((Delegate)dele2);\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                        {\n                            return (Delegate)dele1 == ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType());\n                        }\n                        else\n                            return (Delegate)dele1 == (Delegate)dele2;\n                    }\n                }\n                else\n                    return dele1 == null;\n            }\n            else\n                return dele2 == null;\n        }*/\n\n        public unsafe static StackObject* DelegateInequlity(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            //Don't ask me why not esp -2, unity won't return the right result\n            var ret = esp - 1 - 1;\n            AppDomain domain = intp.AppDomain;\n            var param = esp - 1;\n            object dele2 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = esp - 1 - 1;\n            object dele1 = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            bool res = false;\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            res = !((IDelegateAdapter)dele1).Equals((IDelegateAdapter)dele2);\n                        else\n                            res = !((IDelegateAdapter)dele1).Equals((Delegate)dele2);\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            res = (Delegate)dele1 != ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType());\n                        else\n                            res = (Delegate)dele1 != (Delegate)dele2;\n                    }\n                }\n                else\n                    res = dele1 != null;\n            }\n            else\n                res = dele2 != null;\n            if (res)\n                return ILIntepreter.PushOne(ret);\n            else\n                return ILIntepreter.PushZero(ret);\n        }\n\n        /*public unsafe static object DelegateInequlity(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            //op_Equality,op_Inequality\n            var esp = ctx.ESP;\n            var mStack = ctx.ManagedStack;\n            var domain = ctx.AppDomain;\n\n            var dele1 = StackObject.ToObject((esp - 1 - 1), domain, mStack);\n            var dele2 = StackObject.ToObject((esp - 1), domain, mStack);\n\n            if (dele1 != null)\n            {\n                if (dele2 != null)\n                {\n                    if (dele1 is IDelegateAdapter)\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return !((IDelegateAdapter)dele1).Equals((IDelegateAdapter)dele2);\n                        else\n                            return !((IDelegateAdapter)dele1).Equals((Delegate)dele2);\n                    }\n                    else\n                    {\n                        if (dele2 is IDelegateAdapter)\n                            return (Delegate)dele1 != ((IDelegateAdapter)dele2).GetConvertor(dele1.GetType());\n                        else\n                            return (Delegate)dele1 != (Delegate)dele2;\n                    }\n                }\n                else\n                    return dele1 != null;\n            }\n            else\n                return dele2 != null;\n        }*/\n\n        public static StackObject* GetTypeFromHandle(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            //Nothing to do\n            return esp;\n        }\n\n        /*public static object GetTypeFromHandle(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            return param[0];\n        }*/\n\n        public unsafe static StackObject* MethodInfoInvoke(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            AppDomain domain = intp.AppDomain;\n            //Don't ask me why not esp - 3, unity won't return the right result\n            var ret = ILIntepreter.Minus(esp, 3);\n            var param = esp - 1;\n            var p = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = esp - 1 - 1;\n            var obj = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            param = ILIntepreter.Minus(esp, 3);\n            object instance = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n\n            if (instance is ILRuntimeMethodInfo)\n            {\n                if (obj != null)\n                    esp = ILIntepreter.PushObject(ret, mStack, obj);\n                else\n                    esp = ret;\n                if (p != null)\n                {\n                    object[] arr = (object[])p;\n                    foreach (var i in arr)\n                    {\n                        esp = ILIntepreter.PushObject(esp, mStack, i);\n                    }\n                }\n                bool unhandled;\n                var ilmethod = ((ILRuntimeMethodInfo)instance).ILMethod;\n                return intp.Execute(ilmethod, esp, out unhandled);\n            }\n            else\n                return ILIntepreter.PushObject(ret, mStack, ((MethodInfo)instance).Invoke(obj, (object[])p));\n        }\n\n        /*public unsafe static object MethodInfoInvoke(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var esp = ctx.ESP;\n            var mStack = ctx.ManagedStack;\n            var domain = ctx.AppDomain;\n            var intp = ctx.Interpreter;\n            //Don't ask me why not esp - 3, unity won't return the right result\n            var obj = param[0];\n            var p = param[1];\n\n            if (instance is ILRuntimeMethodInfo)\n            {\n                if (obj != null)\n                    esp = ILIntepreter.PushObject(esp, mStack, obj);\n                if (p != null)\n                {\n                    object[] arr = (object[])p;\n                    foreach (var i in arr)\n                    {\n                        esp = ILIntepreter.PushObject(esp, mStack, i);\n                    }\n                }\n                bool unhandled;\n                var ilmethod = ((ILRuntimeMethodInfo)instance).ILMethod;\n                esp = intp.Execute(ilmethod, esp, out unhandled);\n                object res = null;\n                if (ilmethod.ReturnType != domain.VoidType)\n                {\n                    res = StackObject.ToObject((esp - 1),domain, mStack);\n                    intp.Free(esp - 1);\n                }\n                return res;\n            }\n            else\n                return ((MethodInfo)instance).Invoke(obj, (object[])p);\n        }*/\n\n        public unsafe static StackObject* ObjectGetType(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)\n        {\n            AppDomain domain = intp.AppDomain;\n            var ret = esp - 1;\n            var param = esp - 1;\n            var instance = StackObject.ToObject(param, domain, mStack);\n            intp.Free(param);\n             \n            var type = instance.GetType();\n            if (type == typeof(ILTypeInstance))\n            {\n                return ILIntepreter.PushObject(ret, mStack, ((ILTypeInstance)instance).Type.ReflectionType);\n            }\n            else\n                return ILIntepreter.PushObject(ret, mStack, type);\n        }\n\n        /*public unsafe static object ObjectGetType(ILContext ctx, object instance, object[] param, IType[] genericArguments)\n        {\n            var type = instance.GetType();\n            if (type == typeof(ILTypeInstance))\n            {\n                return ((ILTypeInstance)instance).Type.ReflectionType;\n            }\n            else\n                return type;\n        }*/\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Enviorment/CrossBindingAdaptor.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Runtime.Enviorment\n{\n    public interface CrossBindingAdaptorType\n    {\n        ILTypeInstance ILInstance { get; }\n    }\n    /// <summary>\n    /// This interface is used for inheritance and implementation of CLR Types or interfaces\n    /// </summary>\n    public abstract class CrossBindingAdaptor : IType\n    {\n        IType type;\n        /// <summary>\n        /// This returns the CLR type to be inherited or CLR interface to be implemented\n        /// </summary>\n        public abstract Type BaseCLRType { get; }\n\n        /// <summary>\n        /// If this Adaptor is capable to impelement multuple interfaces, use this Property, AND BaseCLRType should return null\n        /// </summary>\n        public virtual Type[] BaseCLRTypes\n        {\n            get\n            {\n                return null;\n            }\n        }\n\n        public abstract Type AdaptorType { get; }\n\n        public abstract object CreateCLRInstance(Enviorment.AppDomain appdomain, ILTypeInstance instance);\n\n        internal IType RuntimeType { get { return type; } set { type = value; } }\n\n        #region IType Members\n\n        public IMethod GetMethod(string name, int paramCount, bool declaredOnly = false)\n        {\n            return type.GetMethod(name, paramCount, declaredOnly);\n        }\n\n        public IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false)\n        {\n            return type.GetMethod(name, param, genericArguments, returnType, declaredOnly);\n        }\n\n        public List<IMethod> GetMethods()\n        {\n            return type.GetMethods();\n        }\n\n        public int GetFieldIndex(object token)\n        {\n            return type.GetFieldIndex(token);\n        }\n\n        public IMethod GetConstructor(List<IType> param)\n        {\n            return type.GetConstructor(param);\n        }\n\n        public bool CanAssignTo(IType type)\n        {\n            bool res = false;\n            if (BaseType != null)\n                res = BaseType.CanAssignTo(type);\n            var interfaces = Implements;\n            if (!res && interfaces != null)\n            {\n                for (int i = 0; i < interfaces.Length; i++)\n                {\n                    var im = interfaces[i];\n                    res = im.CanAssignTo(type);\n                    if (res)\n                        return true;\n                }\n            }\n            return res;\n        }\n\n        public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)\n        {\n            return type.MakeGenericInstance(genericArguments);\n        }\n\n        public IType MakeByRefType()\n        {\n            return type.MakeByRefType();\n        }\n\n        public IType MakeArrayType()\n        {\n            return type.MakeArrayType();\n        }\n\n        public IType FindGenericArgument(string key)\n        {\n            return type.FindGenericArgument(key);\n        }\n\n        public IType ResolveGenericType(IType contextType)\n        {\n            return type.ResolveGenericType(contextType);\n        }\n\n        public IMethod GetVirtualMethod(IMethod method)\n        {\n            return type.GetVirtualMethod(method);\n        }\n\n        public bool IsGenericInstance\n        {\n            get\n            {\n                return type.IsGenericInstance;\n            }\n        }\n\n        public KeyValuePair<string, IType>[] GenericArguments\n        {\n            get\n            {\n                return type.GenericArguments;\n            }\n        }\n\n        public Type TypeForCLR\n        {\n            get\n            {\n                return type.TypeForCLR;\n            }\n        }\n\n        public IType ByRefType\n        {\n            get\n            {\n                return type.ByRefType;\n            }\n        }\n\n        public IType ArrayType\n        {\n            get\n            {\n                return type.ArrayType;\n            }\n        }\n\n        public string FullName\n        {\n            get\n            {\n                return type.FullName;\n            }\n        }\n\n        public string Name\n        {\n            get\n            {\n                return type.Name;\n            }\n        }\n\n        public bool IsValueType\n        {\n            get\n            {\n                return type.IsValueType;\n            }\n        }\n\n        public bool IsPrimitive\n        {\n            get\n            {\n                return type.IsPrimitive;\n            }\n        }\n\n        public bool IsDelegate\n        {\n            get\n            {\n                return type.IsDelegate;\n            }\n        }\n\n        public AppDomain AppDomain\n        {\n            get\n            {\n                return type.AppDomain;\n            }\n        }\n\n        public Type ReflectionType\n        {\n            get\n            {\n                return type.ReflectionType;\n            }\n        }\n\n        public IType BaseType\n        {\n            get\n            {\n                return type.BaseType;\n            }\n        }\n\n        public IType[] Implements\n        {\n            get\n            {\n                return type.Implements;\n            }\n        }\n\n        public bool HasGenericParameter\n        {\n            get\n            {\n                return type.HasGenericParameter;\n            }\n        }\n        public bool IsArray\n        {\n            get { return false; }\n        }\n        #endregion\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Enviorment/DelegateManager.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Other;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Runtime.Enviorment\n{\n    public class DelegateManager\n    {\n        List<DelegateMapNode> methods = new List<DelegateMapNode>();\n        List<DelegateMapNode> functions = new List<DelegateMapNode>();\n        IDelegateAdapter zeroParamMethodAdapter = new MethodDelegateAdapter();\n        IDelegateAdapter dummyAdapter = new DummyDelegateAdapter();\n        Dictionary<Type, Func<Delegate, Delegate>> clrDelegates = new Dictionary<Type, Func<Delegate, Delegate>>(new ByReferenceKeyComparer<Type>());\n        Func<Delegate, Delegate> defaultConverter;\n        Enviorment.AppDomain appdomain;\n        public DelegateManager(Enviorment.AppDomain appdomain)\n        {\n            this.appdomain = appdomain;\n            defaultConverter = DefaultConverterStub;\n        }\n\n        static Delegate DefaultConverterStub(Delegate dele)\n        {\n            return dele;\n        }\n\n        public void RegisterDelegateConvertor<T>(Func<Delegate, Delegate> action)\n        {\n            var type = typeof(T);\n            if (type.IsSubclassOf(typeof(Delegate)))\n            {\n                clrDelegates[type] = action;\n            }\n            else\n                throw new NotSupportedException();\n        }\n\n        public void RegisterMethodDelegate<T1>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new MethodDelegateAdapter<T1>();\n            node.ParameterTypes = new Type[] { typeof(T1) };\n            methods.Add(node);\n            RegisterDelegateConvertor<Action<T1>>(defaultConverter);\n        }\n\n        public void RegisterMethodDelegate<T1, T2>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new MethodDelegateAdapter<T1, T2>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2) };\n            methods.Add(node);\n            RegisterDelegateConvertor<Action<T1, T2>>(defaultConverter);\n        }\n\n        public void RegisterMethodDelegate<T1, T2, T3>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new MethodDelegateAdapter<T1, T2, T3>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2), typeof(T3) };\n            methods.Add(node);\n            RegisterDelegateConvertor<Action<T1, T2, T3>>(defaultConverter);\n        }\n\n        public void RegisterMethodDelegate<T1, T2, T3, T4>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new MethodDelegateAdapter<T1, T2, T3, T4>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) };\n            methods.Add(node);\n            RegisterDelegateConvertor<Action<T1, T2, T3, T4>>(defaultConverter);\n        }\n\n        public void RegisterFunctionDelegate<TResult>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new FunctionDelegateAdapter<TResult>();\n            node.ParameterTypes = new Type[] { typeof(TResult) };\n            functions.Add(node);\n            RegisterDelegateConvertor<Func<TResult>>(defaultConverter);\n        }\n\n        public void RegisterFunctionDelegate<T1, TResult>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new FunctionDelegateAdapter<T1, TResult>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(TResult) };\n            functions.Add(node);\n            RegisterDelegateConvertor<Func<T1, TResult>>(defaultConverter);\n        }\n\n        public void RegisterFunctionDelegate<T1, T2, TResult>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new FunctionDelegateAdapter<T1, T2, TResult>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2), typeof(TResult) };\n            functions.Add(node);\n            RegisterDelegateConvertor<Func<T1, T2, TResult>>(defaultConverter);\n        }\n\n        public void RegisterFunctionDelegate<T1, T2, T3, TResult>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new FunctionDelegateAdapter<T1, T2, T3, TResult>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(TResult) };\n            functions.Add(node);\n            RegisterDelegateConvertor<Func<T1, T2, T3, TResult>>(defaultConverter);\n        }\n\n        public void RegisterFunctionDelegate<T1, T2, T3, T4, TResult>()\n        {\n            DelegateMapNode node = new Enviorment.DelegateManager.DelegateMapNode();\n            node.Adapter = new FunctionDelegateAdapter<T1, T2, T3, T4, TResult>();\n            node.ParameterTypes = new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(TResult) };\n            functions.Add(node);\n            RegisterDelegateConvertor<Func<T1, T2, T3, T4, TResult>>(defaultConverter);\n        }\n\n        internal Delegate ConvertToDelegate(Type clrDelegateType, IDelegateAdapter adapter)\n        {\n            Func<Delegate, Delegate> func;\n            if(adapter is DummyDelegateAdapter)\n            {\n                DelegateAdapter.ThrowAdapterNotFound(adapter.Method);\n                return null;\n            }\n            if (clrDelegates.TryGetValue(clrDelegateType, out func))\n            {\n                return func(adapter.Delegate);\n            }\n            else\n            {\n                StringBuilder sb = new StringBuilder();\n                string clsName, rName;\n                bool isByRef;\n                clrDelegateType.GetClassName(out clsName, out rName, out isByRef);\n                sb.AppendLine(\"Cannot find convertor for \" + rName);\n                sb.AppendLine(\"Please add following code:\");\n                sb.Append(\"appdomain.DelegateManager.RegisterDelegateConvertor<\");\n                sb.Append(rName);\n                sb.AppendLine(\">((act) =>\");\n                sb.AppendLine(\"{\");\n                sb.Append(\"    return new \");\n                sb.Append(rName);\n                sb.Append(\"((\");\n                var mi = clrDelegateType.GetMethod(\"Invoke\");\n                bool first = true;\n                foreach(var i in mi.GetParameters())\n                {\n                    if (first)\n                    {\n                        first = false;\n                    }\n                    else\n                        sb.Append(\", \");\n                    sb.Append(i.Name);\n                }\n                sb.AppendLine(\") =>\");\n                sb.AppendLine(\"    {\");\n                if(mi.ReturnType != appdomain.VoidType.TypeForCLR)\n                {\n                    sb.Append(\"        return ((Func<\");\n                    first = true;\n                    foreach (var i in mi.GetParameters())\n                    {\n                        if (first)\n                        {\n                            first = false;\n                        }\n                        else\n                            sb.Append(\", \");\n                        i.ParameterType.GetClassName(out clsName, out rName, out isByRef);\n                        sb.Append(rName);\n                    }\n                    if (!first)\n                        sb.Append(\", \");\n                    mi.ReturnType.GetClassName(out clsName, out rName, out isByRef);\n                    sb.Append(rName);\n                }\n                else\n                {\n                    sb.Append(\"        ((Action<\");\n                    first = true;\n                    foreach (var i in mi.GetParameters())\n                    {\n                        if (first)\n                        {\n                            first = false;\n                        }\n                        else\n                            sb.Append(\", \");\n                        i.ParameterType.GetClassName(out clsName, out rName, out isByRef);\n                        sb.Append(rName);\n                    }\n                }\n                sb.Append(\">)act)(\");\n                first = true;\n                foreach (var i in mi.GetParameters())\n                {\n                    if (first)\n                    {\n                        first = false;\n                    }\n                    else\n                        sb.Append(\", \");\n                    sb.Append(i.Name);\n                }\n                sb.AppendLine(\");\");\n                sb.AppendLine(\"    });\");\n                sb.AppendLine(\"});\");\n                throw new KeyNotFoundException(sb.ToString());\n            }\n        }\n\n        internal IDelegateAdapter FindDelegateAdapter(ILTypeInstance instance, ILMethod method)\n        {\n            IDelegateAdapter res;\n            if (method.ReturnType == appdomain.VoidType)\n            {\n                if (method.ParameterCount == 0)\n                {\n                    res = zeroParamMethodAdapter.Instantiate(appdomain, instance, method);\n                    if (instance != null)\n                        instance.SetDelegateAdapter(method, res);\n                    return res;\n                }\n                foreach (var i in methods)\n                {\n                    if (i.ParameterTypes.Length == method.ParameterCount)\n                    {\n                        bool match = true;\n                        for (int j = 0; j < method.ParameterCount; j++)\n                        {\n                            if (i.ParameterTypes[j] != method.Parameters[j].TypeForCLR)\n                            {\n                                match = false;\n                                break;\n                            }\n                        }\n                        if (match)\n                        {\n                            res = i.Adapter.Instantiate(appdomain, instance, method);\n                            if (instance != null)\n                                instance.SetDelegateAdapter(method, res);\n                            return res;\n                        }\n                    }\n                }\n            }\n            else\n            {\n                foreach (var i in functions)\n                {\n                    if (i.ParameterTypes.Length == method.ParameterCount + 1)\n                    {\n                        bool match = true;\n                        for (int j = 0; j < method.ParameterCount; j++)\n                        {\n                            if (i.ParameterTypes[j] != method.Parameters[j].TypeForCLR)\n                            {\n                                match = false;\n                                break;\n                            }\n                        }\n                        if (match)\n                        {\n                            if (method.ReturnType.TypeForCLR == i.ParameterTypes[method.ParameterCount])\n                            {\n                                res = i.Adapter.Instantiate(appdomain, instance, method);\n                                if (instance != null)\n                                    instance.SetDelegateAdapter(method, res);\n                                return res;\n                            }\n                        }\n                    }\n                }\n            }\n\n            res = dummyAdapter.Instantiate(appdomain, instance, method);\n            if (instance != null)\n                instance.SetDelegateAdapter(method, res);\n            return res;\n        }\n\n        class DelegateMapNode\n        {\n            public IDelegateAdapter Adapter { get; set; }\n            public Type[] ParameterTypes { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Enviorment/ILContext.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.Runtime.Intepreter;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.CLR.Method;\nnamespace ILRuntime.Runtime.Enviorment\n{\n    public unsafe struct ILContext\n    {\n        public AppDomain AppDomain { get; private set; }\n        public StackObject* ESP { get; private set; }\n        public IList<object> ManagedStack { get; private set; }\n        public IMethod Method { get; private set; }\n        public ILIntepreter Interpreter { get; private set; }\n\n        internal ILContext(AppDomain domain,ILIntepreter intpreter, StackObject* esp, IList<object> mStack, IMethod method)\n        {\n            AppDomain = domain;\n            ESP = esp;\n            ManagedStack = mStack;\n            Method = method;\n            Interpreter = intpreter;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Enviorment/ValueTypeBinder.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Stack;\n\nnamespace ILRuntime.Runtime.Enviorment\n{\n    public unsafe abstract class ValueTypeBinder\n    {\n        CLRType clrType;\n        Enviorment.AppDomain domain;\n\n        public CLRType CLRType\n        {\n            get { return clrType; }\n            set\n            {\n                if (clrType == null)\n                {\n                    clrType = value;\n                    domain = value.AppDomain;\n                }\n                else\n                    throw new NotSupportedException();\n            }\n        }\n\n        public abstract void CopyValueTypeToStack(object ins, StackObject* ptr, IList<object> mStack);\n\n        public abstract object ToObject(StackObject* esp, IList<object> managedStack);\n\n        public virtual void RegisterCLRRedirection(Enviorment.AppDomain appdomain)\n        {\n\n        }\n\n        protected void CopyValueTypeToStack<K>(ref K ins, StackObject* esp, IList<object> mStack)\n            where K : struct\n        {\n            switch (esp->ObjectType)\n            {\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        var dst = *(StackObject**)&esp->Value;\n                        var vb = ((CLRType)domain.GetType(dst->Value)).ValueTypeBinder as ValueTypeBinder<K>;\n                        if (vb != null)\n                        {\n                            vb.CopyValueTypeToStack(ref ins, dst, mStack);\n                        }\n                        else\n                            throw new NotSupportedException();\n                    }\n                    break;\n                case ObjectTypes.Object:\n                    mStack[esp->Value] = ins;\n                    break;\n                default:\n                    throw new NotImplementedException();\n            }\n        }\n\n        protected void AssignFromStack<K>(ref K ins, StackObject* esp, IList<object> mStack)\n            where K : struct\n        {\n            switch (esp->ObjectType)\n            {\n                case ObjectTypes.Null:\n                    throw new NullReferenceException();\n                case ObjectTypes.Object:\n                    ins = (K)mStack[esp->Value];\n                    break;\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        var dst = *(StackObject**)&esp->Value;\n                        var vb = ((CLRType)domain.GetType(dst->Value)).ValueTypeBinder as ValueTypeBinder<K>;\n                        if (vb != null)\n                        {\n                            vb.AssignFromStack(ref ins, dst, mStack);\n                        }\n                        else\n                            throw new NotSupportedException();\n                    }\n                    break;\n                default:\n                    throw new NotImplementedException();\n            }\n        }        \n    }\n\n    public unsafe abstract class ValueTypeBinder<T> : ValueTypeBinder\n        where T : struct\n    {\n        public override unsafe void CopyValueTypeToStack(object ins, StackObject* ptr, IList<object> mStack)\n        {\n            T obj = (T)ins;\n            CopyValueTypeToStack(ref obj, ptr, mStack);\n        }\n\n        public abstract void CopyValueTypeToStack(ref T ins, StackObject* ptr, IList<object> mStack);\n\n        public override unsafe object ToObject(StackObject* esp, IList<object> managedStack)\n        {\n            T obj = new T();\n            AssignFromStack(ref obj, esp, managedStack);\n            return obj;\n        }\n\n        public abstract void AssignFromStack(ref T ins, StackObject* ptr, IList<object> mStack);\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Extensions.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.Runtime.Stack;\n\nnamespace ILRuntime.Runtime\n{\n    static class Extensions\n    {\n        public static void GetClassName(this Type type, out string clsName, out string realClsName, out bool isByRef, bool simpleClassName = false)\n        {\n            isByRef = type.IsByRef;\n            bool isArray = type.IsArray;\n            if (isByRef)\n                type = type.GetElementType();\n            if (isArray)\n                type = type.GetElementType();\n            string realNamespace = null;\n            bool isNestedGeneric = false;\n            if (type.IsNested)\n            {\n                string bClsName, bRealClsName;\n                bool tmp;\n                var rt = type.ReflectedType;\n                if(rt.IsGenericType && rt.IsGenericTypeDefinition)\n                {\n                    if (type.IsGenericType)\n                    {\n                        rt = rt.MakeGenericType(type.GetGenericArguments());\n                        isNestedGeneric = true;\n                    }\n                }\n                GetClassName(rt, out bClsName, out bRealClsName, out tmp);\n                clsName = simpleClassName ? \"\" : bClsName + \"_\";\n                realNamespace = bRealClsName + \".\";\n            }\n            else\n            {\n                clsName = simpleClassName ? \"\" : (!string.IsNullOrEmpty(type.Namespace) ? type.Namespace.Replace(\".\", \"_\") + \"_\" : \"\");\n                realNamespace = !string.IsNullOrEmpty(type.Namespace) ? type.Namespace + \".\" : null;\n            }\n            clsName = clsName + type.Name.Replace(\".\", \"_\").Replace(\"`\", \"_\").Replace(\"<\", \"_\").Replace(\">\", \"_\");\n            bool isGeneric = false;\n            string ga = null;\n            if (type.IsGenericType && !isNestedGeneric)\n            {\n                isGeneric = true;\n                clsName += \"_\";\n                ga = \"<\";\n                var args = type.GetGenericArguments();\n                bool first = true;\n                foreach (var j in args)\n                {\n                    if (first)\n                        first = false;\n                    else\n                    {\n                        clsName += \"_\";\n                        ga += \", \";\n                    }\n                    string a, b;\n                    bool tmp;\n                    GetClassName(j, out a, out b, out tmp, true);\n                    clsName += a;\n                    ga += b;\n                }\n                ga += \">\";\n            }\n            if (!simpleClassName)\n                clsName += \"_Binding\";\n            if (isArray)\n                clsName += \"_Array\";\n\n            realClsName = realNamespace;\n            if (isGeneric)\n            {\n                int idx = type.Name.IndexOf(\"`\");\n                if (idx > 0)\n                {\n                    realClsName += type.Name.Substring(0, idx);\n                    realClsName += ga;\n                }\n                else\n                    realClsName += type.Name;\n            }\n            else\n                realClsName += type.Name;\n\n            if (isArray)\n                realClsName += \"[]\";\n\n        }\n        public static int ToInt32(this object obj)\n        {\n            if (obj is int)\n                return (int)obj;\n            if (obj is float)\n                return (int)(float)obj;\n            if (obj is long)\n                return (int)(long)obj;\n            if (obj is short)\n                return (int)(short)obj;\n            if (obj is double)\n                return (int)(double)obj;\n            if (obj is byte)\n                return (int)(byte)obj;\n            if (obj is Intepreter.ILEnumTypeInstance)\n                return (int)((Intepreter.ILEnumTypeInstance)obj)[0];\n            if (obj is uint)\n                return (int)(uint)obj;\n            if (obj is ushort)\n                return (int)(ushort)obj;\n            if (obj is sbyte)\n                return (int)(sbyte)obj;\n            throw new InvalidCastException();\n        }\n        public static long ToInt64(this object obj)\n        {\n            if (obj is long)\n                return (long)obj;\n            if (obj is int)\n                return (long)(int)obj;\n            if (obj is float)\n                return (long)(float)obj;\n            if (obj is short)\n                return (long)(short)obj;\n            if (obj is double)\n                return (long)(double)obj;\n            if (obj is byte)\n                return (long)(byte)obj;\n            if (obj is uint)\n                return (long)(uint)obj;\n            if (obj is ushort)\n                return (long)(ushort)obj;\n            if (obj is sbyte)\n                return (long)(sbyte)obj;\n            throw new InvalidCastException();\n        }\n        public static short ToInt16(this object obj)\n        {\n            if (obj is short)\n                return (short)obj;\n            if (obj is long)\n                return (short)(long)obj;\n            if (obj is int)\n                return (short)(int)obj;\n            if (obj is float)\n                return (short)(float)obj;\n            if (obj is double)\n                return (short)(double)obj;\n            if (obj is byte)\n                return (short)(byte)obj;\n            if (obj is uint)\n                return (short)(uint)obj;\n            if (obj is ushort)\n                return (short)(ushort)obj;\n            if (obj is sbyte)\n                return (short)(sbyte)obj;\n            throw new InvalidCastException();\n        }\n        public static float ToFloat(this object obj)\n        {\n            if (obj is float)\n                return (float)obj;\n            if (obj is int)\n                return (float)(int)obj;\n            if (obj is long)\n                return (float)(long)obj;\n            if (obj is short)\n                return (float)(short)obj;\n            if (obj is double)\n                return (float)(double)obj;\n            if (obj is byte)\n                return (float)(byte)obj;\n            if (obj is uint)\n                return (float)(uint)obj;\n            if (obj is ushort)\n                return (float)(ushort)obj;\n            if (obj is sbyte)\n                return (float)(sbyte)obj;\n            throw new InvalidCastException();\n        }\n\n        public static double ToDouble(this object obj)\n        {\n            if (obj is double)\n                return (double)obj;\n            if (obj is float)\n                return (float)obj;\n            if (obj is int)\n                return (double)(int)obj;\n            if (obj is long)\n                return (double)(long)obj;\n            if (obj is short)\n                return (double)(short)obj;\n            if (obj is byte)\n                return (double)(byte)obj;\n            if (obj is uint)\n                return (double)(uint)obj;\n            if (obj is ushort)\n                return (double)(ushort)obj;\n            if (obj is sbyte)\n                return (double)(sbyte)obj;\n            throw new InvalidCastException();\n        }\n\n        public static Type GetActualType(this object value)\n        {\n            if (value is ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)\n                return ((ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)value).ILInstance.Type.ReflectionType;\n            if (value is ILRuntime.Runtime.Intepreter.ILTypeInstance)\n                return ((ILRuntime.Runtime.Intepreter.ILTypeInstance)value).Type.ReflectionType;\n            else\n                return value.GetType();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Intepreter/DelegateAdapter.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.Runtime;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.Other;\nusing ILRuntime.Runtime.Enviorment;\n\nnamespace ILRuntime.Runtime.Intepreter\n{\n    #region Functions\n    class FunctionDelegateAdapter<TResult> : DelegateAdapter\n    {\n        Func<TResult> action;\n\n        public FunctionDelegateAdapter()\n        {\n\n        }\n\n        private FunctionDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        TResult InvokeILMethod()\n        {\n            if (method.HasThis)\n                return (TResult)appdomain.Invoke(method, instance, null);\n            else\n                return (TResult)appdomain.Invoke(method, null, null);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new FunctionDelegateAdapter<TResult>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new FunctionDelegateAdapter<TResult>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Func<TResult>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Func<TResult>)dele;\n        }\n    }\n\n    class FunctionDelegateAdapter<T1, TResult> : DelegateAdapter\n    {\n        Func<T1, TResult> action;\n\n        public FunctionDelegateAdapter()\n        {\n\n        }\n\n        private FunctionDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        TResult InvokeILMethod(T1 p1)\n        {\n            if (method.HasThis)\n                return (TResult)appdomain.Invoke(method, instance, p1);\n            else\n                return (TResult)appdomain.Invoke(method, null, p1);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new FunctionDelegateAdapter<T1, TResult>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new FunctionDelegateAdapter<T1, TResult>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Func<T1, TResult>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Func<T1, TResult>)dele;\n        }\n    }\n\n    class FunctionDelegateAdapter<T1, T2, TResult> : DelegateAdapter\n    {\n        Func<T1, T2, TResult> action;\n\n        public FunctionDelegateAdapter()\n        {\n\n        }\n\n        private FunctionDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        TResult InvokeILMethod(T1 p1, T2 p2)\n        {\n            if (method.HasThis)\n                return (TResult)appdomain.Invoke(method, instance, p1, p2);\n            else\n                return (TResult)appdomain.Invoke(method, null, p1, p2);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new FunctionDelegateAdapter<T1, T2, TResult>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new FunctionDelegateAdapter<T1, T2, TResult>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Func<T1, T2, TResult>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Func<T1, T2, TResult>)dele;\n        }\n    }\n\n    class FunctionDelegateAdapter<T1, T2, T3, TResult> : DelegateAdapter\n    {\n        Func<T1, T2, T3, TResult> action;\n\n        public FunctionDelegateAdapter()\n        {\n\n        }\n\n        private FunctionDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        TResult InvokeILMethod(T1 p1, T2 p2, T3 p3)\n        {\n            if (method.HasThis)\n                return (TResult)appdomain.Invoke(method, instance, p1, p2, p3);\n            else\n                return (TResult)appdomain.Invoke(method, null, p1, p2, p3);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new FunctionDelegateAdapter<T1, T2, T3, TResult>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new FunctionDelegateAdapter<T1, T2, T3, TResult>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n        public override void Combine(Delegate dele)\n        {\n            action += (Func<T1, T2, T3, TResult>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Func<T1, T2, T3, TResult>)dele;\n        }\n    }\n\n    class FunctionDelegateAdapter<T1, T2, T3, T4, TResult> : DelegateAdapter\n    {\n        Func<T1, T2, T3, T4, TResult> action;\n\n        public FunctionDelegateAdapter()\n        {\n\n        }\n\n        private FunctionDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        TResult InvokeILMethod(T1 p1, T2 p2, T3 p3, T4 p4)\n        {\n            if (method.HasThis)\n                return (TResult)appdomain.Invoke(method, instance, p1, p2, p3, p4);\n            else\n                return (TResult)appdomain.Invoke(method, null, p1, p2, p3, p4);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new FunctionDelegateAdapter<T1, T2, T3, T4, TResult>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new FunctionDelegateAdapter<T1, T2, T3, T4, TResult>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Func<T1, T2, T3, T4, TResult>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Func<T1, T2, T3, T4, TResult>)dele;\n        }\n    }\n    #endregion\n\n    #region Methods\n    class MethodDelegateAdapter<T1> : DelegateAdapter\n    {\n        Action<T1> action;\n\n        public MethodDelegateAdapter()\n        {\n\n        }\n\n        private MethodDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        void InvokeILMethod(T1 p1)\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, p1);\n            else\n                appdomain.Invoke(method, null, p1);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new MethodDelegateAdapter<T1>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new MethodDelegateAdapter<T1>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Action<T1>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Action<T1>)dele;\n        }\n    }\n\n    class MethodDelegateAdapter<T1, T2> : DelegateAdapter\n    {\n        Action<T1, T2> action;\n\n        public MethodDelegateAdapter()\n        {\n\n        }\n\n        private MethodDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        void InvokeILMethod(T1 p1, T2 p2)\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, p1, p2);\n            else\n                appdomain.Invoke(method, instance, p1, p2);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new MethodDelegateAdapter<T1, T2>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new MethodDelegateAdapter<T1, T2>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Action<T1, T2>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Action<T1, T2>)dele;\n        }\n    }\n\n    class MethodDelegateAdapter<T1, T2, T3> : DelegateAdapter\n    {\n        Action<T1, T2, T3> action;\n\n        public MethodDelegateAdapter()\n        {\n\n        }\n\n        private MethodDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        void InvokeILMethod(T1 p1, T2 p2, T3 p3)\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, p1, p2, p3);\n            else\n                appdomain.Invoke(method, null, p1, p2, p3);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new MethodDelegateAdapter<T1, T2, T3>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new MethodDelegateAdapter<T1, T2, T3>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Action<T1, T2, T3>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Action<T1, T2, T3>)dele;\n        }\n    }\n\n    class MethodDelegateAdapter<T1, T2, T3, T4> : DelegateAdapter\n    {\n        Action<T1, T2, T3, T4> action;\n\n        public MethodDelegateAdapter()\n        {\n\n        }\n\n        private MethodDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        void InvokeILMethod(T1 p1, T2 p2, T3 p3, T4 p4)\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, p1, p2, p3, p4);\n            else\n                appdomain.Invoke(method, null, p1, p2, p3, p4);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new MethodDelegateAdapter<T1, T2, T3, T4>(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new MethodDelegateAdapter<T1, T2, T3, T4>(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Action<T1, T2, T3, T4>)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Action<T1, T2, T3, T4>)dele;\n        }\n    }\n\n    class MethodDelegateAdapter : DelegateAdapter\n    {\n        Action action;\n        \n        public MethodDelegateAdapter()\n        {\n\n        }\n\n        protected MethodDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            action = InvokeILMethod;\n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        void InvokeILMethod()\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, null);\n            else\n                appdomain.Invoke(method, null, null);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new MethodDelegateAdapter(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new MethodDelegateAdapter(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            action += (Action)dele;\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            action -= (Action)dele;\n        }\n    }\n\n    class DummyDelegateAdapter : DelegateAdapter\n    {\n        public DummyDelegateAdapter()\n        {\n\n        }\n\n        protected DummyDelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n            : base(appdomain, instance, method)\n        {\n            \n        }\n\n        public override Delegate Delegate\n        {\n            get\n            {\n                ThrowAdapterNotFound(method);\n                return null;\n            }\n        }\n\n        void InvokeILMethod()\n        {\n            if (method.HasThis)\n                appdomain.Invoke(method, instance, null);\n            else\n                appdomain.Invoke(method, null, null);\n        }\n\n        public override IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            return new DummyDelegateAdapter(appdomain, instance, method);\n        }\n\n        public override IDelegateAdapter Clone()\n        {\n            var res = new DummyDelegateAdapter(appdomain, instance, method);\n            res.isClone = true;\n            return res;\n        }\n\n        public override void Combine(Delegate dele)\n        {\n            ThrowAdapterNotFound(method);\n        }\n\n        public override void Remove(Delegate dele)\n        {\n            ThrowAdapterNotFound(method);\n        }\n    }\n    #endregion\n    abstract class DelegateAdapter : ILTypeInstance, IDelegateAdapter\n    {\n        protected ILMethod method;\n        protected ILTypeInstance instance;\n        protected Enviorment.AppDomain appdomain;\n        Dictionary<Type, Delegate> converters;\n        IDelegateAdapter next;\n        protected bool isClone;\n\n        public abstract Delegate Delegate { get; }\n\n        public IDelegateAdapter Next { get { return next; } }\n\n        public ILTypeInstance Instance { get { return instance; } }\n\n        public ILMethod Method { get { return method; } }\n\n        protected DelegateAdapter() { }\n\n        protected DelegateAdapter(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method)\n        {\n            this.appdomain = appdomain;\n            this.instance = instance;\n            this.method = method;\n            CLRInstance = this;\n        }\n\n        public override bool IsValueType\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        public unsafe StackObject* ILInvoke(ILIntepreter intp, StackObject* esp, IList<object> mStack)\n        {\n            var ebp = esp;\n            esp = ILInvokeSub(intp, esp, mStack);\n            return ClearStack(intp, esp, ebp, mStack);\n        }\n\n        unsafe StackObject* ILInvokeSub(ILIntepreter intp, StackObject* esp, IList<object> mStack)\n        {\n            var ebp = esp;\n            bool unhandled;\n            if (method.HasThis)\n                esp = ILIntepreter.PushObject(esp, mStack, instance);\n            int paramCnt = method.ParameterCount;\n            for(int i = paramCnt; i > 0; i--)\n            {\n                intp.CopyToStack(esp, Minus(ebp, i), mStack);\n                esp++;\n            }\n            var ret = intp.Execute(method, esp, out unhandled);\n            if (next != null)\n            {\n                if (method.ReturnType != appdomain.VoidType)\n                {\n                    intp.Free(ret - 1);//Return value for multicast delegate doesn't make sense, only return the last one's value\n                }\n                DelegateAdapter n = (DelegateAdapter)next;\n                ret = n.ILInvokeSub(intp, ebp, mStack);\n\n            }\n            return ret;\n        }\n\n        unsafe StackObject* ClearStack(ILIntepreter intp, StackObject* esp, StackObject* ebp, IList<object> mStack)\n        {\n            int paramCnt = method.ParameterCount;\n            object retObj = null;\n            StackObject retSObj = StackObject.Null;\n            bool hasReturn = method.ReturnType != appdomain.VoidType;\n            if (hasReturn)\n            {\n                var ret = esp - 1;\n                retSObj = *ret;\n                if(ret->ObjectType>= ObjectTypes.Object)\n                {\n                    retObj = mStack[ret->Value];\n                }\n                intp.Free(ret);\n            }\n            for (int i = 1; i <= paramCnt; i++)\n            {\n                intp.Free(ebp - i);\n            }\n            var returnVal = Minus(ebp, paramCnt + 1);\n            intp.Free(returnVal);//Free delegateInstance\n            if (hasReturn)\n            {\n                *returnVal = retSObj;\n                if(retObj != null)\n                {\n                    returnVal->Value = mStack.Count;\n                    mStack.Add(retObj);\n                }\n                returnVal++;\n            }\n            return returnVal;\n        }\n\n        public abstract IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method);\n\n        public new abstract IDelegateAdapter Clone();\n\n        public bool IsClone\n        {\n            get\n            {\n                return isClone;\n            }\n        }\n\n        public virtual void Combine(IDelegateAdapter adapter)\n        {\n            if (next != null)\n                next.Combine(adapter);\n            else\n                next = adapter;\n        }\n\n        public abstract void Combine(Delegate dele);\n\n        public virtual void Remove(IDelegateAdapter adapter)\n        {\n            if (next != null)\n            {\n                if (next.Equals(adapter))\n                {\n                    next = ((DelegateAdapter)next).next;\n                }\n                else\n                    next.Remove(adapter);\n            }\n        }\n\n        public abstract void Remove(Delegate dele);\n\n        public virtual bool Equals(IDelegateAdapter adapter)\n        {\n            if (adapter is DelegateAdapter)\n            {\n                DelegateAdapter b = (DelegateAdapter)adapter;\n                return instance == b.instance && method == b.method;\n            }\n            else\n                return false;\n        }\n\n        public virtual bool Equals(Delegate dele)\n        {\n            return Delegate == dele;\n        }\n\n        public override string ToString()\n        {\n            return method.ToString();\n        }\n\n        public Delegate GetConvertor(Type type)\n        {\n            if (converters == null)\n                converters = new Dictionary<System.Type, Delegate>(new ByReferenceKeyComparer<Type>());\n            Delegate res;\n            if (converters.TryGetValue(type, out res))\n                return res;\n            else\n            {\n                res = appdomain.DelegateManager.ConvertToDelegate(type, this);\n                converters[type] = res;\n                return res;\n            }\n        }\n\n        unsafe StackObject* Minus(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a - sizeof(StackObject) * b);\n        }\n\n        public static void ThrowAdapterNotFound(IMethod method)\n        {\n            StringBuilder sb = new StringBuilder();\n            sb.Append(\"Cannot find Delegate Adapter for:\");\n            sb.Append(method.ToString());\n            string clsName, rName;\n            bool isByRef;\n            if (method.ReturnType.Name != \"Void\" || method.ParameterCount > 0)\n            {\n                sb.AppendLine(\", Please add following code:\");\n                if (method.ReturnType.Name == \"Void\")\n                {\n                    sb.Append(\"appdomain.DelegateManager.RegisterMethodDelegate<\");\n                    bool first = true;\n                    foreach(var i in method.Parameters)\n                    {\n                        if (first)\n                        {\n                            first = false;\n                        }\n                        else\n                        {\n                            sb.Append(\", \");\n                        }\n                        i.TypeForCLR.GetClassName(out clsName, out rName, out isByRef);\n                        sb.Append(rName);                        \n                    }\n                    sb.AppendLine(\">();\");\n                }\n                else\n                {\n                    sb.Append(\"appdomain.DelegateManager.RegisterFunctionDelegate<\");\n                    bool first = true;\n                    foreach (var i in method.Parameters)\n                    {\n                        if (first)\n                        {\n                            first = false;\n                        }\n                        else\n                        {\n                            sb.Append(\", \");\n                        }\n                        i.TypeForCLR.GetClassName(out clsName, out rName, out isByRef);\n                        sb.Append(rName);\n                    }\n                    if (!first)\n                        sb.Append(\", \");\n                    method.ReturnType.TypeForCLR.GetClassName(out clsName, out rName, out isByRef);\n                    sb.Append(rName);\n                    sb.AppendLine(\">();\");\n                }\n            }\n            throw new KeyNotFoundException(sb.ToString());\n        }\n    }\n\n    unsafe interface IDelegateAdapter\n    {\n        Delegate Delegate { get; }\n        IDelegateAdapter Next { get; }\n        ILTypeInstance Instance { get; }\n        ILMethod Method { get; }\n        StackObject* ILInvoke(ILIntepreter intp, StackObject* esp, IList<object> mStack);\n        IDelegateAdapter Instantiate(Enviorment.AppDomain appdomain, ILTypeInstance instance, ILMethod method);\n        bool IsClone { get; }\n        IDelegateAdapter Clone();\n        Delegate GetConvertor(Type type);\n        void Combine(IDelegateAdapter adapter);\n        void Combine(Delegate dele);\n        void Remove(IDelegateAdapter adapter);\n        void Remove(Delegate dele);\n        bool Equals(IDelegateAdapter adapter);\n        bool Equals(Delegate dele);\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Intepreter/ILIntepreter.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\n\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Stack;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Intepreter.OpCodes;\nusing ILRuntime.Runtime.Debugger;\nusing ILRuntime.CLR.Utils;\nusing ILRuntime.Other;\n\nnamespace ILRuntime.Runtime.Intepreter\n{\n    public unsafe class ILIntepreter\n    {\n        Enviorment.AppDomain domain;\n        RuntimeStack stack;\n        object _lockObj;\n        bool allowUnboundCLRMethod;\n\n        public RuntimeStack Stack { get { return stack; } }\n        public bool ShouldBreak { get; set; }\n        public StepTypes CurrentStepType { get; set; }\n        public StackObject* LastStepFrameBase { get; set; }\n        public int LastStepInstructionIndex { get; set; }\n        StackObject* ValueTypeBasePointer;\n        public ILIntepreter(Enviorment.AppDomain domain)\n        {\n            this.domain = domain;\n            stack = new RuntimeStack(this);\n            allowUnboundCLRMethod = domain.AllowUnboundCLRMethod;\n#if DEBUG\n            _lockObj = new object();\n#endif\n        }\n\n        public Enviorment.AppDomain AppDomain { get { return domain; } }\n\n        public void Break()\n        {\n            //Clear old debug state\n            ClearDebugState();\n            lock (_lockObj)\n                Monitor.Wait(_lockObj);\n        }\n\n        public void Resume()\n        {\n            lock (_lockObj)\n                Monitor.Pulse(_lockObj);\n        }\n\n        public void ClearDebugState()\n        {\n            ShouldBreak = false;\n            CurrentStepType = StepTypes.None;\n            LastStepFrameBase = (StackObject*)0;\n            LastStepInstructionIndex = 0;\n        }\n        public object Run(ILMethod method, object instance, object[] p)\n        {\n            IList<object> mStack = stack.ManagedStack;\n            int mStackBase = mStack.Count;\n            StackObject* esp = stack.StackBase;\n            stack.ResetValueTypePointer();\n            if (method.HasThis)\n            {\n                if (instance is CrossBindingAdaptorType)\n                    instance = ((CrossBindingAdaptorType)instance).ILInstance;\n                if (instance == null)\n                    throw new NullReferenceException(\"instance should not be null!\");\n                esp = PushObject(esp, mStack, instance);\n            }\n            esp = PushParameters(method, esp, p);\n            bool unhandledException;\n            esp = Execute(method, esp, out unhandledException);\n            object result = method.ReturnType != domain.VoidType ? method.ReturnType.TypeForCLR.CheckCLRTypes(StackObject.ToObject((esp - 1), domain, mStack)) : null;\n            //ClearStack\n#if DEBUG\n            ((List<object>)mStack).RemoveRange(mStackBase, mStack.Count - mStackBase);\n#else\n            ((UncheckedList<object>)mStack).RemoveRange(mStackBase, mStack.Count - mStackBase);\n#endif\n            return result;\n        }\n        internal StackObject* Execute(ILMethod method, StackObject* esp, out bool unhandledException)\n        {\n            if (method == null)\n                throw new NullReferenceException();\n#if UNITY_EDITOR\n            if (System.Threading.Thread.CurrentThread.ManagedThreadId == AppDomain.UnityMainThreadID)\n\n#if UNITY_5_5_OR_NEWER\n                UnityEngine.Profiling.Profiler.BeginSample(method.ToString());\n#else\n                UnityEngine.Profiler.BeginSample(method.ToString());\n#endif\n\n#endif\n            OpCode[] body = method.Body;\n            StackFrame frame;\n            stack.InitializeFrame(method, esp, out frame);\n            StackObject* v1 = frame.LocalVarPointer;\n            StackObject* v2 = frame.LocalVarPointer + 1;\n            StackObject* v3 = frame.LocalVarPointer + 1 + 1;\n            StackObject* v4 = Add(frame.LocalVarPointer, 3);\n            int finallyEndAddress = 0;\n\n            esp = frame.BasePointer;\n            StackObject* arg = Minus(frame.LocalVarPointer, method.ParameterCount);\n            IList<object> mStack = stack.ManagedStack;\n            int paramCnt = method.ParameterCount;\n            if (method.HasThis)//this parameter is always object reference\n            {\n                arg--;\n                paramCnt++;\n            }\n            unhandledException = false;\n\n            //Managed Stack reserved for arguments(In case of starg)\n            for (int i = 0; i < paramCnt; i++)\n            {\n                var a = Add(arg, i);\n                switch (a->ObjectType)\n                {\n                    case ObjectTypes.Null:\n                        //Need to reserve place for null, in case of starg\n                        a->ObjectType = ObjectTypes.Object;\n                        a->Value = mStack.Count;\n                        mStack.Add(null);\n                        break;\n                    case ObjectTypes.ValueTypeObjectReference:\n                        CloneStackValueType(a, a, mStack);\n                        break;\n                    case ObjectTypes.Object:\n                    case ObjectTypes.FieldReference:\n                    case ObjectTypes.ArrayReference:\n                        frame.ManagedStackBase--;\n                        break;\n                }\n            }\n\n            stack.PushFrame(ref frame);\n\n            int locBase = mStack.Count;\n            //Managed Stack reserved for local variable\n            for (int i = 0; i < method.LocalVariableCount; i++)\n            {\n                mStack.Add(null);\n            }\n\n            for (int i = 0; i < method.LocalVariableCount; i++)\n            {\n                var v = method.Variables[i];\n                if (v.VariableType.IsValueType && !v.VariableType.IsPrimitive)\n                {\n                    var t = AppDomain.GetType(v.VariableType, method.DeclearingType, method);\n                    if (t is ILType)\n                    {\n                        //var obj = ((ILType)t).Instantiate(false);\n                        var loc = Add(v1, i);\n                        stack.AllocValueType(loc, t);\n\n                        /*loc->ObjectType = ObjectTypes.Object;\n                        loc->Value = mStack.Count;\n                        mStack.Add(obj);*/\n\n                    }\n                    else\n                    {\n                        CLRType cT = (CLRType)t;\n                        var loc = Add(v1, i);\n                        if (cT.ValueTypeBinder != null)\n                        {\n                            stack.AllocValueType(loc, t);\n                        }\n                        else\n                        {\n                            var obj = ((CLRType)t).CreateDefaultInstance();\n                            loc->ObjectType = ObjectTypes.Object;\n                            loc->Value = locBase + i;\n                            mStack[locBase + i] = obj;\n                        }\n                    }\n                }\n                else\n                {\n                    if (v.VariableType.IsPrimitive)\n                    {\n                        var t = AppDomain.GetType(v.VariableType, method.DeclearingType, method);\n                        var loc = Add(v1, i);\n                        StackObject.Initialized(loc, t);\n                    }\n                    else\n                    {\n                        var loc = Add(v1, i);\n                        loc->ObjectType = ObjectTypes.Object;\n                        loc->Value = locBase + i;\n                    }\n                }\n            }\n            var bp = stack.ValueTypeStackPointer;\n            ValueTypeBasePointer = bp;\n            fixed (OpCode* ptr = body)\n            {\n                OpCode* ip = ptr;\n                OpCodeEnum code = ip->Code;\n                bool returned = false;\n                while (!returned)\n                {\n                    try\n                    {\n#if DEBUG\n                        if (ShouldBreak)\n                            Break();\n                        var insOffset = (int)(ip - ptr);\n                        frame.Address.Value = insOffset;\n                        AppDomain.DebugService.CheckShouldBreak(method, this, insOffset);\n#endif\n                        code = ip->Code;\n                        switch (code)\n                        {\n                            #region Arguments and Local Variable\n                            case OpCodeEnum.Ldarg_0:\n                                CopyToStack(esp, arg, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldarg_1:\n                                CopyToStack(esp, arg + 1, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldarg_2:\n                                CopyToStack(esp, arg + 1 + 1, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldarg_3:\n                                CopyToStack(esp, arg + 1 + 1 + 1, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldarg:\n                            case OpCodeEnum.Ldarg_S:\n                                CopyToStack(esp, Add(arg, ip->TokenInteger), mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldarga:\n                            case OpCodeEnum.Ldarga_S:\n                                {\n                                    var a = Add(arg, ip->TokenInteger);\n                                    esp->ObjectType = ObjectTypes.StackObjectReference;\n                                    *(StackObject**)&esp->Value = a;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Starg:\n                            case OpCodeEnum.Starg_S:\n                                {\n                                    var a = Add(arg, ip->TokenInteger);\n                                    var val = esp - 1;\n                                    int idx = a->Value;\n                                    bool isObj = a->ObjectType >= ObjectTypes.Object;\n                                    if (val->ObjectType >= ObjectTypes.Object)\n                                    {\n                                        a->ObjectType = val->ObjectType;\n                                        mStack[a->Value] = mStack[val->Value];\n                                        a->ValueLow = val->ValueLow;\n                                    }\n                                    else\n                                    {\n                                        *a = *val;\n                                        if (isObj)\n                                        {\n                                            a->Value = idx;\n                                            if (val->ObjectType == ObjectTypes.Null)\n                                            {\n                                                mStack[a->Value] = null;\n                                            }\n                                        }\n                                    }\n                                    Free(val);\n                                    esp--;\n                                }\n                                break;\n                            case OpCodeEnum.Stloc_0:\n                                {\n                                    esp--;\n                                    int idx = locBase;\n                                    StLocSub(esp, v1, bp, idx, mStack);\n                                }\n                                break;\n                            case OpCodeEnum.Ldloc_0:\n                                CopyToStack(esp, v1, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Stloc_1:\n                                {\n                                    esp--;\n                                    int idx = locBase + 1;\n                                    StLocSub(esp, v2, bp, idx, mStack);\n                                }\n                                break;\n                            case OpCodeEnum.Ldloc_1:\n                                CopyToStack(esp, v2, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Stloc_2:\n                                {\n                                    esp--;\n                                    int idx = locBase + 2;\n                                    StLocSub(esp, v3, bp, idx, mStack);\n                                    break;\n                                }\n                            case OpCodeEnum.Ldloc_2:\n                                CopyToStack(esp, v3, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Stloc_3:\n                                {\n                                    esp--;\n                                    int idx = locBase + 3;\n\n                                    StLocSub(esp, v4, bp, idx, mStack);\n                                }\n                                break;\n                            case OpCodeEnum.Ldloc_3:\n                                CopyToStack(esp, v4, mStack);\n                                esp++;\n                                break;\n                            case OpCodeEnum.Stloc:\n                            case OpCodeEnum.Stloc_S:\n                                {\n                                    esp--;\n                                    var v = Add(frame.LocalVarPointer, ip->TokenInteger);\n                                    int idx = locBase + ip->TokenInteger;\n                                    StLocSub(esp, v, bp, idx, mStack);\n                                }\n                                break;\n                            case OpCodeEnum.Ldloc:\n                            case OpCodeEnum.Ldloc_S:\n                                {\n                                    var v = Add(frame.LocalVarPointer, ip->TokenInteger);\n                                    CopyToStack(esp, v, mStack);\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldloca:\n                            case OpCodeEnum.Ldloca_S:\n                                {\n                                    var v = Add(frame.LocalVarPointer, ip->TokenInteger);\n                                    esp->ObjectType = ObjectTypes.StackObjectReference;\n                                    *(StackObject**)&esp->Value = v;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldobj:\n                                {\n                                    var objRef = esp - 1;\n                                    switch (objRef->ObjectType)\n                                    {\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var t = AppDomain.GetType(ip->TokenInteger);\n                                                var obj = mStack[objRef->Value];\n                                                var idx = objRef->ValueLow;\n                                                Free(objRef);\n                                                LoadFromArrayReference(obj, idx, objRef, t, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.StackObjectReference:\n                                            {\n                                                var obj = GetObjectAndResolveReference(objRef);\n                                                *objRef = *obj;\n                                                if (objRef->ObjectType >= ObjectTypes.Object)\n                                                {\n                                                    objRef->Value = mStack.Count;\n                                                    mStack.Add(mStack[obj->Value]);\n                                                }\n                                            }\n                                            break;\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var obj = mStack[objRef->Value];\n                                                int idx = objRef->ValueLow;\n                                                Free(objRef);\n                                                if (obj is ILTypeInstance)\n                                                {\n                                                    ((ILTypeInstance)obj).PushToStack(idx, objRef, AppDomain, mStack);\n                                                }\n                                                else\n                                                {\n                                                    var t = AppDomain.GetType(ip->TokenInteger);\n                                                    obj = ((CLRType) t).GetFieldValue(idx, obj);\n                                                    PushObject(objRef, mStack, obj);\n                                                }\n                                            }\n                                            break;\n                                        case ObjectTypes.StaticFieldReference:\n                                            {\n                                                var t = AppDomain.GetType(objRef->Value);\n                                                int idx = objRef->ValueLow;\n                                                Free(objRef);\n                                                if (t is ILType)\n                                                {\n                                                    ((ILType)t).StaticInstance.PushToStack(idx, objRef, AppDomain, mStack);\n                                                }\n                                                else\n                                                {\n                                                    var obj = ((CLRType)t).GetFieldValue(idx, null);\n                                                    PushObject(objRef, mStack, obj);\n                                                }\n                                            }\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Stobj:\n                                {\n                                    var objRef = esp - 1 - 1;\n                                    var val = esp - 1;\n                                    switch (objRef->ObjectType)\n                                    {\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var t = AppDomain.GetType(ip->TokenInteger);\n                                                StoreValueToArrayReference(objRef, val, t, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.StackObjectReference:\n                                            {\n                                                objRef = GetObjectAndResolveReference(objRef);\n                                                if (val->ObjectType >= ObjectTypes.Object)\n                                                {\n                                                    mStack[objRef->Value] = mStack[val->Value];\n                                                    objRef->ValueLow = val->ValueLow;\n                                                }\n                                                else\n                                                {\n                                                    *objRef = *val;\n                                                }\n                                            }\n                                            break;\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var obj = mStack[objRef->Value];\n                                                int idx = objRef->ValueLow;\n                                                if (obj is ILTypeInstance)\n                                                {\n                                                    ((ILTypeInstance)obj).AssignFromStack(idx, val, AppDomain, mStack);\n                                                }\n                                                else\n                                                {\n                                                    var t = AppDomain.GetType(ip->TokenInteger);\n                                                    ((CLRType)t).SetFieldValue(idx, ref obj, t.TypeForCLR.CheckCLRTypes(StackObject.ToObject(val, AppDomain, mStack)));\n                                                }\n                                            }\n                                            break;\n                                        case ObjectTypes.StaticFieldReference:\n                                            {\n                                                var t = AppDomain.GetType(objRef->Value);\n                                                if (t is ILType)\n                                                {\n                                                    ((ILType)t).StaticInstance.AssignFromStack(objRef->ValueLow, val, AppDomain, mStack);\n                                                }\n                                                else\n                                                {\n                                                    ((CLRType)t).SetStaticFieldValue(objRef->ValueLow, t.TypeForCLR.CheckCLRTypes(StackObject.ToObject(val, AppDomain, mStack)));\n                                                }\n                                            }\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                }\n                                break;\n                            #endregion\n\n                            #region Load Constants\n                            case OpCodeEnum.Ldc_I4_M1:\n                                esp->Value = -1;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_0:\n                                esp->Value = 0;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_1:\n                                esp->Value = 1;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_2:\n                                esp->Value = 2;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_3:\n                                esp->Value = 3;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_4:\n                                esp->Value = 4;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_5:\n                                esp->Value = 5;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_6:\n                                esp->Value = 6;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_7:\n                                esp->Value = 7;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4_8:\n                                esp->Value = 8;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I4:\n                            case OpCodeEnum.Ldc_I4_S:\n                                esp->Value = ip->TokenInteger;\n                                esp->ObjectType = ObjectTypes.Integer;\n                                esp++;\n                                break;\n                            case OpCodeEnum.Ldc_I8:\n                                {\n                                    *(long*)(&esp->Value) = ip->TokenLong;\n                                    esp->ObjectType = ObjectTypes.Long;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldc_R4:\n                                {\n                                    *(float*)(&esp->Value) = *(float*)&ip->TokenInteger;\n                                    esp->ObjectType = ObjectTypes.Float;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldc_R8:\n                                {\n                                    *(double*)(&esp->Value) = *(double*)&ip->TokenLong;\n                                    esp->ObjectType = ObjectTypes.Double;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldnull:\n                                {\n                                    esp = PushNull(esp);\n                                }\n                                break;\n                            case OpCodeEnum.Ldind_I:\n                            case OpCodeEnum.Ldind_I1:\n                            case OpCodeEnum.Ldind_I2:\n                            case OpCodeEnum.Ldind_I4:\n                            case OpCodeEnum.Ldind_U1:\n                            case OpCodeEnum.Ldind_U2:\n                            case OpCodeEnum.Ldind_U4:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var dst = esp - 1;\n                                    switch (val->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromFieldReference(instance, idx, dst, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromArrayReference(instance, idx, dst, instance.GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                dst->ObjectType = ObjectTypes.Integer;\n                                                dst->Value = val->Value;\n                                                dst->ValueLow = 0;\n                                            }\n                                            break;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldind_I8:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var dst = esp - 1;\n                                    switch (val->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromFieldReference(instance, idx, dst, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromArrayReference(instance, idx, dst, instance.GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                *dst = *val;\n                                                dst->ObjectType = ObjectTypes.Long;\n                                                dst->ValueLow = 0;\n                                            }\n                                            break;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldind_R4:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var dst = esp - 1;\n                                    switch (val->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromFieldReference(instance, idx, dst, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromArrayReference(instance, idx, dst, instance.GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                dst->ObjectType = ObjectTypes.Float;\n                                                dst->Value = val->Value;\n                                                dst->ValueLow = 0;\n                                            }\n                                            break;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldind_R8:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var dst = esp - 1;\n                                    switch (val->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromFieldReference(instance, idx, dst, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromArrayReference(instance, idx, dst, instance.GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                *dst = *val;\n                                                dst->ObjectType = ObjectTypes.Double;\n                                            }\n                                            break;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldind_Ref:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var dst = esp - 1;\n                                    switch (val->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromFieldReference(instance, idx, dst, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                var instance = mStack[val->Value];\n                                                var idx = val->ValueLow;\n                                                Free(dst);\n                                                LoadFromArrayReference(instance, idx, dst, instance.GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                dst->ObjectType = ObjectTypes.Object;\n                                                dst->Value = mStack.Count;\n                                                mStack.Add(mStack[val->Value]);\n                                            }\n                                            break;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Stind_I:\n                            case OpCodeEnum.Stind_I1:\n                            case OpCodeEnum.Stind_I2:\n                            case OpCodeEnum.Stind_I4:\n                            case OpCodeEnum.Stind_R4:\n                                {\n                                    var dst = GetObjectAndResolveReference(esp - 1 - 1);\n                                    var val = esp - 1;\n                                    switch (dst->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                StoreValueToFieldReference(mStack[dst->Value], dst->ValueLow, val, mStack);\n                                            }\n                                            break;\n                                        case ObjectTypes.ArrayReference:\n                                            {\n                                                StoreValueToArrayReference(dst, val, mStack[dst->Value].GetType().GetElementType(), mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                dst->Value = val->Value;\n                                            }\n                                            break;\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stind_I8:\n                            case OpCodeEnum.Stind_R8:\n                                {\n                                    var dst = GetObjectAndResolveReference(esp - 1 - 1);\n                                    var val = esp - 1;\n                                    switch (dst->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                StoreValueToFieldReference(mStack[dst->Value], dst->ValueLow, val, mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                dst->Value = val->Value;\n                                                dst->ValueLow = val->ValueLow;\n                                            }\n                                            break;\n                                    }\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stind_Ref:\n                                {\n                                    var dst = GetObjectAndResolveReference(esp - 1 - 1);\n                                    var val = esp - 1;\n                                    switch (dst->ObjectType)\n                                    {\n                                        case ObjectTypes.FieldReference:\n                                            {\n                                                StoreValueToFieldReference(mStack[dst->Value], dst->ValueLow, val, mStack);\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                switch (val->ObjectType)\n                                                {\n                                                    case ObjectTypes.Object:\n                                                        mStack[dst->Value] = mStack[val->Value];\n                                                        break;\n                                                    case ObjectTypes.Null:\n                                                        mStack[dst->Value] = null;\n                                                        break;\n                                                    default:\n                                                        throw new NotImplementedException();\n                                                }\n                                            }\n                                            break;\n                                    }\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldstr:\n                                esp = PushObject(esp, mStack, AppDomain.GetString(ip->TokenLong));\n                                break;\n                            #endregion\n\n                            #region Althemetics\n                            case OpCodeEnum.Add:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) + *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value + b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *((float*)&esp->Value) = *((float*)&a->Value) + *((float*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *((double*)&esp->Value) = *((double*)&a->Value) + *((double*)&b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Sub:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) - *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value - b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *((float*)&esp->Value) = *((float*)&a->Value) - *((float*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *((double*)&esp->Value) = *((double*)&a->Value) - *((double*)&b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Mul:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) * *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value * b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *((float*)&esp->Value) = *((float*)&a->Value) * *((float*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *((double*)&esp->Value) = *((double*)&a->Value) * *((double*)&b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Div:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) / *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value / b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *((float*)&esp->Value) = *((float*)&a->Value) / *((float*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *((double*)&esp->Value) = *((double*)&a->Value) / *((double*)&b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Div_Un:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((ulong*)&esp->Value) = *((ulong*)&a->Value) / *((ulong*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = (int)((uint)a->Value / (uint)b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Rem:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) % *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value % b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *(float*)&esp->Value = *(float*)&a->Value % *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *(double*)&esp->Value = *(double*)&a->Value % *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Rem_Un:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((ulong*)&esp->Value) = *((ulong*)&a->Value) % *((ulong*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = (int)((uint)a->Value % (uint)b->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Xor:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) ^ *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value ^ b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.And:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) & *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value & b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Or:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) | *((long*)&b->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value | b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Shl:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    int bits = b->Value;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) << bits;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value << bits;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Shr:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    int bits = b->Value;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&esp->Value) = *((long*)&a->Value) >> bits;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            esp->Value = a->Value >> bits;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Shr_Un:\n                                {\n                                    StackObject* b = esp - 1;\n                                    StackObject* a = esp - 1 - 1;\n                                    esp = a;\n                                    int bits = b->Value;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((ulong*)&esp->Value) = *((ulong*)&a->Value) >> bits;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            *(uint*)&esp->Value = (uint)a->Value >> bits;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Not:\n                                {\n                                    StackObject* a = esp - 1;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&a->Value) = ~*((long*)&a->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            a->Value = ~a->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Neg:\n                                {\n                                    StackObject* a = esp - 1;\n                                    switch (a->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            *((long*)&a->Value) = -*((long*)&a->Value);\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            a->Value = -a->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            *((float*)&a->Value) = -*((float*)&a->Value);\n                                            break;\n                                        case ObjectTypes.Double:\n                                            *((double*)&a->Value) = -*((double*)&a->Value);\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                }\n                                break;\n                            #endregion\n\n                            #region Control Flows\n                            case OpCodeEnum.Ret:\n                                returned = true;\n                                break;\n                            case OpCodeEnum.Brtrue:\n                            case OpCodeEnum.Brtrue_S:\n                                {\n                                    esp--;\n                                    bool res = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            res = esp->Value != 0;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = *(long*)&esp->Value != 0;\n                                            break;\n                                        case ObjectTypes.Object:\n                                            res = mStack[esp->Value] != null;\n                                            break;\n                                    }\n                                    if (res)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        Free(esp);\n                                        continue;\n                                    }\n                                    else\n                                        Free(esp);\n                                }\n                                break;\n                            case OpCodeEnum.Brfalse:\n                            case OpCodeEnum.Brfalse_S:\n                                {\n                                    esp--;\n                                    bool res = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Null:\n                                            res = true;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            res = esp->Value == 0;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = *(long*)&esp->Value == 0;\n                                            break;\n                                        case ObjectTypes.Object:\n                                            res = mStack[esp->Value] == null;\n                                            Free(esp);\n                                            break;\n                                        default:\n                                            Free(esp);\n                                            break;\n                                    }\n                                    if (res)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Beq:\n                            case OpCodeEnum.Beq_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    bool transfer = false;\n                                    if (a->ObjectType == b->ObjectType)\n                                    {\n                                        switch (a->ObjectType)\n                                        {\n                                            case ObjectTypes.Null:\n                                                transfer = true;\n                                                break;\n                                            case ObjectTypes.Integer:\n                                                transfer = a->Value == b->Value;\n                                                break;\n                                            case ObjectTypes.Long:\n                                                transfer = *(long*)&a->Value == *(long*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Float:\n                                                transfer = *(float*)&a->Value == *(float*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Double:\n                                                transfer = *(double*)&a->Value == *(double*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Object:\n                                                transfer = mStack[a->Value] == mStack[b->Value];\n                                                break;\n                                            default:\n                                                throw new NotImplementedException();\n                                        }\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Bne_Un:\n                            case OpCodeEnum.Bne_Un_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    bool transfer = false;\n                                    if (a->ObjectType == b->ObjectType)\n                                    {\n                                        switch (a->ObjectType)\n                                        {\n                                            case ObjectTypes.Null:\n                                                transfer = false;\n                                                break;\n                                            case ObjectTypes.Integer:\n                                                transfer = (uint)a->Value != (uint)b->Value;\n                                                break;\n                                            case ObjectTypes.Float:\n                                                transfer = *(float*)&a->Value != *(float*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Long:\n                                                transfer = *(long*)&a->Value != *(long*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Double:\n                                                transfer = *(double*)&a->Value != *(double*)&b->Value;\n                                                break;\n                                            case ObjectTypes.Object:\n                                                transfer = mStack[a->Value] != mStack[b->Value];\n                                                break;\n                                            default:\n                                                throw new NotImplementedException();\n                                        }\n                                    }\n                                    else\n                                        transfer = true;\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Bgt:\n                            case OpCodeEnum.Bgt_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = a->Value > b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(long*)&a->Value > *(long*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value > *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value > *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Bgt_Un:\n                            case OpCodeEnum.Bgt_Un_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = (uint)a->Value > (uint)b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(ulong*)&a->Value > *(ulong*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value > *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value > *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Bge:\n                            case OpCodeEnum.Bge_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = a->Value >= b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(long*)&a->Value >= *(long*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value >= *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value >= *(double*)&b->Value;\n                                            break;\n\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Bge_Un:\n                            case OpCodeEnum.Bge_Un_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = (uint)a->Value >= (uint)b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(ulong*)&a->Value >= *(ulong*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value >= *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value >= *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Blt:\n                            case OpCodeEnum.Blt_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = a->Value < b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(long*)&a->Value < *(long*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value < *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value < *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Blt_Un:\n                            case OpCodeEnum.Blt_Un_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = (uint)a->Value < (uint)b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(ulong*)&a->Value < *(ulong*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value < *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value < *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Ble:\n                            case OpCodeEnum.Ble_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = a->Value <= b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(long*)&a->Value <= *(long*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value <= *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value <= *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Ble_Un:\n                            case OpCodeEnum.Ble_Un_S:\n                                {\n                                    var b = esp - 1;\n                                    var a = esp - 1 - 1;\n                                    esp = esp - 1 - 1;\n                                    bool transfer = false;\n                                    switch (esp->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            transfer = (uint)a->Value <= (uint)b->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            transfer = *(ulong*)&a->Value <= *(ulong*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            transfer = *(float*)&a->Value <= *(float*)&b->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            transfer = *(double*)&a->Value <= *(double*)&b->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n\n                                    if (transfer)\n                                    {\n                                        ip = ptr + ip->TokenInteger;\n                                        continue;\n                                    }\n\n                                }\n                                break;\n                            case OpCodeEnum.Br_S:\n                            case OpCodeEnum.Br:\n                                ip = ptr + ip->TokenInteger;\n                                continue;\n                            case OpCodeEnum.Switch:\n                                {\n                                    var val = (esp - 1)->Value;\n                                    Free(esp - 1);\n                                    esp--;\n                                    var table = method.JumpTables[ip->TokenInteger];\n                                    if (val >= 0 && val < table.Length)\n                                    {\n                                        ip = ptr + table[val];\n                                        continue;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Leave:\n                            case OpCodeEnum.Leave_S:\n                                {\n                                    if (method.ExceptionHandler != null)\n                                    {\n                                        ExceptionHandler eh = null;\n\n                                        int addr = ip->TokenInteger;\n                                        var sql = from e in method.ExceptionHandler\n                                                  where addr == e.HandlerEnd + 1 && e.HandlerType == ExceptionHandlerType.Finally || e.HandlerType == ExceptionHandlerType.Fault\n                                                  select e;\n                                        eh = sql.FirstOrDefault();\n                                        if (eh != null)\n                                        {\n                                            finallyEndAddress = ip->TokenInteger;\n                                            ip = ptr + eh.HandlerStart;\n                                            continue;\n                                        }\n                                    }\n                                    ip = ptr + ip->TokenInteger;\n                                    continue;\n                                }\n                            case OpCodeEnum.Endfinally:\n                                {\n                                    ip = ptr + finallyEndAddress;\n                                    finallyEndAddress = 0;\n                                    continue;\n                                }\n                            case OpCodeEnum.Call:\n                            case OpCodeEnum.Callvirt:\n                                {\n                                    IMethod m = domain.GetMethod(ip->TokenInteger);\n                                    if (m == null)\n                                    {\n                                        //Irrelevant method\n                                        int cnt = (int)ip->TokenLong;\n                                        //Balance the stack\n                                        for (int i = 0; i < cnt; i++)\n                                        {\n                                            Free(esp - 1);\n                                            esp--;\n                                        }\n                                    }\n                                    else\n                                    {\n                                        if (m is ILMethod)\n                                        {\n                                            ILMethod ilm = (ILMethod)m;\n                                            bool processed = false;\n                                            if (m.IsDelegateInvoke)\n                                            {\n                                                var instance = StackObject.ToObject((Minus(esp, m.ParameterCount + 1)), domain, mStack);\n                                                if (instance is IDelegateAdapter)\n                                                {\n                                                    esp = ((IDelegateAdapter)instance).ILInvoke(this, esp, mStack);\n                                                    processed = true;\n                                                }\n                                            }\n                                            if (!processed)\n                                            {\n                                                if (code == OpCodeEnum.Callvirt)\n                                                {\n                                                    var objRef = GetObjectAndResolveReference(Minus(esp, ilm.ParameterCount + 1));\n                                                    if (objRef->ObjectType == ObjectTypes.Null)\n                                                        throw new NullReferenceException();\n                                                    var obj = mStack[objRef->Value];\n                                                    if (obj == null)\n                                                        throw new NullReferenceException();\n                                                    ilm = ((ILTypeInstance)obj).Type.GetVirtualMethod(ilm) as ILMethod;\n                                                }\n                                                esp = Execute(ilm, esp, out unhandledException);\n                                                ValueTypeBasePointer = bp;\n                                                if (unhandledException)\n                                                    returned = true;\n                                            }\n                                        }\n                                        else\n                                        {\n                                            CLRMethod cm = (CLRMethod)m;\n                                            bool processed = false;\n                                            if (cm.IsDelegateInvoke)\n                                            {\n                                                var instance = StackObject.ToObject((Minus(esp, cm.ParameterCount + 1)), domain, mStack);\n                                                if (instance is IDelegateAdapter)\n                                                {\n                                                    esp = ((IDelegateAdapter)instance).ILInvoke(this, esp, mStack);\n                                                    processed = true;\n                                                }\n                                            }\n\n                                            if (!processed)\n                                            {\n                                                var redirect = cm.Redirection;\n                                                if (redirect != null)\n                                                    esp = redirect(this, esp, mStack, cm, false);\n                                                else\n                                                {\n#if DEBUG\n                                                    if (!allowUnboundCLRMethod)\n                                                        throw new NotSupportedException(cm.ToString() + \" is not bound!\");\n#endif\n#if UNITY_EDITOR\n                                                    if (System.Threading.Thread.CurrentThread.ManagedThreadId == AppDomain.UnityMainThreadID)\n\n#if UNITY_5_5_OR_NEWER\n                                                        UnityEngine.Profiling.Profiler.BeginSample(cm.ToString());\n#else\n                                                        UnityEngine.Profiler.BeginSample(cm.ToString());\n#endif\n#endif\n                                                    object result = cm.Invoke(this, esp, mStack);\n#if UNITY_EDITOR\n                                                    if (System.Threading.Thread.CurrentThread.ManagedThreadId == AppDomain.UnityMainThreadID)\n#if UNITY_5_5_OR_NEWER\n                                                        UnityEngine.Profiling.Profiler.EndSample();\n#else\n                                                        UnityEngine.Profiler.EndSample();\n#endif\n\n#endif\n                                                    if (result is CrossBindingAdaptorType)\n                                                        result = ((CrossBindingAdaptorType)result).ILInstance;\n                                                    int paramCount = cm.ParameterCount;\n                                                    for (int i = 1; i <= paramCount; i++)\n                                                    {\n                                                        Free(Minus(esp, i));\n                                                    }\n                                                    esp = Minus(esp, paramCount);\n                                                    if (cm.HasThis)\n                                                    {\n                                                        Free(esp - 1);\n                                                        esp--;\n                                                    }\n                                                    if (cm.ReturnType != AppDomain.VoidType && !cm.IsConstructor)\n                                                    {\n                                                        esp = PushObject(esp, mStack, result, cm.ReturnType.TypeForCLR == typeof(object));\n                                                    }\n                                                }\n                                            }\n                                        }\n\n                                    }\n                                }\n                                break;\n                            #endregion\n\n                            #region FieldOperation\n                            case OpCodeEnum.Stfld:\n                                {\n                                    var objRef = GetObjectAndResolveReference(esp - 1 - 1);\n                                    if (objRef->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                                    {\n                                        StackObject* dst = *(StackObject**)&objRef->Value;\n                                        var ft = domain.GetType(dst->Value);\n                                        if (ft is ILType)\n                                            CopyToValueTypeField(dst, (int)ip->TokenLong, esp - 1, mStack);\n                                        else\n                                            CopyToValueTypeField(dst, ((CLRType)ft).FieldIndexMapping[(int)ip->TokenLong], esp - 1, mStack);\n                                    }\n                                    else\n                                    {\n                                        object obj = RetriveObject(objRef, mStack);\n\n                                        if (obj != null)\n                                        {\n                                            if (obj is ILTypeInstance)\n                                            {\n                                                ILTypeInstance instance = obj as ILTypeInstance;\n                                                StackObject* val = esp - 1;\n                                                instance.AssignFromStack((int)ip->TokenLong, val, AppDomain, mStack);\n                                            }\n                                            else\n                                            {\n                                                var t = obj.GetType();\n                                                var type = AppDomain.GetType((int)(ip->TokenLong >> 32));\n                                                if (type != null)\n                                                {\n                                                    var val = esp - 1;\n                                                    var fieldToken = (int)ip->TokenLong;\n                                                    var f = ((CLRType)type).GetField(fieldToken);\n                                                    ((CLRType)type).SetFieldValue(fieldToken, ref obj, f.FieldType.CheckCLRTypes(CheckAndCloneValueType(StackObject.ToObject(val, domain, mStack), domain)));\n                                                    //Writeback\n                                                    if (t.IsValueType)\n                                                    {\n                                                        switch (objRef->ObjectType)\n                                                        {\n                                                            case ObjectTypes.Object:\n                                                                break;\n                                                            case ObjectTypes.FieldReference:\n                                                                {\n                                                                    var oldObj = mStack[objRef->Value];\n                                                                    int idx = objRef->ValueLow;\n                                                                    if (oldObj is ILTypeInstance)\n                                                                    {\n                                                                        ((ILTypeInstance)oldObj)[idx] = obj;\n                                                                    }\n                                                                    else\n                                                                    {\n                                                                        var it = AppDomain.GetType(oldObj.GetType());\n                                                                        ((CLRType)it).SetFieldValue(idx, ref oldObj, obj);\n                                                                    }\n                                                                }\n                                                                break;\n                                                            case ObjectTypes.StaticFieldReference:\n                                                                {\n                                                                    var it = AppDomain.GetType(objRef->Value);\n                                                                    int idx = objRef->ValueLow;\n                                                                    if (it is ILType)\n                                                                    {\n                                                                        ((ILType)it).StaticInstance[idx] = obj;\n                                                                    }\n                                                                    else\n                                                                    {\n                                                                        ((CLRType)it).SetStaticFieldValue(idx, obj);\n                                                                    }\n                                                                }\n                                                                break;\n                                                            default:\n                                                                throw new NotImplementedException();\n                                                        }\n                                                    }\n                                                }\n                                                else\n                                                    throw new TypeLoadException();\n                                            }\n                                        }\n                                        else\n                                            throw new NullReferenceException();\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    esp = esp - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldfld:\n                                {\n                                    StackObject* objRef = GetObjectAndResolveReference(esp - 1);\n                                    if (objRef->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                                    {\n                                        var dst = *(StackObject**)&objRef->Value;\n                                        var ft = domain.GetType(dst->Value);\n                                        if (ft is ILType)\n                                            dst = Minus(dst, (int)ip->TokenLong + 1);\n                                        else\n                                            dst = Minus(dst, ((CLRType)ft).FieldIndexMapping[(int)ip->TokenLong] + 1);\n                                        CopyToStack(objRef, dst, mStack);\n                                    }\n                                    else\n                                    {\n                                        object obj = RetriveObject(objRef, mStack);\n                                        Free(esp - 1);\n                                        if (obj != null)\n                                        {\n                                            if (obj is ILTypeInstance)\n                                            {\n                                                ILTypeInstance instance = obj as ILTypeInstance;\n                                                instance.PushToStack((int)ip->TokenLong, esp - 1, AppDomain, mStack);\n                                            }\n                                            else\n                                            {\n                                                //var t = obj.GetType();\n                                                var type = AppDomain.GetType((int)(ip->TokenLong >> 32));\n                                                if (type != null)\n                                                {\n                                                    var token = (int)ip->TokenLong;\n                                                    var ft = ((CLRType)type).GetField(token);\n                                                    var val = ((CLRType)type).GetFieldValue(token, obj);\n                                                    if (val is CrossBindingAdaptorType)\n                                                        val = ((CrossBindingAdaptorType)val).ILInstance;\n                                                    PushObject(esp - 1, mStack, val, ft.FieldType == typeof(object));\n                                                }\n                                                else\n                                                    throw new TypeLoadException();\n                                            }\n                                        }\n                                        else\n                                            throw new NullReferenceException();\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldflda:\n                                {\n                                    StackObject* objRef = GetObjectAndResolveReference(esp - 1);\n                                    if (objRef->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                                    {\n                                        var dst = esp - 1;\n                                        var ft = domain.GetType((int)(ip->TokenLong >> 32));\n                                        StackObject* fieldAddr;\n                                        if (ft is ILType)\n                                        {\n                                            fieldAddr = Minus(*(StackObject**)&objRef->Value, (int)ip->TokenLong + 1);                                            \n                                        }\n                                        else\n                                        {\n                                            fieldAddr = Minus(*(StackObject**)&objRef->Value, ((CLRType)ft).FieldIndexMapping[(int)ip->TokenLong] + 1);\n                                        }\n                                        dst->ObjectType = ObjectTypes.StackObjectReference;\n                                        *(StackObject**)&dst->Value = fieldAddr;\n                                    }\n                                    else\n                                    {\n                                        object obj = RetriveObject(objRef, mStack);\n\n                                        Free(esp - 1);\n                                        if (obj != null)\n                                        {\n                                            if (obj is ILTypeInstance)\n                                            {\n                                                ILTypeInstance instance = obj as ILTypeInstance;\n                                                instance.PushFieldAddress((int)ip->TokenLong, esp - 1, mStack);\n                                            }\n                                            else\n                                            {\n                                                objRef = esp - 1;\n                                                objRef->ObjectType = ObjectTypes.FieldReference;\n                                                objRef->Value = mStack.Count;\n                                                mStack.Add(obj);\n                                                objRef->ValueLow = (int)ip->TokenLong;\n                                            }\n                                        }\n                                        else\n                                            throw new NullReferenceException();\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Stsfld:\n                                {\n                                    IType type = AppDomain.GetType((int)(ip->TokenLong >> 32));\n                                    if (type != null)\n                                    {\n                                        if (type is ILType)\n                                        {\n                                            ILType t = type as ILType;\n                                            StackObject* val = esp - 1;\n                                            t.StaticInstance.AssignFromStack((int)ip->TokenLong, val, AppDomain, mStack);\n                                        }\n                                        else\n                                        {\n                                            CLRType t = type as CLRType;\n                                            int idx = (int)ip->TokenLong;\n                                            var f = t.GetField(idx);\n                                            StackObject* val = esp - 1;\n                                            t.SetStaticFieldValue(idx, f.FieldType.CheckCLRTypes(CheckAndCloneValueType(StackObject.ToObject(val, domain, mStack), domain)));\n                                        }\n                                    }\n                                    else\n                                        throw new TypeLoadException();\n                                    Free(esp - 1);\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldsfld:\n                                {\n                                    IType type = AppDomain.GetType((int)(ip->TokenLong >> 32));\n                                    if (type != null)\n                                    {\n                                        if (type is ILType)\n                                        {\n                                            ILType t = type as ILType;\n                                            t.StaticInstance.PushToStack((int)ip->TokenLong, esp, AppDomain, mStack);\n                                        }\n                                        else\n                                        {\n                                            CLRType t = type as CLRType;\n                                            int idx = (int)ip->TokenLong;\n                                            var f = t.GetField(idx);\n                                            var val = t.GetFieldValue(idx, null);\n                                            if (val is CrossBindingAdaptorType)\n                                                val = ((CrossBindingAdaptorType)val).ILInstance;\n                                            PushObject(esp, mStack, val, f.FieldType == typeof(object));\n                                        }\n                                    }\n                                    else\n                                        throw new TypeLoadException();\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldsflda:\n                                {\n                                    int type = (int)(ip->TokenLong >> 32);\n                                    int fieldIdx = (int)(ip->TokenLong);\n                                    esp->ObjectType = ObjectTypes.StaticFieldReference;\n                                    esp->Value = type;\n                                    esp->ValueLow = fieldIdx;\n                                    esp++;\n                                }\n                                break;\n                            case OpCodeEnum.Ldtoken:\n                                {\n                                    switch (ip->TokenInteger)\n                                    {\n                                        case 0:\n                                            {\n                                                IType type = AppDomain.GetType((int)(ip->TokenLong >> 32));\n                                                if (type != null)\n                                                {\n                                                    if (type is ILType)\n                                                    {\n                                                        ILType t = type as ILType;\n                                                        t.StaticInstance.PushToStack((int)ip->TokenLong, esp, AppDomain, mStack);\n                                                    }\n                                                    else\n                                                        throw new NotImplementedException();\n                                                }\n                                            }\n                                            esp++;\n                                            break;\n                                        case 1:\n                                            {\n                                                IType type = AppDomain.GetType((int)ip->TokenLong);\n                                                if (type != null)\n                                                {\n                                                    esp = PushObject(esp, mStack, type.ReflectionType);\n                                                }\n                                                else\n                                                    throw new TypeLoadException();\n                                            }\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Ldftn:\n                                {\n                                    IMethod m = domain.GetMethod(ip->TokenInteger);\n                                    esp = PushObject(esp, mStack, m);\n                                }\n                                break;\n                            case OpCodeEnum.Ldvirtftn:\n                                {\n                                    IMethod m = domain.GetMethod(ip->TokenInteger);\n                                    var objRef = esp - 1;\n                                    if (m is ILMethod)\n                                    {\n                                        ILMethod ilm = (ILMethod)m;\n\n                                        var obj = mStack[objRef->Value];\n                                        m = ((ILTypeInstance)obj).Type.GetVirtualMethod(ilm) as ILMethod;\n                                    }\n                                    else\n                                    {\n                                        var obj = mStack[objRef->Value];\n                                        if (obj is ILTypeInstance)\n                                            m = ((ILTypeInstance)obj).Type.GetVirtualMethod(m);\n                                        else if (obj is CrossBindingAdaptorType)\n                                        {\n                                            m = ((CrossBindingAdaptorType)obj).ILInstance.Type.BaseType.GetVirtualMethod(m);\n                                        }\n                                    }\n                                    Free(objRef);\n                                    esp = PushObject(objRef, mStack, m);\n                                }\n                                break;\n                            #endregion\n\n                            #region Compare\n                            case OpCodeEnum.Ceq:\n                                {\n                                    StackObject* obj1 = esp - 1 - 1;\n                                    StackObject* obj2 = esp - 1;\n                                    bool res = false;\n                                    if (obj1->ObjectType == obj2->ObjectType)\n                                    {\n                                        switch (obj1->ObjectType)\n                                        {\n                                            case ObjectTypes.Integer:\n                                            case ObjectTypes.Float:\n                                                res = obj1->Value == obj2->Value;\n                                                break;\n                                            case ObjectTypes.Object:\n                                                res = mStack[obj1->Value] == mStack[obj2->Value];\n                                                break;\n                                            case ObjectTypes.FieldReference:\n                                                res = mStack[obj1->Value] == mStack[obj2->Value] && obj1->ValueLow == obj2->ValueLow;\n                                                break;\n                                            case ObjectTypes.Null:\n                                                res = true;\n                                                break;\n                                            default:\n                                                res = obj1->Value == obj2->Value && obj1->ValueLow == obj2->ValueLow;\n                                                break;\n                                        }\n                                    }\n                                    else\n                                    {\n                                        switch (obj1->ObjectType)\n                                        {\n                                            case ObjectTypes.Object:\n                                                res = mStack[obj1->Value] == null && obj2->ObjectType == ObjectTypes.Null;\n                                                break;\n                                            case ObjectTypes.Null:\n                                                res = obj2->ObjectType == ObjectTypes.Object && mStack[obj2->Value] == null;\n                                                break;\n                                        }\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    if (res)\n                                        esp = PushOne(esp - 1 - 1);\n                                    else\n                                        esp = PushZero(esp - 1 - 1);\n\n                                }\n                                break;\n                            case OpCodeEnum.Clt:\n                                {\n                                    StackObject* obj1 = esp - 1 - 1;\n                                    StackObject* obj2 = esp - 1;\n                                    bool res = false;\n                                    switch (obj1->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            res = obj1->Value < obj2->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = *(long*)&obj1->Value < *(long*)&obj2->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            res = *(float*)&obj1->Value < *(float*)&obj2->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            res = *(double*)&obj1->Value < *(double*)&obj2->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    if (res)\n                                        esp = PushOne(esp - 1 - 1);\n                                    else\n                                        esp = PushZero(esp - 1 - 1);\n                                }\n                                break;\n                            case OpCodeEnum.Clt_Un:\n                                {\n                                    StackObject* obj1 = esp - 1 - 1;\n                                    StackObject* obj2 = esp - 1;\n                                    bool res = false;\n                                    switch (obj1->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            res = (uint)obj1->Value < (uint)obj2->Value && obj2->ObjectType != ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = (ulong)*(long*)&obj1->Value < (ulong)*(long*)&obj2->Value && obj2->ObjectType != ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            res = *(float*)&obj1->Value < *(float*)&obj2->Value && obj2->ObjectType != ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            res = *(double*)&obj1->Value < *(double*)&obj2->Value && obj2->ObjectType != ObjectTypes.Null;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    if (res)\n                                        esp = PushOne(esp - 1 - 1);\n                                    else\n                                        esp = PushZero(esp - 1 - 1);\n                                }\n                                break;\n                            case OpCodeEnum.Cgt:\n                                {\n                                    StackObject* obj1 = esp - 1 - 1;\n                                    StackObject* obj2 = esp - 1;\n                                    bool res = false;\n                                    switch (obj1->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            res = obj1->Value > obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = *(long*)&obj1->Value > *(long*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            res = *(float*)&obj1->Value > *(float*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            res = *(double*)&obj1->Value > *(double*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    if (res)\n                                        esp = PushOne(esp - 1 - 1);\n                                    else\n                                        esp = PushZero(esp - 1 - 1);\n                                }\n                                break;\n                            case OpCodeEnum.Cgt_Un:\n                                {\n                                    StackObject* obj1 = esp - 1 - 1;\n                                    StackObject* obj2 = esp - 1;\n                                    bool res = false;\n                                    switch (obj1->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            res = ((uint)obj1->Value > (uint)obj2->Value) || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            res = (ulong)*(long*)&obj1->Value > (ulong)*(long*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            res = *(float*)&obj1->Value > *(float*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            res = *(double*)&obj1->Value > *(double*)&obj2->Value || obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Object:\n                                            res = mStack[obj1->Value] != null && obj2->ObjectType == ObjectTypes.Null;\n                                            break;\n                                        case ObjectTypes.Null:\n                                            res = false;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    if (res)\n                                        esp = PushOne(esp - 1 - 1);\n                                    else\n                                        esp = PushZero(esp - 1 - 1);\n                                }\n                                break;\n                            #endregion\n\n                            #region Initialization & Instantiation\n                            case OpCodeEnum.Newobj:\n                                {\n                                    IMethod m = domain.GetMethod(ip->TokenInteger);\n                                    if (m is ILMethod)\n                                    {\n                                        ILType type = m.DeclearingType as ILType;\n                                        if (type.IsDelegate)\n                                        {\n                                            var objRef = GetObjectAndResolveReference(esp - 1 - 1);\n                                            var mi = (IMethod)mStack[(esp - 1)->Value];\n                                            object ins;\n                                            if (objRef->ObjectType == ObjectTypes.Null)\n                                                ins = null;\n                                            else\n                                                ins = mStack[objRef->Value];\n                                            Free(esp - 1);\n                                            Free(esp - 1 - 1);\n                                            esp = esp - 1 - 1;\n                                            object dele;\n                                            if (mi is ILMethod)\n                                            {\n                                                if (ins != null)\n                                                {\n                                                    dele = ((ILTypeInstance)ins).GetDelegateAdapter((ILMethod)mi);\n                                                    if (dele == null)\n                                                        dele = domain.DelegateManager.FindDelegateAdapter((ILTypeInstance)ins, (ILMethod)mi);\n                                                }\n                                                else\n                                                {\n                                                    if (((ILMethod)mi).DelegateAdapter == null)\n                                                    {\n                                                        ((ILMethod)mi).DelegateAdapter = domain.DelegateManager.FindDelegateAdapter(null, (ILMethod)mi);\n                                                    }\n                                                    dele = ((ILMethod)mi).DelegateAdapter;\n                                                }\n                                            }\n\n                                            else\n                                            {\n                                                throw new NotImplementedException();\n                                            }\n                                            esp = PushObject(esp, mStack, dele);\n                                        }\n                                        else\n                                        {\n                                            var a = esp - m.ParameterCount;\n                                            StackObject* objRef;\n                                            ILTypeInstance obj = null;\n                                            bool isValueType = type.IsValueType;\n                                            if (isValueType)\n                                            {\n                                                stack.AllocValueType(esp, type);\n                                                objRef = esp + 1;\n                                                objRef->ObjectType = ObjectTypes.StackObjectReference;\n                                                *(StackObject**)&objRef->Value = esp;\n                                                objRef++;\n                                            }\n                                            else\n                                            {\n                                                obj = type.Instantiate(false);\n                                                objRef = PushObject(esp, mStack, obj);//this parameter for constructor\n                                            }\n                                            esp = objRef;\n                                            for (int i = 0; i < m.ParameterCount; i++)\n                                            {\n                                                CopyToStack(esp, a + i, mStack);\n                                                esp++;\n                                            }\n                                            esp = Execute((ILMethod)m, esp, out unhandledException);\n                                            ValueTypeBasePointer = bp;\n                                            if (isValueType)\n                                            {\n                                                var ins = objRef - 1 - 1;\n                                                *a = *ins;\n                                                esp = a + 1;\n                                            }\n                                            else\n                                                esp = PushObject(a, mStack, obj);//new constructedObj\n                                        }\n                                        if (unhandledException)\n                                            returned = true;\n                                    }\n                                    else\n                                    {\n                                        CLRMethod cm = (CLRMethod)m;\n                                        //Means new object();\n                                        if (cm == null)\n                                        {\n                                            esp = PushObject(esp, mStack, new object());\n                                        }\n                                        else\n                                        {\n                                            if (cm.DeclearingType.IsDelegate)\n                                            {\n                                                var objRef = GetObjectAndResolveReference(esp - 1 - 1);\n                                                var mi = (IMethod)mStack[(esp - 1)->Value];\n                                                object ins;\n                                                if (objRef->ObjectType == ObjectTypes.Null)\n                                                    ins = null;\n                                                else\n                                                    ins = mStack[objRef->Value];\n                                                Free(esp - 1);\n                                                Free(esp - 1 - 1);\n                                                esp = esp - 1 - 1;\n                                                object dele;\n                                                if (mi is ILMethod)\n                                                {\n                                                    if (ins != null)\n                                                    {\n                                                        dele = ((ILTypeInstance)ins).GetDelegateAdapter((ILMethod)mi);\n                                                        if (dele == null)\n                                                            dele = domain.DelegateManager.FindDelegateAdapter((ILTypeInstance)ins, (ILMethod)mi);\n                                                    }\n                                                    else\n                                                    {\n                                                        if (((ILMethod)mi).DelegateAdapter == null)\n                                                        {\n                                                            ((ILMethod)mi).DelegateAdapter = domain.DelegateManager.FindDelegateAdapter(null, (ILMethod)mi);\n                                                        }\n                                                        dele = ((ILMethod)mi).DelegateAdapter;\n                                                    }\n                                                }\n                                                else\n                                                {\n                                                    if (ins is ILTypeInstance)\n                                                        ins = ((ILTypeInstance)ins).CLRInstance;\n                                                    dele = Delegate.CreateDelegate(cm.DeclearingType.TypeForCLR, ins, ((CLRMethod)mi).MethodInfo);\n                                                }\n                                                esp = PushObject(esp, mStack, dele);\n                                            }\n                                            else\n                                            {\n                                                var redirect = cm.Redirection;\n                                                if (redirect != null)\n                                                    esp = redirect(this, esp, mStack, cm, true);\n                                                else\n                                                {\n                                                    object result = cm.Invoke(this, esp, mStack, true);\n                                                    int paramCount = cm.ParameterCount;\n                                                    for (int i = 1; i <= paramCount; i++)\n                                                    {\n                                                        Free(esp - i);\n                                                    }\n                                                    esp = Minus(esp, paramCount);\n                                                    esp = PushObject(esp, mStack, result);//new constructedObj\n                                                }\n                                            }\n                                        }\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Constrained:\n                                {\n                                    var objRef = esp - 1;\n                                    var obj = GetObjectAndResolveReference(objRef);\n                                    var type = domain.GetType(ip->TokenInteger);\n                                    if (type != null)\n                                    {\n                                        if (type is ILType)\n                                        {\n                                            var t = (ILType)type;\n                                            if (t.IsEnum)\n                                            {\n                                                ILEnumTypeInstance ins = new ILEnumTypeInstance(t);\n                                                switch (obj->ObjectType)\n                                                {\n                                                    case ObjectTypes.FieldReference:\n                                                        {\n                                                            var owner = mStack[obj->Value] as ILTypeInstance;\n                                                            int idx = obj->ValueLow;\n                                                            Free(objRef);\n                                                            owner.PushToStack(idx, objRef, AppDomain, mStack);\n                                                            ins.AssignFromStack(0, objRef, AppDomain, mStack);\n                                                            ins.Boxed = true;\n                                                        }\n                                                        break;\n                                                    case ObjectTypes.StaticFieldReference:\n                                                        {\n                                                            var st = AppDomain.GetType(obj->Value) as ILType;\n                                                            int idx = obj->ValueLow;\n                                                            Free(objRef);\n                                                            st.StaticInstance.PushToStack(idx, objRef, AppDomain, mStack);\n                                                            ins.AssignFromStack(0, objRef, AppDomain, mStack);\n                                                            ins.Boxed = true;\n                                                        }\n                                                        break;\n                                                    case ObjectTypes.ArrayReference:\n                                                        {\n                                                            var arr = mStack[obj->Value];\n                                                            var idx = obj->ValueLow;\n                                                            Free(objRef);\n                                                            LoadFromArrayReference(arr, idx, objRef, t, mStack);\n                                                            ins.AssignFromStack(0, objRef, AppDomain, mStack);\n                                                            ins.Boxed = true;\n                                                        }\n                                                        break;\n                                                    default:\n                                                        ins.AssignFromStack(0, obj, AppDomain, mStack);\n                                                        ins.Boxed = true;\n                                                        break;\n                                                }\n                                                esp = PushObject(esp - 1, mStack, ins);\n                                            }\n                                            else\n                                            {\n                                                //Nothing to do for normal IL Types\n                                            }\n                                        }\n                                        else\n                                        {\n                                            var tt = type.TypeForCLR;\n                                            if (tt.IsEnum)\n                                            {\n                                                esp = PushObject(esp - 1, mStack, Enum.ToObject(tt, StackObject.ToObject(obj, AppDomain, mStack)));\n                                            }\n                                            else if (tt.IsPrimitive)\n                                            {\n                                                esp = PushObject(esp - 1, mStack, tt.CheckCLRTypes(StackObject.ToObject(obj, AppDomain, mStack)));\n                                            }\n                                            else\n                                            {\n                                                //Nothing to do for other CLR types\n                                            }\n                                        }\n                                    }\n                                    else\n                                        throw new NullReferenceException();\n                                }\n                                break;\n                            case OpCodeEnum.Box:\n                                {\n                                    var obj = esp - 1;\n                                    var type = domain.GetType(ip->TokenInteger);\n                                    if (type != null)\n                                    {\n                                        if (type is ILType)\n                                        {\n                                            if (((ILType)type).IsEnum)\n                                            {\n                                                ILEnumTypeInstance ins = new Intepreter.ILEnumTypeInstance((ILType)type);\n                                                ins.AssignFromStack(0, obj, AppDomain, mStack);\n                                                ins.Boxed = true;\n                                                esp = PushObject(obj, mStack, ins, true);\n                                            }\n                                            else\n                                            {\n                                                switch (obj->ObjectType)\n                                                {\n                                                    case ObjectTypes.Null:\n                                                        break;\n                                                    case ObjectTypes.ValueTypeObjectReference:\n                                                        {\n                                                            ILTypeInstance ins = ((ILType)type).Instantiate(false);\n                                                            ins.AssignFromStack(obj, domain, mStack);\n                                                            FreeStackValueType(obj);\n                                                            esp = PushObject(obj, mStack, ins, true);\n                                                        }\n                                                        break;\n                                                    default:\n                                                        {\n                                                            var val = mStack[obj->Value];\n                                                            Free(obj);\n                                                            ILTypeInstance ins = (ILTypeInstance)val;\n                                                            if (ins != null)\n                                                            {\n                                                                if (ins.IsValueType)\n                                                                {\n                                                                    ins.Boxed = true;\n                                                                }\n                                                                esp = PushObject(obj, mStack, ins, true);\n                                                            }\n                                                            else\n                                                            {\n                                                                esp = PushNull(obj);\n                                                            }\n                                                        }\n                                                        break;\n                                                }\n                                            }\n                                        }\n                                        else\n                                        {\n                                            if (type.TypeForCLR.IsPrimitive)\n                                            {\n                                                var t = type.TypeForCLR;\n                                                if (t == typeof(int))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, 0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(bool))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (obj->Value == 1), true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, false, true);\n                                                            break;\n                                                        case ObjectTypes.Object:\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(byte))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (byte)obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, 0L, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(short))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (short)obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, (short)0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(long))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Long:\n                                                            esp = PushObject(obj, mStack, *(long*)&obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, 0L, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(float))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Float:\n                                                            esp = PushObject(obj, mStack, *(float*)&obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, 0f, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(double))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Double:\n                                                            esp = PushObject(obj, mStack, *(double*)&obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, 0.0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(char))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (char)obj->Value, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(uint))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (uint)obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, (uint)0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(ushort))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (ushort)obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, (ushort)0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(ulong))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Long:\n                                                            esp = PushObject(obj, mStack, *(ulong*)&obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, (ulong)0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else if (t == typeof(sbyte))\n                                                {\n                                                    switch (obj->ObjectType)\n                                                    {\n                                                        case ObjectTypes.Integer:\n                                                            esp = PushObject(obj, mStack, (sbyte)obj->Value, true);\n                                                            break;\n                                                        case ObjectTypes.Null:\n                                                            esp = PushObject(obj, mStack, (sbyte)0, true);\n                                                            break;\n                                                        default:\n                                                            throw new NotImplementedException();\n                                                    }\n                                                }\n                                                else\n                                                    throw new NotImplementedException();\n                                            }\n                                            else if (type.TypeForCLR.IsEnum)\n                                            {\n                                                esp = PushObject(obj, mStack, Enum.ToObject(type.TypeForCLR, StackObject.ToObject(obj, AppDomain, mStack)), true);\n                                            }\n                                            else\n                                            {\n                                                if(obj->ObjectType== ObjectTypes.ValueTypeObjectReference)\n                                                {\n                                                    var dst = *(StackObject**)&obj->Value;\n                                                    var vt = domain.GetType(dst->Value);\n                                                    if (vt != type)\n                                                        throw new InvalidCastException();\n                                                    object ins = ((CLRType)vt).ValueTypeBinder.ToObject(dst, mStack);\n                                                    FreeStackValueType(obj);\n                                                    esp = PushObject(obj, mStack, ins, true);\n                                                }\n                                                //nothing to do for CLR type boxing\n                                            }\n                                        }\n                                    }\n                                    else\n                                        throw new NullReferenceException();\n                                }\n                                break;\n                            case OpCodeEnum.Unbox:\n                            case OpCodeEnum.Unbox_Any:\n                                {\n                                    var objRef = esp - 1;\n                                    if (objRef->ObjectType == ObjectTypes.Object)\n                                    {\n                                        object obj = mStack[objRef->Value];\n                                        Free(objRef);\n                                        if (obj != null)\n                                        {\n                                            var t = domain.GetType(ip->TokenInteger);\n                                            if (t != null)\n                                            {\n                                                var type = t.TypeForCLR;\n                                                if ((t is CLRType) && type.IsPrimitive)\n                                                {\n                                                    if (type == typeof(int))\n                                                    {\n                                                        int val = obj.ToInt32();\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(bool))\n                                                    {\n                                                        bool val = (bool)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val ? 1 : 0;\n                                                    }\n                                                    else if (type == typeof(short))\n                                                    {\n                                                        short val = obj.ToInt16();\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(long))\n                                                    {\n                                                        long val = obj.ToInt64();\n                                                        objRef->ObjectType = ObjectTypes.Long;\n                                                        *(long*)&objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(float))\n                                                    {\n                                                        float val = obj.ToFloat();\n                                                        objRef->ObjectType = ObjectTypes.Float;\n                                                        *(float*)&objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(byte))\n                                                    {\n                                                        byte val = (byte)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(double))\n                                                    {\n                                                        double val = obj.ToDouble();\n                                                        objRef->ObjectType = ObjectTypes.Double;\n                                                        *(double*)&objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(char))\n                                                    {\n                                                        char val = (char)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        *(char*)&objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(uint))\n                                                    {\n                                                        uint val = (uint)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = (int)val;\n                                                    }\n                                                    else if (type == typeof(ushort))\n                                                    {\n                                                        ushort val = (ushort)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(ulong))\n                                                    {\n                                                        ulong val = (ulong)obj;\n                                                        objRef->ObjectType = ObjectTypes.Long;\n                                                        *(ulong*)&objRef->Value = val;\n                                                    }\n                                                    else if (type == typeof(sbyte))\n                                                    {\n                                                        sbyte val = (sbyte)obj;\n                                                        objRef->ObjectType = ObjectTypes.Integer;\n                                                        objRef->Value = val;\n                                                    }\n                                                    else\n                                                        throw new NotImplementedException();\n                                                }\n                                                else if (t.IsValueType)\n                                                {\n                                                    if (obj is ILTypeInstance)\n                                                    {\n                                                        var res = ((ILTypeInstance)obj);\n                                                        if (res is ILEnumTypeInstance)\n                                                        {\n                                                            res.PushToStack(0, objRef, AppDomain, mStack);\n                                                        }\n                                                        else\n                                                        {\n                                                            if (res.Boxed)\n                                                            {\n                                                                res = res.Clone();\n                                                                res.Boxed = false;\n                                                            }\n                                                            PushObject(objRef, mStack, res);\n                                                        }\n                                                    }\n                                                    else\n                                                        PushObject(objRef, mStack, obj);\n                                                }\n                                                else\n                                                {\n                                                    PushObject(objRef, mStack, obj);\n                                                }\n                                            }\n                                            else\n                                                throw new TypeLoadException();\n                                        }\n                                        else\n                                            throw new NullReferenceException();\n                                    }\n                                    else if (objRef->ObjectType < ObjectTypes.StackObjectReference)\n                                    {\n                                        //Nothing to do with primitive types\n                                    }\n                                    else\n                                        throw new InvalidCastException();\n                                }\n                                break;\n                            case OpCodeEnum.Initobj:\n                                {\n                                    var objRef = GetObjectAndResolveReference(esp - 1);\n                                    var type = domain.GetType(ip->TokenInteger);\n                                    if (type is ILType)\n                                    {\n                                        ILType it = (ILType)type;\n                                        if (it.IsValueType)\n                                        {\n                                            switch (objRef->ObjectType)\n                                            {\n                                                case ObjectTypes.Null:\n                                                    throw new NullReferenceException();\n                                                case ObjectTypes.ValueTypeObjectReference:\n                                                    stack.ClearValueTypeObject(type, *(StackObject**)&objRef->Value);\n                                                    break;\n                                                case ObjectTypes.Object:\n                                                    {\n                                                        var obj = mStack[objRef->Value];\n                                                        if (obj != null)\n                                                        {\n                                                            if (obj is ILTypeInstance)\n                                                            {\n                                                                ILTypeInstance instance = obj as ILTypeInstance;\n                                                                instance.Clear();\n                                                            }\n                                                            else\n                                                                throw new NotSupportedException();\n                                                        }\n                                                        else\n                                                            throw new NullReferenceException();\n                                                    }\n                                                    break;\n                                                default:\n                                                    throw new NotImplementedException();\n                                            }\n\n                                            Free(esp - 1);\n                                            esp--;\n                                        }\n                                        else\n                                        {\n                                            PushNull(esp);\n                                            switch (objRef->ObjectType)\n                                            {\n                                                case ObjectTypes.StaticFieldReference:\n                                                    {\n                                                        var t = AppDomain.GetType(objRef->Value) as ILType;\n                                                        t.StaticInstance.AssignFromStack(objRef->ValueLow, esp, AppDomain, mStack);\n                                                    }\n                                                    break;\n                                                case ObjectTypes.FieldReference:\n                                                    {\n                                                        var instance = mStack[objRef->Value] as ILTypeInstance;\n                                                        instance.AssignFromStack(objRef->ValueLow, esp, AppDomain, mStack);\n                                                        Free(esp - 1);\n                                                        esp--;\n                                                    }\n                                                    break;\n                                                default:\n                                                    {\n                                                        if (objRef->ObjectType >= ObjectTypes.Object)\n                                                            mStack[objRef->Value] = null;\n                                                        else\n                                                            PushNull(objRef);\n                                                    }\n                                                    break;\n                                            }\n                                        }\n                                    }\n                                    else\n                                    {\n                                        if (objRef->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                                        {\n                                            stack.ClearValueTypeObject(type, *(StackObject**)&objRef->Value);\n                                        }\n                                        Free(esp - 1);\n                                        esp--;\n                                    }\n                                }\n                                break;\n                            case OpCodeEnum.Isinst:\n                                {\n                                    var objRef = esp - 1;\n                                    var type = domain.GetType(ip->TokenInteger);\n                                    if (type != null)\n                                    {\n                                        objRef = GetObjectAndResolveReference(objRef);\n                                        if (objRef->ObjectType <= ObjectTypes.Double)\n                                        {\n                                            var tclr = type.TypeForCLR;\n                                            switch (objRef->ObjectType)\n                                            {\n                                                case ObjectTypes.Integer:\n                                                    {\n                                                        if (tclr != typeof(int) && tclr != typeof(bool) && tclr != typeof(short) && tclr != typeof(byte) && tclr != typeof(ushort) && tclr !=typeof(uint))\n                                                        {\n                                                            objRef->ObjectType = ObjectTypes.Null;\n                                                            objRef->Value = -1;\n                                                            objRef->ValueLow = 0;\n                                                        }\n                                                    }\n                                                    break;\n                                                case ObjectTypes.Long:\n                                                    {\n                                                        if (tclr != typeof(long) && tclr != typeof(ulong))\n                                                        {\n                                                            objRef->ObjectType = ObjectTypes.Null;\n                                                            objRef->Value = -1;\n                                                            objRef->ValueLow = 0;\n                                                        }\n                                                    }\n                                                    break;\n                                                case ObjectTypes.Float:\n                                                    {\n                                                        if (tclr != typeof(float))\n                                                        {\n                                                            objRef->ObjectType = ObjectTypes.Null;\n                                                            objRef->Value = -1;\n                                                            objRef->ValueLow = 0;\n                                                        }\n                                                    }\n                                                    break;\n                                                case ObjectTypes.Double:\n                                                    {\n                                                        if (tclr != typeof(double))\n                                                        {\n                                                            objRef->ObjectType = ObjectTypes.Null;\n                                                            objRef->Value = -1;\n                                                            objRef->ValueLow = 0;\n                                                        }\n                                                    }\n                                                    break;\n                                                case ObjectTypes.Null:\n                                                    objRef->ObjectType = ObjectTypes.Null;\n                                                    objRef->Value = -1;\n                                                    objRef->ValueLow = 0;\n                                                    break;\n                                            }\n                                        }\n                                        else\n                                        {\n                                            var obj = RetriveObject(objRef, mStack);\n                                            Free(objRef);\n\n                                            if (obj != null)\n                                            {\n                                                if (obj is ILTypeInstance)\n                                                {\n                                                    if (((ILTypeInstance)obj).CanAssignTo(type))\n                                                    {\n                                                        esp = PushObject(objRef, mStack, obj);\n                                                    }\n                                                    else\n                                                    {\n#if !DEBUG\n                                                        objRef->ObjectType = ObjectTypes.Null;\n                                                        objRef->Value = -1;\n                                                        objRef->ValueLow = 0;\n#endif\n                                                    }\n                                                }\n                                                else\n                                                {\n                                                    if (type.TypeForCLR.IsAssignableFrom(obj.GetType()))\n                                                    {\n                                                        esp = PushObject(objRef, mStack, obj, true);\n                                                    }\n                                                    else\n                                                    {\n#if !DEBUG\n                                                        objRef->ObjectType = ObjectTypes.Null;\n                                                        objRef->Value = -1;\n                                                        objRef->ValueLow = 0;\n#endif\n                                                    }\n                                                }\n                                            }\n                                            else\n                                            {\n#if !DEBUG\n                                                    objRef->ObjectType = ObjectTypes.Null;\n                                                    objRef->Value = -1;\n                                                    objRef->ValueLow = 0;\n#endif\n                                            }\n                                        }\n                                    }\n                                    else\n                                        throw new NullReferenceException();\n                                }\n                                break;\n                            #endregion\n\n                            #region Array\n                            case OpCodeEnum.Newarr:\n                                {\n                                    var cnt = (esp - 1);\n                                    var type = domain.GetType(ip->TokenInteger);\n                                    object arr = null;\n                                    if (type != null)\n                                    {\n                                        if (type.TypeForCLR != typeof(ILTypeInstance))\n                                        {\n                                            if (type is CLRType)\n                                            {\n                                                arr = ((CLRType)type).CreateArrayInstance(cnt->Value);\n                                            }\n                                            else\n                                            {\n                                                arr = Array.CreateInstance(type.TypeForCLR, cnt->Value);\n                                            }\n\n                                            //Register Type\n                                            AppDomain.GetType(arr.GetType());\n                                        }\n                                        else\n                                        {\n                                            arr = new ILTypeInstance[cnt->Value];\n                                        }\n                                    }\n                                    cnt->ObjectType = ObjectTypes.Object;\n                                    cnt->Value = mStack.Count;\n                                    mStack.Add(arr);\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_Ref:\n                            case OpCodeEnum.Stelem_Any:\n                                {\n                                    var val = GetObjectAndResolveReference(esp - 1);\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    Array arr = mStack[arrRef->Value] as Array;\n                                    if (arr is object[])\n                                    {\n                                        switch (val->ObjectType)\n                                        {\n                                            case ObjectTypes.Null:\n                                                arr.SetValue(null, idx->Value);\n                                                break;\n                                            case ObjectTypes.Object:\n                                                ArraySetValue(arr, mStack[val->Value], idx->Value);\n                                                break;\n                                            case ObjectTypes.Integer:\n                                                arr.SetValue(val->Value, idx->Value);\n                                                break;\n                                            case ObjectTypes.Long:\n                                                arr.SetValue(*(long*)&val->Value, idx->Value);\n                                                break;\n                                            case ObjectTypes.Float:\n                                                arr.SetValue(*(float*)&val->Value, idx->Value);\n                                                break;\n                                            case ObjectTypes.Double:\n                                                arr.SetValue(*(double*)&val->Value, idx->Value);\n                                                break;\n                                            default:\n                                                throw new NotImplementedException();\n                                        }\n                                    }\n                                    else\n                                    {\n                                        switch (val->ObjectType)\n                                        {\n                                            case ObjectTypes.Object:\n                                                ArraySetValue(arr, mStack[val->Value], idx->Value);\n                                                break;\n                                            case ObjectTypes.Integer:\n                                                {\n                                                    StoreIntValueToArray(arr, val, idx);\n                                                }\n                                                break;\n                                            case ObjectTypes.Long:\n                                                {\n                                                    if (arr is long[])\n                                                    {\n                                                        ((long[])arr)[idx->Value] = *(long*)&val->Value;\n                                                    }\n                                                    else\n                                                    {\n                                                        ((ulong[])arr)[idx->Value] = *(ulong*)&val->Value;\n                                                    }\n                                                }\n                                                break;\n                                            case ObjectTypes.Float:\n                                                {\n                                                    ((float[])arr)[idx->Value] = *(float*)&val->Value;\n                                                }\n                                                break;\n                                            case ObjectTypes.Double:\n                                                {\n                                                    ((double[])arr)[idx->Value] = *(double*)&val->Value;\n                                                }\n                                                break;\n                                            default:\n                                                throw new NotImplementedException();\n                                        }\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n\n                            case OpCodeEnum.Ldelem_Ref:\n                            case OpCodeEnum.Ldelem_Any:\n                                {\n                                    var idx = esp - 1;\n                                    var arrRef = esp - 1 - 1;\n                                    Array arr = mStack[arrRef->Value] as Array;\n                                    object val = arr.GetValue(idx->Value);\n                                    if (val is CrossBindingAdaptorType)\n                                        val = ((CrossBindingAdaptorType)val).ILInstance;\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    esp = PushObject(esp - 1 - 1, mStack, val);\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_I1:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    byte[] arr = mStack[arrRef->Value] as byte[];\n                                    if (arr != null)\n                                    {\n                                        arr[idx->Value] = (byte)val->Value;\n                                    }\n                                    else\n                                    {\n                                        bool[] arr2 = mStack[arrRef->Value] as bool[];\n                                        if (arr2 != null)\n                                        {\n                                            arr2[idx->Value] = val->Value == 1;\n                                        }\n                                        else\n                                        {\n                                            sbyte[] arr3 = mStack[arrRef->Value] as sbyte[];\n                                            arr3[idx->Value] = (sbyte)val->Value;\n                                        }\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_I1:\n                                {\n                                    var idx = esp - 1;\n                                    var arrRef = esp - 1 - 1;\n                                    bool[] arr = mStack[arrRef->Value] as bool[];\n                                    int val;\n                                    if (arr != null)\n                                        val = arr[idx->Value] ? 1 : 0;\n                                    else\n                                    {\n                                        sbyte[] arr2 = mStack[arrRef->Value] as sbyte[];\n                                        val = arr2[idx->Value];\n                                    }\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = val;\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_U1:\n                                {\n                                    var idx = (esp - 1);\n                                    var arrRef = esp - 1 - 1;\n                                    byte[] arr = mStack[arrRef->Value] as byte[];\n                                    int val;\n                                    if (arr != null)\n                                        val = arr[idx->Value];\n                                    else\n                                    {\n                                        bool[] arr2 = mStack[arrRef->Value] as bool[];\n                                        val = arr2[idx->Value] ? 1 : 0;\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = val;\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_I2:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    short[] arr = mStack[arrRef->Value] as short[];\n                                    if (arr != null)\n                                    {\n                                        arr[idx->Value] = (short)val->Value;\n                                    }\n                                    else\n                                    {\n                                        ushort[] arr2 = mStack[arrRef->Value] as ushort[];\n                                        if (arr2 != null)\n                                        {\n                                            arr2[idx->Value] = (ushort)val->Value;\n                                        }\n                                        else\n                                        {\n                                            char[] arr3 = mStack[arrRef->Value] as char[];\n                                            arr3[idx->Value] = (char)val->Value;\n                                        }\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_I2:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    short[] arr = mStack[arrRef->Value] as short[];\n                                    int val = 0;\n                                    if (arr != null)\n                                    {\n                                        val = arr[idx];\n                                    }\n                                    else\n                                    {\n                                        char[] arr2 = mStack[arrRef->Value] as char[];\n                                        val = arr2[idx];\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = val;\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_U2:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    ushort[] arr = mStack[arrRef->Value] as ushort[];\n                                    int val = 0;\n                                    if (arr != null)\n                                    {\n                                        val = arr[idx];\n                                    }\n                                    else\n                                    {\n                                        char[] arr2 = mStack[arrRef->Value] as char[];\n                                        val = arr2[idx];\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = val;\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_I4:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    int[] arr = mStack[arrRef->Value] as int[];\n                                    if (arr != null)\n                                    {\n                                        arr[idx->Value] = val->Value;\n                                    }\n                                    else\n                                    {\n                                        uint[] arr2 = mStack[arrRef->Value] as uint[];\n                                        arr2[idx->Value] = (uint)val->Value;\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_I4:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    int[] arr = mStack[arrRef->Value] as int[];\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = arr[idx];\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_U4:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    uint[] arr = mStack[arrRef->Value] as uint[];\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = (int)arr[idx];\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_I8:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    long[] arr = mStack[arrRef->Value] as long[];\n                                    if (arr != null)\n                                    {\n                                        arr[idx->Value] = *(long*)&val->Value;\n                                    }\n                                    else\n                                    {\n                                        ulong[] arr2 = mStack[arrRef->Value] as ulong[];\n                                        arr2[idx->Value] = *(ulong*)&val->Value;\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_I8:\n                                {\n                                    var idx = esp - 1;\n                                    var arrRef = esp - 1 - 1;\n                                    long[] arr = mStack[arrRef->Value] as long[];\n                                    long val;\n                                    if (arr != null)\n                                        val = arr[idx->Value];\n                                    else\n                                    {\n                                        ulong[] arr2 = mStack[arrRef->Value] as ulong[];\n                                        val = (long)arr2[idx->Value];\n                                    }\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Long;\n                                    *(long*)&arrRef->Value = val;\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_R4:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    float[] arr = mStack[arrRef->Value] as float[];\n                                    arr[idx->Value] = *(float*)&val->Value;\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_R4:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    float[] arr = mStack[arrRef->Value] as float[];\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Float;\n                                    *(float*)&arrRef->Value = arr[idx];\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Stelem_R8:\n                                {\n                                    var val = esp - 1;\n                                    var idx = esp - 1 - 1;\n                                    var arrRef = esp - 1 - 1 - 1;\n                                    double[] arr = mStack[arrRef->Value] as double[];\n                                    arr[idx->Value] = *(double*)&val->Value;\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n                                    Free(esp - 1 - 1 - 1);\n                                    esp = esp - 1 - 1 - 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelem_R8:\n                                {\n                                    var idx = (esp - 1)->Value;\n                                    var arrRef = esp - 1 - 1;\n                                    double[] arr = mStack[arrRef->Value] as double[];\n\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Double;\n                                    *(double*)&arrRef->Value = arr[idx];\n                                    esp -= 1;\n                                }\n                                break;\n                            case OpCodeEnum.Ldlen:\n                                {\n                                    var arrRef = esp - 1;\n                                    Array arr = mStack[arrRef->Value] as Array;\n                                    Free(esp - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.Integer;\n                                    arrRef->Value = arr.Length;\n                                }\n                                break;\n                            case OpCodeEnum.Ldelema:\n                                {\n                                    var arrRef = esp - 1 - 1;\n                                    var idx = (esp - 1)->Value;\n\n                                    Array arr = mStack[arrRef->Value] as Array;\n                                    Free(esp - 1);\n                                    Free(esp - 1 - 1);\n\n                                    arrRef->ObjectType = ObjectTypes.ArrayReference;\n                                    arrRef->Value = mStack.Count;\n                                    mStack.Add(arr);\n                                    arrRef->ValueLow = idx;\n                                    esp--;\n                                }\n                                break;\n                            #endregion\n\n                            #region Conversion\n                            case OpCodeEnum.Conv_U1:\n                            case OpCodeEnum.Conv_Ovf_U1:\n                            case OpCodeEnum.Conv_Ovf_U1_Un:\n                                {\n                                    var obj = esp - 1;\n                                    int val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                        case ObjectTypes.Integer:\n                                            val = (byte)obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (byte)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (byte)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = val;\n                                    obj->ValueLow = 0;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_I1:\n                            case OpCodeEnum.Conv_Ovf_I1:\n                            case OpCodeEnum.Conv_Ovf_I1_Un:\n                                {\n                                    var obj = esp - 1;\n                                    int val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                        case ObjectTypes.Integer:\n                                            val = (sbyte)obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (sbyte)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (sbyte)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = val;\n                                    obj->ValueLow = 0;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_U2:\n                            case OpCodeEnum.Conv_Ovf_U2:\n                            case OpCodeEnum.Conv_Ovf_U2_Un:\n                                {\n                                    var obj = esp - 1;\n                                    int val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                        case ObjectTypes.Integer:\n                                            val = (ushort)obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (ushort)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (ushort)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = val;\n                                    obj->ValueLow = 0;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_I2:\n                            case OpCodeEnum.Conv_Ovf_I2:\n                            case OpCodeEnum.Conv_Ovf_I2_Un:\n                                {\n                                    var obj = esp - 1;\n                                    int val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                        case ObjectTypes.Integer:\n                                            val = (short)(obj->Value);\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (short)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (short)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = val;\n                                    obj->ValueLow = 0;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_U4:\n                            case OpCodeEnum.Conv_Ovf_U4:\n                            case OpCodeEnum.Conv_Ovf_U4_Un:\n                                {\n                                    var obj = esp - 1;\n                                    uint val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            val = (uint)*(long*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            val = (uint)obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (uint)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (uint)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = (int)val;\n                                    obj->ValueLow = 0;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_I4:\n                            case OpCodeEnum.Conv_Ovf_I:\n                            case OpCodeEnum.Conv_Ovf_I_Un:\n                            case OpCodeEnum.Conv_Ovf_I4:\n                            case OpCodeEnum.Conv_Ovf_I4_Un:\n                                {\n                                    var obj = esp - 1;\n                                    int val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            val = (int)*(long*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = (int)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (int)*(double*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            val = obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Integer;\n                                    obj->Value = val;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_U8:\n                            case OpCodeEnum.Conv_I8:\n                            case OpCodeEnum.Conv_Ovf_I8:\n                            case OpCodeEnum.Conv_Ovf_I8_Un:\n                            case OpCodeEnum.Conv_Ovf_U8:\n                            case OpCodeEnum.Conv_Ovf_U8_Un:\n                                {\n                                    var obj = esp - 1;\n                                    long val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Integer:\n                                            val = obj->Value;\n                                            break;\n                                        case ObjectTypes.Long:\n                                            ip++;\n                                            continue;\n                                        case ObjectTypes.Float:\n                                            val = (long)*(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            val = (long)*(double*)&obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Long;\n                                    *(long*)(&obj->Value) = val;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_R4:\n                                {\n                                    var obj = esp - 1;\n                                    float val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            val = (float)*(long*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            ip++;\n                                            continue;\n                                        case ObjectTypes.Double:\n                                            val = (float)*(double*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            val = obj->Value;\n                                            break;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Float;\n                                    *(float*)&obj->Value = val;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_R8:\n                                {\n                                    var obj = esp - 1;\n                                    double val;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            val = (double)*(long*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            val = *(float*)&obj->Value;\n                                            break;\n                                        case ObjectTypes.Integer:\n                                            val = obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            ip++;\n                                            continue;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    obj->ObjectType = ObjectTypes.Double;\n                                    *(double*)&obj->Value = val;\n                                }\n                                break;\n                            case OpCodeEnum.Conv_R_Un:\n                                {\n                                    var obj = esp - 1;\n                                    bool isDouble = false;\n                                    float val = 0;\n                                    double val2 = 0;\n                                    switch (obj->ObjectType)\n                                    {\n                                        case ObjectTypes.Long:\n                                            val2 = (double)*(ulong*)&obj->Value;\n                                            isDouble = true;\n                                            break;\n                                        case ObjectTypes.Float:\n                                            ip++;\n                                            continue;\n                                        case ObjectTypes.Integer:\n                                            val = (uint)obj->Value;\n                                            break;\n                                        case ObjectTypes.Double:\n                                            ip++;\n                                            continue;\n                                        default:\n                                            throw new NotImplementedException();\n                                    }\n                                    if (isDouble)\n                                    {\n                                        obj->ObjectType = ObjectTypes.Double;\n                                        *(double*)&obj->Value = val2;\n                                    }\n                                    else\n                                    {\n                                        obj->ObjectType = ObjectTypes.Float;\n                                        *(float*)&obj->Value = val;\n                                    }\n                                }\n                                break;\n                            #endregion\n\n                            #region Stack operation\n                            case OpCodeEnum.Pop:\n                                {\n                                    Free(esp - 1);\n                                    esp--;\n                                }\n                                break;\n                            case OpCodeEnum.Dup:\n                                {\n                                    var obj = esp - 1;\n                                    *esp = *obj;\n                                    if (esp->ObjectType >= ObjectTypes.Object)\n                                    {\n                                        esp->Value = mStack.Count;\n                                        mStack.Add(mStack[obj->Value]);\n                                    }\n                                    esp++;\n                                }\n                                break;\n                            #endregion\n\n                            case OpCodeEnum.Throw:\n                                {\n                                    var obj = GetObjectAndResolveReference(esp - 1);\n                                    var ex = mStack[obj->Value] as Exception;\n                                    Free(obj);\n                                    esp--;\n                                    throw ex;\n                                }\n                            case OpCodeEnum.Nop:\n                            case OpCodeEnum.Volatile:\n                            case OpCodeEnum.Castclass:\n                                break;\n                            default:\n                                throw new NotSupportedException(\"Not supported opcode \" + code);\n                        }\n                        ip++;\n                    }\n                    catch (Exception ex)\n                    {\n                        if (method.ExceptionHandler != null)\n                        {\n                            int addr = (int)(ip - ptr);\n                            var eh = GetCorrespondingExceptionHandler(method, ex, addr, ExceptionHandlerType.Catch, true);\n\n                            if (eh == null)\n                            {\n                                eh = GetCorrespondingExceptionHandler(method, ex, addr, ExceptionHandlerType.Catch, false);\n                            }\n                            if (eh != null)\n                            {\n                                if (ex is ILRuntimeException)\n                                {\n                                    ILRuntimeException ire = (ILRuntimeException)ex;\n                                    var inner = ire.InnerException;\n                                    inner.Data[\"ThisInfo\"] = ire.ThisInfo;\n                                    inner.Data[\"StackTrace\"] = ire.StackTrace;\n                                    inner.Data[\"LocalInfo\"] = ire.LocalInfo;\n                                    ex = inner;\n                                }\n                                else\n                                {\n                                    var debugger = AppDomain.DebugService;\n                                    if (method.HasThis)\n                                        ex.Data[\"ThisInfo\"] = debugger.GetThisInfo(this);\n                                    else\n                                        ex.Data[\"ThisInfo\"] = \"\";\n                                    ex.Data[\"StackTrace\"] = debugger.GetStackTrance(this);\n                                    ex.Data[\"LocalInfo\"] = debugger.GetLocalVariableInfo(this);\n                                }\n                                //Clear call stack\n                                while (stack.Frames.Peek().BasePointer != frame.BasePointer)\n                                {\n                                    var f = stack.Frames.Peek();\n                                    esp = stack.PopFrame(ref f, esp);\n                                    if (f.Method.ReturnType != AppDomain.VoidType)\n                                    {\n                                        Free(esp - 1);\n                                        esp--;\n                                    }\n                                }\n                                esp = PushObject(esp, mStack, ex);\n                                unhandledException = false;\n                                ip = ptr + eh.HandlerStart;\n                                continue;\n                            }\n                        }\n                        if (unhandledException)\n                        {\n                            throw ex;\n                        }\n\n                        unhandledException = true;\n                        returned = true;\n#if DEBUG\n                        if (!AppDomain.DebugService.Break(this, ex))\n#endif\n                        {\n                            var newEx = new ILRuntimeException(ex.Message, this, method, ex);\n                            throw newEx;\n                        }\n                    }\n                }\n            }\n#if UNITY_EDITOR\n            if (System.Threading.Thread.CurrentThread.ManagedThreadId == AppDomain.UnityMainThreadID)\n#if UNITY_5_5_OR_NEWER\n                UnityEngine.Profiling.Profiler.EndSample();\n#else\n                UnityEngine.Profiler.EndSample();\n#endif\n#endif\n            //ClearStack\n            return stack.PopFrame(ref frame, esp);\n        }\n\n        void DumpStack(StackObject* esp)\n        {\n            AppDomain.DebugService.DumpStack(esp, stack);\n        }\n\n        void CloneStackValueType(StackObject* src, StackObject* dst, IList<object> mStack)\n        {\n            StackObject* descriptor = *(StackObject**)&src->Value;\n            stack.AllocValueType(dst, AppDomain.GetType(descriptor->Value));\n            StackObject* dstDescriptor = *(StackObject**)&dst->Value;\n            int cnt = descriptor->ValueLow;\n            for(int i = 0; i < cnt; i++)\n            {\n                StackObject* val = Minus(descriptor, i + 1);\n                CopyToValueTypeField(dstDescriptor, i, val, mStack);\n            }\n        }\n\n        void CopyStackValueType(StackObject* src, StackObject* dst, IList<object> mStack)\n        {\n            StackObject* descriptor = *(StackObject**)&src->Value;\n            StackObject* dstDescriptor = *(StackObject**)&dst->Value;\n            if (descriptor->Value != dstDescriptor->Value)\n                throw new InvalidCastException();\n            int cnt = descriptor->ValueLow;\n            for(int i = 0; i < cnt; i++)\n            {\n                StackObject* srcVal = Minus(descriptor, i + 1);\n                StackObject* dstVal = Minus(dstDescriptor, i + 1);\n                if (srcVal->ObjectType != dstVal->ObjectType)\n                    throw new NotSupportedException();\n                switch (dstVal->ObjectType)\n                {\n                    case ObjectTypes.Object:\n                    case ObjectTypes.ArrayReference:\n                    case ObjectTypes.FieldReference:\n                        mStack[dstVal->Value] = mStack[srcVal->Value];\n                        break;\n                    case ObjectTypes.ValueTypeObjectReference:\n                        CopyStackValueType(srcVal, dstVal, mStack);\n                        break;\n                    default:\n                        *dstVal = *srcVal;\n                        break;\n                }\n            }\n        }\n\n        void CopyToValueTypeField(StackObject* obj, int idx, StackObject* val, IList<object> mStack)\n        {\n            StackObject* dst = Minus(obj, idx + 1);\n            switch (val->ObjectType)\n            {\n                case ObjectTypes.Null:\n                    {\n                        mStack[dst->Value] = null;\n                    }\n                    break;\n                case ObjectTypes.Object:\n                case ObjectTypes.FieldReference:\n                case ObjectTypes.ArrayReference:\n                    {\n                        if (dst->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                        {\n                            var ins = mStack[val->Value];\n                            dst = *(StackObject**)&dst->Value;\n\n                            if (ins is ILTypeInstance)\n                            {\n                                ((ILTypeInstance)ins).CopyValueTypeToStack(dst, mStack);\n                            }\n                            else\n                            {\n                                var vb = ((CLRType)domain.GetType(dst->Value)).ValueTypeBinder;\n                                vb.CopyValueTypeToStack(ins, dst, mStack);\n                            }\n                        }\n                        else\n                        {\n                            mStack[dst->Value] = CheckAndCloneValueType(mStack[val->Value], domain);                            \n                        }\n                    }\n                    break;\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        if (dst->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                        {\n                            CopyStackValueType(val, dst, mStack);\n                        }\n                        else\n                            throw new NotImplementedException();\n                    }\n                    break;\n                default:\n                    *dst = *val;\n                    break;\n            }\n        }\n\n        void StLocSub(StackObject* esp, StackObject* v, StackObject* bp, int idx, IList<object> mStack)\n        {\n            switch (esp->ObjectType)\n            {\n                case ObjectTypes.Null:\n                    v->ObjectType = ObjectTypes.Object;\n                    v->Value = idx;\n                    mStack[idx] = null;\n                    break;\n                case ObjectTypes.Object:\n                case ObjectTypes.FieldReference:\n                case ObjectTypes.ArrayReference:\n                    if (v->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                    {\n                        var obj = mStack[esp->Value];\n                        if (obj is ILTypeInstance)\n                        {\n                            var dst = *(StackObject**)&v->Value;\n                            ((ILTypeInstance)obj).CopyValueTypeToStack(dst, mStack);\n                        }\n                        else\n                        {\n                            var dst = *(StackObject**)&v->Value;\n                            var ct = domain.GetType(dst->Value) as CLRType;\n                            var binder = ct.ValueTypeBinder;\n                            binder.CopyValueTypeToStack(obj, dst, mStack);\n                        }                            \n                    }\n                    else\n                    {\n                        *v = *esp;\n                        mStack[idx] = CheckAndCloneValueType(mStack[v->Value], domain);\n                        v->Value = idx;\n                    }\n                    Free(esp);\n                    break;\n                case ObjectTypes.ValueTypeObjectReference:\n                    if (v->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                    {\n                        CopyStackValueType(esp, v, mStack);\n                    }\n                    else\n                        throw new NotImplementedException();\n                    FreeStackValueType(esp);\n                    break;\n                default:\n                    *v = *esp;\n                    mStack[idx] = null;\n                    break;\n            }\n        }\n\n        object RetriveObject(StackObject* esp, IList<object> mStack)\n        {\n            StackObject* objRef = GetObjectAndResolveReference(esp);\n            if (objRef->ObjectType == ObjectTypes.Null)\n                return null;\n            object obj = null;\n            switch (objRef->ObjectType)\n            {\n                case ObjectTypes.Object:\n                    obj = mStack[objRef->Value];\n                    break;\n                case ObjectTypes.FieldReference:\n                    {\n                        obj = mStack[objRef->Value];\n                        int idx = objRef->ValueLow;\n                        if (obj is ILTypeInstance)\n                        {\n                            obj = ((ILTypeInstance)obj)[idx];\n                        }\n                        else\n                        {\n                            var t = AppDomain.GetType(obj.GetType());\n                            obj = ((CLRType) t).GetFieldValue(idx, obj);\n                        }\n                    }\n                    break;\n                case ObjectTypes.ArrayReference:\n                    {\n                        Array arr = mStack[objRef->Value] as Array;\n                        int idx = objRef->ValueLow;\n                        obj = arr.GetValue(idx);\n                        obj = obj.GetType().CheckCLRTypes(obj);\n                    }\n                    break;\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = AppDomain.GetType(objRef->Value);\n                        int idx = objRef->ValueLow;\n                        if (t is ILType)\n                        {\n                            obj = ((ILType)t).StaticInstance[idx];\n                        }\n                        else\n                        {\n                            obj = ((CLRType)t).GetFieldValue(idx, null);\n                        }\n                    }\n                    break;\n                default:\n                    throw new NotImplementedException();\n            }\n            return obj;\n        }\n\n        void ArraySetValue(Array arr, object obj, int idx)\n        {\n            if (obj == null)\n                arr.SetValue(null, idx);\n            else\n                arr.SetValue(arr.GetType().GetElementType().CheckCLRTypes(obj), idx);\n        }\n\n        void StoreIntValueToArray(Array arr, StackObject* val, StackObject* idx)\n        {\n            {\n                int[] tmp = arr as int[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = val->Value;\n                    return;\n                }\n            }\n            {\n                short[] tmp = arr as short[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (short)val->Value;\n                    return;\n                }\n            }\n            {\n                byte[] tmp = arr as byte[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (byte)val->Value;\n                    return;\n                }\n            }\n            {\n                bool[] tmp = arr as bool[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = val->Value == 1;\n                    return;\n                }\n            }\n            {\n                uint[] tmp = arr as uint[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (uint)val->Value;\n                    return;\n                }\n            }\n            {\n                ushort[] tmp = arr as ushort[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (ushort)val->Value;\n                    return;\n                }\n            }\n            {\n                char[] tmp = arr as char[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (char)val->Value;\n                    return;\n                }\n            }\n            {\n                sbyte[] tmp = arr as sbyte[];\n                if (tmp != null)\n                {\n                    tmp[idx->Value] = (sbyte)val->Value;\n                    return;\n                }\n            }\n            throw new NotImplementedException();\n        }\n\n        ExceptionHandler GetCorrespondingExceptionHandler(ILMethod method, object obj, int addr, ExceptionHandlerType type, bool explicitMatch)\n        {\n            ExceptionHandler res = null;\n            int distance = int.MaxValue;\n            Exception ex = obj is ILRuntimeException ? ((ILRuntimeException)obj).InnerException : obj as Exception;\n            foreach (var i in method.ExceptionHandler)\n            {\n                if (i.HandlerType == type)\n                {\n                    if (addr >= i.TryStart && addr <= i.TryEnd)\n                    {\n                        if (CheckExceptionType(i.CatchType, ex, explicitMatch))\n                        {\n                            int d = addr - i.TryStart;\n                            if (d < distance)\n                            {\n                                distance = d;\n                                res = i;\n                            }\n                        }\n                    }\n                }\n            }\n            return res;\n        }\n\n        void LoadFromFieldReference(object obj, int idx, StackObject* dst, IList<object> mStack)\n        {\n            if (obj is ILTypeInstance)\n            {\n                ((ILTypeInstance)obj).PushToStack(idx, dst, AppDomain, mStack);\n            }\n            else\n            {\n                CLRType t = AppDomain.GetType(obj.GetType()) as CLRType;\n                ILIntepreter.PushObject(dst, mStack, t.GetFieldValue(idx, obj));\n            }\n        }\n\n        void StoreValueToFieldReference(object obj, int idx, StackObject* val, IList<object> mStack)\n        {\n            if (obj is ILTypeInstance)\n            {\n                ((ILTypeInstance)obj).AssignFromStack(idx, val, AppDomain, mStack);\n            }\n            else\n            {\n                CLRType t = AppDomain.GetType(obj.GetType()) as CLRType;\n                var v = obj.GetType().CheckCLRTypes(CheckAndCloneValueType(StackObject.ToObject(val, AppDomain, mStack), AppDomain));\n                t.SetFieldValue(idx, ref obj, v);\n            }\n        }\n\n        void LoadFromArrayReference(object obj, int idx, StackObject* objRef, IType t, IList<object> mStack)\n        {\n            var nT = t.TypeForCLR;\n            LoadFromArrayReference(obj, idx, objRef, nT, mStack);\n        }\n\n        void LoadFromArrayReference(object obj, int idx, StackObject* objRef, Type nT, IList<object> mStack)\n        {\n            if (nT.IsPrimitive)\n            {\n                if (nT == typeof(int))\n                {\n                    int[] arr = obj as int[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(short))\n                {\n                    short[] arr = obj as short[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(long))\n                {\n                    long[] arr = obj as long[];\n                    objRef->ObjectType = ObjectTypes.Long;\n                    *(long*)&objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(float))\n                {\n                    float[] arr = obj as float[];\n                    objRef->ObjectType = ObjectTypes.Float;\n                    *(float*)&objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(double))\n                {\n                    double[] arr = obj as double[];\n                    objRef->ObjectType = ObjectTypes.Double;\n                    *(double*)&objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(byte))\n                {\n                    byte[] arr = obj as byte[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(char))\n                {\n                    char[] arr = obj as char[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(uint))\n                {\n                    uint[] arr = obj as uint[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    *(uint*)&objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else if (nT == typeof(sbyte))\n                {\n                    sbyte[] arr = obj as sbyte[];\n                    objRef->ObjectType = ObjectTypes.Integer;\n                    objRef->Value = arr[idx];\n                    objRef->ValueLow = 0;\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                Array arr = obj as Array;\n                objRef->ObjectType = ObjectTypes.Object;\n                objRef->Value = mStack.Count;\n                mStack.Add(arr.GetValue(idx));\n                objRef->ValueLow = 0;\n            }\n        }\n\n        void StoreValueToArrayReference(StackObject* objRef, StackObject* val, IType t, IList<object> mStack)\n        {\n            var nT = t.TypeForCLR;\n            StoreValueToArrayReference(objRef, val, nT, mStack);\n        }\n\n        void StoreValueToArrayReference(StackObject* objRef, StackObject* val, Type nT, IList<object> mStack)\n        {\n            if (nT.IsPrimitive)\n            {\n                if (nT == typeof(int))\n                {\n                    int[] arr = mStack[objRef->Value] as int[];\n                    arr[objRef->ValueLow] = val->Value;\n                }\n                else if (nT == typeof(short))\n                {\n                    short[] arr = mStack[objRef->Value] as short[];\n                    arr[objRef->ValueLow] = (short)val->Value;\n                }\n                else if (nT == typeof(long))\n                {\n                    long[] arr = mStack[objRef->Value] as long[];\n                    arr[objRef->ValueLow] = *(long*)&val->Value;\n                }\n                else if (nT == typeof(float))\n                {\n                    float[] arr = mStack[objRef->Value] as float[];\n                    arr[objRef->ValueLow] = *(float*)&val->Value;\n                }\n                else if (nT == typeof(double))\n                {\n                    double[] arr = mStack[objRef->Value] as double[];\n                    arr[objRef->ValueLow] = *(double*)&val->Value;\n                }\n                else if (nT == typeof(byte))\n                {\n                    byte[] arr = mStack[objRef->Value] as byte[];\n                    arr[objRef->ValueLow] = (byte)val->Value;\n                }\n                else if (nT == typeof(char))\n                {\n                    char[] arr = mStack[objRef->Value] as char[];\n                    arr[objRef->ValueLow] = (char)val->Value;\n                }\n                else if (nT == typeof(uint))\n                {\n                    uint[] arr = mStack[objRef->Value] as uint[];\n                    arr[objRef->ValueLow] = (uint)val->Value;\n                }\n                else if (nT == typeof(sbyte))\n                {\n                    sbyte[] arr = mStack[objRef->Value] as sbyte[];\n                    arr[objRef->ValueLow] = (sbyte)val->Value;\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                Array arr = mStack[objRef->Value] as Array;\n                arr.SetValue(mStack[val->Value], objRef->ValueLow);\n            }\n        }\n\n        bool CheckExceptionType(IType catchType, object exception, bool explicitMatch)\n        {\n            if (catchType is CLRType)\n            {\n                if (explicitMatch)\n                    return exception.GetType() == catchType.TypeForCLR;\n                else\n                    return catchType.TypeForCLR.IsAssignableFrom(exception.GetType());\n            }\n            else\n                throw new NotImplementedException();\n        }\n\n        public static StackObject* GetObjectAndResolveReference(StackObject* esp)\n        {\n            if (esp->ObjectType == ObjectTypes.StackObjectReference)\n            {\n                return *(StackObject**)&esp->Value;\n            }\n            else\n                return esp;\n        }\n\n        StackObject* PushParameters(IMethod method, StackObject* esp, object[] p)\n        {\n            IList<object> mStack = stack.ManagedStack;\n            var plist = method.Parameters;\n            int pCnt = plist != null ? plist.Count : 0;\n            int pCnt2 = p != null ? p.Length : 0;\n            if (pCnt != pCnt2)\n                throw new ArgumentOutOfRangeException(\"Parameter mismatch\");\n            if (pCnt2 > 0)\n            {\n                for (int i = 0; i < p.Length; i++)\n                {\n                    bool isBox = false;\n                    if (plist != null && i < plist.Count)\n                        isBox = plist[i] == AppDomain.ObjectType;\n                    object obj = p[i];\n                    if (obj is CrossBindingAdaptorType)\n                        obj = ((CrossBindingAdaptorType)obj).ILInstance;\n                    esp = ILIntepreter.PushObject(esp, mStack, obj, isBox);\n                }\n            }\n            return esp;\n        }\n\n        public void CopyToStack(StackObject* dst, StackObject* src, IList<object> mStack)\n        {\n            *dst = *src;\n            if (dst->ObjectType >= ObjectTypes.Object)\n            {\n                dst->Value = mStack.Count;\n                var obj = mStack[src->Value];\n                mStack.Add(obj);\n            }\n        }\n\n        internal static object CheckAndCloneValueType(object obj, Enviorment.AppDomain domain)\n        {\n            if (obj != null)\n            {\n                if (obj is ILTypeInstance)\n                {\n                    ILTypeInstance ins = obj as ILTypeInstance;\n                    if (ins.IsValueType)\n                    {\n                        return ins.Clone();\n                    }\n                }\n                else\n                {\n                    var type = obj.GetType();\n                    var typeFlags = type.GetTypeFlags();\n\n                    var isPrimitive = (typeFlags & CLR.Utils.Extensions.TypeFlags.IsPrimitive) != 0;\n                    var isValueType = (typeFlags & CLR.Utils.Extensions.TypeFlags.IsValueType) != 0;\n\n                    if (!isPrimitive && isValueType)\n                    {\n                        var t = domain.GetType(type);\n                        return ((CLRType)t).PerformMemberwiseClone(obj);\n                    }\n                }\n            }\n            return obj;\n        }\n        public static StackObject* PushOne(StackObject* esp)\n        {\n            esp->ObjectType = ObjectTypes.Integer;\n            esp->Value = 1;\n            return esp + 1;\n        }\n\n        public static StackObject* PushZero(StackObject* esp)\n        {\n            esp->ObjectType = ObjectTypes.Integer;\n            esp->Value = 0;\n            return esp + 1;\n        }\n\n        public static StackObject* PushNull(StackObject* esp)\n        {\n            esp->ObjectType = ObjectTypes.Null;\n            esp->Value = -1;\n            esp->ValueLow = 0;\n            return esp + 1;\n        }\n\n        public static void UnboxObject(StackObject* esp, object obj)\n        {\n            if (obj is int)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (int)obj;\n            }\n            else if (obj is bool)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (bool)(obj) ? 1 : 0;\n            }\n            else if (obj is short)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (short)obj;\n            }\n            else if (obj is long)\n            {\n                esp->ObjectType = ObjectTypes.Long;\n                *(long*)(&esp->Value) = (long)obj;\n            }\n            else if (obj is float)\n            {\n                esp->ObjectType = ObjectTypes.Float;\n                *(float*)(&esp->Value) = (float)obj;\n            }\n            else if (obj is byte)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (byte)obj;\n            }\n            else if (obj is uint)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (int)(uint)obj;\n            }\n            else if (obj is ushort)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (int)(ushort)obj;\n            }\n            else if (obj is char)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (int)(char)obj;\n            }\n            else if (obj is double)\n            {\n                esp->ObjectType = ObjectTypes.Double;\n                *(double*)(&esp->Value) = (double)obj;\n            }\n            else if (obj is ulong)\n            {\n                esp->ObjectType = ObjectTypes.Long;\n                *(ulong*)(&esp->Value) = (ulong)obj;\n            }\n            else if (obj is sbyte)\n            {\n                esp->ObjectType = ObjectTypes.Integer;\n                esp->Value = (sbyte)obj;\n            }\n            else\n                throw new NotImplementedException();\n        }\n\n        public static StackObject* PushObject(StackObject* esp, IList<object> mStack, object obj, bool isBox = false)\n        {\n            if (obj != null)\n            {\n                if (!isBox)\n                {\n                    var typeFlags = obj.GetType().GetTypeFlags();\n\n                    if ((typeFlags & CLR.Utils.Extensions.TypeFlags.IsPrimitive) != 0)\n                    {\n                        UnboxObject(esp, obj);\n                    }\n                    else if ((typeFlags & CLR.Utils.Extensions.TypeFlags.IsEnum) != 0)\n                    {\n                        esp->ObjectType = ObjectTypes.Integer;\n                        esp->Value = Convert.ToInt32(obj);\n                    }\n                    else\n                    {\n                        esp->ObjectType = ObjectTypes.Object;\n                        esp->Value = mStack.Count;\n                        mStack.Add(obj);\n                    }\n                }\n                else\n                {\n                    esp->ObjectType = ObjectTypes.Object;\n                    esp->Value = mStack.Count;\n                    mStack.Add(obj);\n                }\n            }\n            else\n            {\n                return PushNull(esp);\n            }\n            return esp + 1;\n        }\n\n        //Don't ask me why add this funky method for this, otherwise Unity won't calculate the right value\n        public static StackObject* Add(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a + sizeof(StackObject) * b);\n        }\n\n        public static StackObject* Minus(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a - sizeof(StackObject) * b);\n        }\n\n        public void Free(StackObject* esp)\n        {\n            if (esp->ObjectType >= ObjectTypes.Object)\n            {\n                if (esp->Value == stack.ManagedStack.Count - 1)\n                    stack.ManagedStack.RemoveAt(esp->Value);\n            }\n#if DEBUG\n            esp->ObjectType = ObjectTypes.Null;\n            esp->Value = -1;\n            esp->ValueLow = 0;\n#endif\n        }\n        public void FreeStackValueType(StackObject* esp)\n        {\n            if (esp->ObjectType == ObjectTypes.ValueTypeObjectReference)\n            {\n                var addr = *(StackObject**)&esp->Value;\n                if (addr <= ValueTypeBasePointer)//Only Stack allocation after base pointer should be freed, local variable are freed automatically\n                    stack.FreeValueTypeObject(esp);\n            }\n        }\n\n        public void AllocValueType(StackObject* ptr, IType type)\n        {\n            stack.AllocValueType(ptr, type);\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Intepreter/ILRuntimeException.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.Runtime.Stack;\n\nnamespace ILRuntime.Runtime.Intepreter\n{\n    public class ILRuntimeException : Exception\n    {\n        string stackTrace;\n        string thisInfo, localInfo;\n        internal ILRuntimeException(string message, ILIntepreter intepreter, CLR.Method.ILMethod method, Exception innerException = null)\n            : base(message, innerException)\n        \n        {\n            var ds = intepreter.AppDomain.DebugService;\n            if (innerException is ILRuntimeException)\n            {\n                ILRuntimeException e = innerException as ILRuntimeException;\n                stackTrace = e.stackTrace;\n                thisInfo = e.thisInfo;\n                localInfo = e.localInfo;\n            }\n            else\n            {\n                stackTrace = ds.GetStackTrance(intepreter);\n                if (method.HasThis)\n                    thisInfo = ds.GetThisInfo(intepreter);\n                else\n                    thisInfo = \"\";\n                localInfo = ds.GetLocalVariableInfo(intepreter);\n            }\n        }\n\n        public override string StackTrace\n        {\n            get\n            {\n                return stackTrace;\n            }\n        }\n\n        public string ThisInfo\n        {\n            get { return thisInfo; }\n        }\n\n        public string LocalInfo\n        {\n            get\n            {\n                return localInfo;\n            }\n        }\n\n        public override string ToString()\n        {\n            StringBuilder message = new StringBuilder();\n            message.AppendLine(Message);\n            if (!string.IsNullOrEmpty(ThisInfo))\n            {\n                message.AppendLine(\"this:\");\n                message.AppendLine(ThisInfo);\n            }\n            message.AppendLine(\"Local Variables:\");\n            message.AppendLine(LocalInfo);\n            message.AppendLine(StackTrace);\n            if (InnerException != null)\n                message.AppendLine(InnerException.ToString());\n            return message.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Intepreter/ILTypeInstance.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.Utils;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Stack;\nnamespace ILRuntime.Runtime.Intepreter\n{\n    public class ILTypeStaticInstance : ILTypeInstance\n    {\n        public unsafe ILTypeStaticInstance(ILType type)\n        {\n            this.type = type;\n            fields = new StackObject[type.StaticFieldTypes.Length];\n            managedObjs = new List<object>(fields.Length);\n            for (int i = 0; i < fields.Length; i++)\n            {\n                var ft = type.StaticFieldTypes[i];\n                var t = ft.TypeForCLR;\n                managedObjs.Add(null);\n                StackObject.Initialized(ref fields[i], i, t, ft, managedObjs);\n            }\n            int idx = 0;\n            foreach (var i in type.TypeDefinition.Fields)\n            {\n                if (i.IsStatic)\n                {\n                    if (i.InitialValue != null && i.InitialValue.Length > 0)\n                    {\n                        fields[idx].ObjectType = ObjectTypes.Object;\n                        managedObjs[idx] = i.InitialValue;\n                    }\n                    idx++;\n                }\n            }\n        }\n    }\n\n    unsafe class ILEnumTypeInstance : ILTypeInstance\n    {\n        public ILEnumTypeInstance(ILType type)\n        {\n            if (!type.IsEnum)\n                throw new NotSupportedException();\n            this.type = type;\n            fields = new StackObject[1];\n        }\n\n        public override string ToString()\n        {\n            var fields = type.TypeDefinition.Fields;\n            long longVal = 0;\n            int intVal = 0;\n            bool isLong = this.fields[0].ObjectType == ObjectTypes.Long;\n            if (isLong)\n            {\n                fixed (StackObject* f = this.fields)\n                    longVal = *(long*)&f->Value;\n            }\n            else\n                intVal = this.fields[0].Value;\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var f = fields[i];\n                if (f.IsStatic)\n                {\n                    if (isLong)\n                    {\n                        long val = f.Constant is long ? (long)f.Constant : (long)(ulong)f.Constant;\n                        if (val == longVal)\n                            return f.Name;\n                    }\n                    else\n                    {\n                        if (f.Constant is int)\n                        {\n                            if ((int)f.Constant == intVal)\n                                return f.Name;\n                        }\n                        else if (f.Constant is short)\n                        {\n                            if ((short)f.Constant == intVal)\n                                return f.Name;\n                        }\n                        else if (f.Constant is byte)\n                        {\n                            if ((byte)f.Constant == intVal)\n                                return f.Name;\n                        }\n                        else\n                            throw new NotImplementedException();\n                    }\n                }\n            }\n            return isLong ? longVal.ToString() : intVal.ToString();\n        }\n    }\n\n    public class ILTypeInstance\n    {\n        protected ILType type;\n        protected StackObject[] fields;\n        protected IList<object> managedObjs;\n        object clrInstance;\n        Dictionary<ILMethod, IDelegateAdapter> delegates;\n\n        public ILType Type\n        {\n            get\n            {\n                return type;\n            }\n        }\n\n        public StackObject[] Fields\n        {\n            get { return fields; }\n        }\n\n        public virtual bool IsValueType\n        {\n            get\n            {\n                return type.IsValueType && !Boxed;\n            }\n        }\n\n        /// <summary>\n        /// 是否已装箱\n        /// </summary>\n        public bool Boxed { get; set; }\n\n        public IList<object> ManagedObjects { get { return managedObjs; } }\n\n        public object CLRInstance { get { return clrInstance; } set { clrInstance = value; } }\n\n        protected ILTypeInstance()\n        {\n\n        }\n        public ILTypeInstance(ILType type, bool initializeCLRInstance = true)\n        {\n            this.type = type;\n            fields = new StackObject[type.TotalFieldCount];\n            managedObjs = new List<object>(fields.Length);\n            for (int i = 0; i < fields.Length; i++)\n            {\n                managedObjs.Add(null);\n            }\n            InitializeFields(type);\n            if (initializeCLRInstance)\n            {\n                if (type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n                {\n                    clrInstance = ((Enviorment.CrossBindingAdaptor)type.FirstCLRBaseType).CreateCLRInstance(type.AppDomain, this);\n                }\n                else\n                {\n                    clrInstance = this;\n                }\n                if(type.FirstCLRInterface is Enviorment.CrossBindingAdaptor)\n                {\n                    if (clrInstance != this)//Only one CLRInstance is allowed atm, so implementing multiple interfaces is not supported\n                    {\n                        throw new NotSupportedException(\"Inheriting and implementing interface at the same time is not supported yet\");\n                    }\n                    clrInstance = ((Enviorment.CrossBindingAdaptor)type.FirstCLRInterface).CreateCLRInstance(type.AppDomain, this);\n                }\n            }\n            else\n                clrInstance = this;\n        }\n\n        public unsafe object this[int index]\n        {\n            get\n            {\n                if (index < fields.Length && index >= 0)\n                {\n                    fixed (StackObject* ptr = fields)\n                    {\n                        StackObject* esp = &ptr[index];\n                        return StackObject.ToObject(esp, null, managedObjs);\n                    }\n                }\n                else\n                {\n                    if (Type.FirstCLRBaseType != null && Type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n                    {\n                        CLRType clrType = type.AppDomain.GetType(((Enviorment.CrossBindingAdaptor)Type.FirstCLRBaseType).BaseCLRType) as CLRType;\n                        return clrType.GetFieldValue(index, clrInstance);\n                    }\n                    else\n                        throw new TypeLoadException();\n                }\n            }\n            set\n            {\n                value = ILIntepreter.CheckAndCloneValueType(value, type.AppDomain);\n                if (index < fields.Length && index >= 0)\n                {\n                    fixed (StackObject* ptr = fields)\n                    {\n                        StackObject* esp = &ptr[index];\n                        if (value != null)\n                        {\n                            if (value.GetType().IsPrimitive)\n                            {\n                                ILIntepreter.UnboxObject(esp, value);\n                            }\n                            else\n                            {\n                                esp->ObjectType = ObjectTypes.Object;\n                                esp->Value = index;\n                                managedObjs[index] = value;\n                            }\n                        }\n                        else\n                            *esp = StackObject.Null;\n                    }\n                }\n                else\n                {\n                    if (Type.FirstCLRBaseType != null && Type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n                    {\n                        CLRType clrType = type.AppDomain.GetType(((Enviorment.CrossBindingAdaptor)Type.FirstCLRBaseType).BaseCLRType) as CLRType;\n                        clrType.SetFieldValue(index, ref clrInstance, value);\n                    }\n                    else\n                        throw new TypeLoadException();\n                }\n            }\n        }\n\n        void InitializeFields(ILType type)\n        {\n            for (int i = 0; i < type.FieldTypes.Length; i++)\n            {\n                var ft = type.FieldTypes[i];\n                StackObject.Initialized(ref fields[type.FieldStartIndex + i], type.FieldStartIndex + i, ft.TypeForCLR, ft, managedObjs);\n            }\n            if (type.BaseType != null && type.BaseType is ILType)\n                InitializeFields((ILType)type.BaseType);\n        }\n\n        internal unsafe void PushFieldAddress(int fieldIdx, StackObject* esp, IList<object> managedStack)\n        {\n            esp->ObjectType = ObjectTypes.FieldReference;\n            esp->Value = managedStack.Count;\n            managedStack.Add(this);\n            esp->ValueLow = fieldIdx;\n        }\n\n        internal unsafe void PushToStack(int fieldIdx, StackObject* esp, Enviorment.AppDomain appdomain, IList<object> managedStack)\n        {\n            if (fieldIdx < fields.Length && fieldIdx >= 0)\n                PushToStackSub(ref fields[fieldIdx], fieldIdx, esp, managedStack);\n            else\n            {\n                if (Type.FirstCLRBaseType != null && Type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n                {\n                    CLRType clrType = appdomain.GetType(((Enviorment.CrossBindingAdaptor)Type.FirstCLRBaseType).BaseCLRType) as CLRType;\n                    ILIntepreter.PushObject(esp, managedStack, clrType.GetFieldValue(fieldIdx, clrInstance));\n                }\n                else\n                    throw new TypeLoadException();\n            }\n        }\n\n        unsafe void PushToStackSub(ref StackObject field, int fieldIdx, StackObject* esp, IList<object> managedStack)\n        {\n            *esp = field;\n            if (field.ObjectType >= ObjectTypes.Object)\n            {\n                esp->Value = managedStack.Count;\n                managedStack.Add(managedObjs[fieldIdx]);\n            }\n        }\n\n        internal unsafe void CopyValueTypeToStack(StackObject* ptr, IList<object> mStack)\n        {\n            ptr->ObjectType = ObjectTypes.ValueTypeDescriptor;\n            ptr->Value = type.GetHashCode();\n            ptr->ValueLow = type.TotalFieldCount;\n            for(int i = 0; i < fields.Length; i++)\n            {\n                var val = ILIntepreter.Minus(ptr, i + 1);\n                switch (val->ObjectType)\n                {\n                    case ObjectTypes.Object:\n                    case ObjectTypes.FieldReference:\n                    case ObjectTypes.ArrayReference:\n                        mStack[val->Value] = managedObjs[i];\n                        val->ValueLow = fields[i].ValueLow;\n                        break;\n                    case ObjectTypes.ValueTypeObjectReference:\n                        {\n                            var obj = managedObjs[i];\n                            var dst = *(StackObject**)&val->Value;\n                            var vt = type.AppDomain.GetType(dst->Value);\n                            if (vt is ILType)\n                            {\n                                ((ILTypeInstance)obj).CopyValueTypeToStack(dst, mStack);\n                            }\n                            else\n                            {\n                                ((CLRType)vt).ValueTypeBinder.CopyValueTypeToStack(obj, dst, mStack);\n                            }\n                        }\n                        break;\n                    default:\n                        *val = fields[i];\n                        break;\n                }                \n            }\n        }\n\n        internal void Clear()\n        {   \n            InitializeFields(type);\n        }\n\n        internal unsafe void AssignFromStack(int fieldIdx, StackObject* esp, Enviorment.AppDomain appdomain, IList<object> managedStack)\n        {\n            if (fieldIdx < fields.Length && fieldIdx >= 0)\n                AssignFromStackSub(ref fields[fieldIdx], fieldIdx, esp, managedStack);\n            else\n            {\n                if (Type.FirstCLRBaseType != null && Type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n                {\n                    CLRType clrType = appdomain.GetType(((Enviorment.CrossBindingAdaptor)Type.FirstCLRBaseType).BaseCLRType) as CLRType;\n                    var field = clrType.GetField(fieldIdx);\n                    clrType.SetFieldValue(fieldIdx, ref clrInstance, field.FieldType.CheckCLRTypes(ILIntepreter.CheckAndCloneValueType(StackObject.ToObject(esp, appdomain, managedStack), appdomain)));\n                }\n                else\n                    throw new TypeLoadException();\n            }\n        }\n\n        internal unsafe void AssignFromStack(StackObject* esp, Enviorment.AppDomain appdomain, IList<object> managedStack)\n        {\n            StackObject* val = *(StackObject**)&esp->Value;\n            int cnt = val->ValueLow;\n            for (int i = 0; i < cnt; i++)\n            {\n                var addr = ILIntepreter.Minus(val, i + 1);\n                AssignFromStack(i, addr, type.AppDomain, managedStack);\n            }\n        }\n\n        unsafe void AssignFromStackSub(ref StackObject field, int fieldIdx, StackObject* esp, IList<object> managedStack)\n        {\n            esp = ILIntepreter.GetObjectAndResolveReference(esp);\n            field = *esp;\n            switch (field.ObjectType)\n            {\n                case ObjectTypes.Object:\n                case ObjectTypes.ArrayReference:\n                case ObjectTypes.FieldReference:\n                    field.Value = fieldIdx;\n                    managedObjs[fieldIdx] = ILIntepreter.CheckAndCloneValueType(managedStack[esp->Value], Type.AppDomain);\n                    break;\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        var domain = type.AppDomain;\n                        field.ObjectType = ObjectTypes.Object;\n                        field.Value = fieldIdx;\n                        var dst = *(StackObject**)&esp->Value;\n                        var vt = domain.GetType(dst->Value);\n                        if(vt is ILType)\n                        {\n                            var ins = managedObjs[fieldIdx];\n                            if (ins == null)\n                                throw new NullReferenceException();\n                            ILTypeInstance child = (ILTypeInstance)ins;\n                            child.AssignFromStack(esp, domain, managedStack);\n                        }\n                        else\n                        {\n                            managedObjs[fieldIdx] = ((CLRType)vt).ValueTypeBinder.ToObject(dst, managedStack);\n                        }\n                        \n                    }\n                    break;\n                default:\n                    if (managedObjs != null)\n                        managedObjs[fieldIdx] = null;\n                    break;\n            }\n        }\n\n        public override string ToString()\n        {\n            IMethod m = type.AppDomain.ObjectType.GetMethod(\"ToString\", 0);\n            m = type.GetVirtualMethod(m);\n            if (m != null)\n            {\n                if (m is ILMethod)\n                {\n                    var res = type.AppDomain.Invoke(m, this, null);\n                    return res.ToString();\n                }\n                else\n                    return clrInstance.ToString();\n            }\n            else\n                return type.FullName;\n        }\n\n        public bool CanAssignTo(IType type)\n        {\n            return this.type.CanAssignTo(type);\n        }\n\n        public ILTypeInstance Clone()\n        {\n            ILTypeInstance ins = new ILTypeInstance(type);\n            for (int i = 0; i < fields.Length; i++)\n            {\n                ins.fields[i] = fields[i];\n                ins.managedObjs[i] = managedObjs[i];\n            }\n            if (type.FirstCLRBaseType is Enviorment.CrossBindingAdaptor)\n            {\n                ins.clrInstance = ((Enviorment.CrossBindingAdaptor)type.FirstCLRBaseType).CreateCLRInstance(type.AppDomain, ins);\n            }\n            else\n            {\n                ins.clrInstance = ins;\n            }\n            return ins;\n        }\n\n        internal IDelegateAdapter GetDelegateAdapter(ILMethod method)\n        {\n            if (delegates == null)\n                delegates = new Dictionary<ILMethod, IDelegateAdapter>();\n\n            IDelegateAdapter res;\n            if (delegates.TryGetValue(method, out res))\n                return res;\n            return null;\n        }\n\n        internal void SetDelegateAdapter(ILMethod method, IDelegateAdapter adapter)\n        {\n            if (!delegates.ContainsKey(method))\n                delegates[method] = adapter;\n            else\n                throw new NotSupportedException();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Intepreter/OpCodes/OpCode.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.Method;\n\nnamespace ILRuntime.Runtime.Intepreter.OpCodes\n{\n  \n    /// <summary>\n    /// IL指令\n    /// </summary>\n    struct OpCode\n    {\n        /// <summary>\n        /// 当前指令\n        /// </summary>\n        public OpCodeEnum Code;\n\n        /// <summary>\n        ///  Int32 操作数\n        /// </summary>\n        public int TokenInteger;\n\n        /// <summary>\n        /// Int64 操作数\n        /// </summary>\n        public long TokenLong;\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Intepreter/OpCodes/OpCodeEnum.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ILRuntime.Runtime.Intepreter.OpCodes\n{\n    enum OpCodeEnum\n    {\n        /// <summary>\n        /// 如果修补操作码，则填充空间。尽管可能消耗处理周期，但未执行任何有意义的操作。\n        /// </summary>\n        Nop,\n        /// <summary>\n        /// 向公共语言结构 (CLI) 发出信号以通知调试器已撞上了一个断点。\n        /// </summary>\n        Break,\n        /// <summary>\n        /// 将索引为 0 的参数加载到计算堆栈上。\n        /// </summary>\n        Ldarg_0,\n        /// <summary>\n        /// 将索引为 1 的参数加载到计算堆栈上。\n        /// </summary>\n        Ldarg_1,\n        /// <summary>\n        /// 将索引为 2 的参数加载到计算堆栈上。\n        /// </summary>\n        Ldarg_2,\n        /// <summary>\n        /// 将索引为 3 的参数加载到计算堆栈上。\n        /// </summary>\n        Ldarg_3,\n        /// <summary>\n        /// 将索引 0 处的局部变量加载到计算堆栈上。\n        /// </summary>\n        Ldloc_0,\n        /// <summary>\n        /// 将索引 1 处的局部变量加载到计算堆栈上。\n        /// </summary>\n        Ldloc_1,\n        /// <summary>\n        /// 将索引 2 处的局部变量加载到计算堆栈上。\n        /// </summary>\n        Ldloc_2,\n        /// <summary>\n        /// 将索引 3 处的局部变量加载到计算堆栈上。\n        /// </summary>\n        Ldloc_3,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储到索引 0 处的局部变量列表中。\n        /// </summary>\n        Stloc_0,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储到索引 1 处的局部变量列表中。\n        /// </summary>\n        Stloc_1,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储到索引 2 处的局部变量列表中。\n        /// </summary>\n        Stloc_2,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储到索引 3 处的局部变量列表中。\n        /// </summary>\n        Stloc_3,\n        /// <summary>\n        /// 将参数（由指定的短格式索引引用）加载到计算堆栈上。\n        /// </summary>\n        Ldarg_S,\n        /// <summary>\n        /// 以短格式将参数地址加载到计算堆栈上。\n        /// </summary>\n        Ldarga_S,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值存储在参数槽中的指定索引处（短格式）。\n        /// </summary>\n        Starg_S,\n        /// <summary>\n        /// 将特定索引处的局部变量加载到计算堆栈上（短格式）。\n        /// </summary>\n        Ldloc_S,\n        /// <summary>\n        /// 将位于特定索引处的局部变量的地址加载到计算堆栈上（短格式）。\n        /// </summary>\n        Ldloca_S,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储在局部变量列表中的 index 处（短格式）。\n        /// </summary>\n        Stloc_S,\n        /// <summary>\n        /// 将空引用（O 类型）推送到计算堆栈上。\n        /// </summary>\n        Ldnull,\n        /// <summary>\n        /// 将整数值 -1 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_M1,\n        /// <summary>\n        /// 将整数值 0 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_0,\n        /// <summary>\n        /// 将整数值 1 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_1,\n        /// <summary>\n        /// 将整数值 2 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_2,\n        /// <summary>\n        /// 将整数值 3 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_3,\n        /// <summary>\n        /// 将整数值 4 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_4,\n        /// <summary>\n        /// 将整数值 5 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_5,\n        /// <summary>\n        /// 将整数值 6 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_6,\n        /// <summary>\n        /// 将整数值 7 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_7,\n        /// <summary>\n        /// 将整数值 8 作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4_8,\n        /// <summary>\n        /// 将提供的 int8 值作为 int32 推送到计算堆栈上（短格式）。\n        /// </summary>\n        Ldc_I4_S,\n        /// <summary>\n        /// 将所提供的 int32 类型的值作为 int32 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I4,\n        /// <summary>\n        /// 将所提供的 int64 类型的值作为 int64 推送到计算堆栈上。\n        /// </summary>\n        Ldc_I8,\n        /// <summary>\n        /// 将所提供的 float32 类型的值作为 F (float) 类型推送到计算堆栈上。\n        /// </summary>\n        Ldc_R4,\n        /// <summary>\n        /// 将所提供的 float64 类型的值作为 F (float) 类型推送到计算堆栈上。\n        /// </summary>\n        Ldc_R8,\n        /// <summary>\n        /// 复制计算堆栈上当前最顶端的值，然后将副本推送到计算堆栈上。\n        /// </summary>\n        Dup,\n        /// <summary>\n        /// 移除当前位于计算堆栈顶部的值。\n        /// </summary>\n        Pop,\n        /// <summary>\n        /// 退出当前方法并跳至指定方法。\n        /// </summary>\n        Jmp,\n        /// <summary>\n        /// 调用由传递的方法说明符指示的方法。\n        /// </summary>\n        Call,\n        /// <summary>\n        /// 通过调用约定描述的参数调用在计算堆栈上指示的方法（作为指向入口点的指针）。\n        /// </summary>\n        Calli,\n        /// <summary>\n        /// 从当前方法返回，并将返回值（如果存在）从调用方的计算堆栈推送到被调用方的计算堆栈上。\n        /// </summary>\n        Ret,\n        /// <summary>\n        /// 无条件地将控制转移到目标指令（短格式）。\n        /// </summary>\n        Br_S,\n        /// <summary>\n        /// 如果 value 为 false、空引用或零，则将控制转移到目标指令。\n        /// </summary>\n        Brfalse_S,\n        /// <summary>\n        /// 如果 value 为 true、非空或非零，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Brtrue_S,\n        /// <summary>\n        /// 如果两个值相等，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Beq_S,\n        /// <summary>\n        /// 如果第一个值大于或等于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Bge_S,\n        /// <summary>\n        /// 如果第一个值大于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Bgt_S,\n        /// <summary>\n        /// 如果第一个值小于或等于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Ble_S,\n        /// <summary>\n        /// 如果第一个值小于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Blt_S,\n        /// <summary>\n        /// 当两个无符号整数值或不可排序的浮点型值不相等时，将控制转移到目标指令（短格式）。\n        /// </summary>\n        Bne_Un_S,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值大于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Bge_Un_S,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值大于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Bgt_Un_S,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点值时，如果第一个值小于或等于第二个值，则将控制权转移到目标指令（短格式）。\n        /// </summary>\n        Ble_Un_S,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值小于第二个值，则将控制转移到目标指令（短格式）。\n        /// </summary>\n        Blt_Un_S,\n        /// <summary>\n        /// 无条件地将控制转移到目标指令。\n        /// </summary>\n        Br,\n        /// <summary>\n        /// 如果 value 为 false、空引用（Visual Basic 中的 Nothing）或零，则将控制转移到目标指令。\n        /// </summary>\n        Brfalse,\n        /// <summary>\n        /// 如果 value 为 true、非空或非零，则将控制转移到目标指令。\n        /// </summary>\n        Brtrue,\n        /// <summary>\n        /// 如果两个值相等，则将控制转移到目标指令。\n        /// </summary>\n        Beq,\n        /// <summary>\n        /// 如果第一个值大于或等于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Bge,\n        /// <summary>\n        /// 如果第一个值大于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Bgt,\n        /// <summary>\n        /// 如果第一个值小于或等于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Ble,\n        /// <summary>\n        /// 如果第一个值小于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Blt,\n        /// <summary>\n        /// 当两个无符号整数值或不可排序的浮点型值不相等时，将控制转移到目标指令。\n        /// </summary>\n        Bne_Un,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值大于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Bge_Un,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值大于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Bgt_Un,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值小于或等于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Ble_Un,\n        /// <summary>\n        /// 当比较无符号整数值或不可排序的浮点型值时，如果第一个值小于第二个值，则将控制转移到目标指令。\n        /// </summary>\n        Blt_Un,\n        /// <summary>\n        /// 实现跳转表。\n        /// </summary>\n        Switch,\n        /// <summary>\n        /// 将 int8 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_I1,\n        /// <summary>\n        /// 将 unsigned int8 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_U1,\n        /// <summary>\n        /// 将 int16 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_I2,\n        /// <summary>\n        /// 将 unsigned int16 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_U2,\n        /// <summary>\n        /// 将 int32 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_I4,\n        /// <summary>\n        /// 将 unsigned int32 类型的值作为 int32 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_U4,\n        /// <summary>\n        /// 将 int64 类型的值作为 int64 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_I8,\n        /// <summary>\n        /// 将 native int 类型的值作为 native int 间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_I,\n        /// <summary>\n        /// 将 float32 类型的值作为 F (float) 类型间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_R4,\n        /// <summary>\n        /// 将 float64 类型的值作为 F (float) 类型间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_R8,\n        /// <summary>\n        /// 将对象引用作为 O（对象引用）类型间接加载到计算堆栈上。\n        /// </summary>\n        Ldind_Ref,\n        /// <summary>\n        /// 存储所提供地址处的对象引用值。\n        /// </summary>\n        Stind_Ref,\n        /// <summary>\n        /// 在所提供的地址存储 int8 类型的值。\n        /// </summary>\n        Stind_I1,\n        /// <summary>\n        /// 在所提供的地址存储 int16 类型的值。\n        /// </summary>\n        Stind_I2,\n        /// <summary>\n        /// 在所提供的地址存储 int32 类型的值。\n        /// </summary>\n        Stind_I4,\n        /// <summary>\n        /// 在所提供的地址存储 int64 类型的值。\n        /// </summary>\n        Stind_I8,\n        /// <summary>\n        /// 在所提供的地址存储 float32 类型的值。\n        /// </summary>\n        Stind_R4,\n        /// <summary>\n        /// 在所提供的地址存储 float64 类型的值。\n        /// </summary>\n        Stind_R8,\n        /// <summary>\n        /// 将两个值相加并将结果推送到计算堆栈上。\n        /// </summary>\n        Add,\n        /// <summary>\n        /// 从其他值中减去一个值并将结果推送到计算堆栈上。\n        /// </summary>\n        Sub,\n        /// <summary>\n        /// 将两个值相乘并将结果推送到计算堆栈上。\n        /// </summary>\n        Mul,\n        /// <summary>\n        /// 将两个值相除并将结果作为浮点（F 类型）或商（int32 类型）推送到计算堆栈上。\n        /// </summary>\n        Div,\n        /// <summary>\n        /// 两个无符号整数值相除并将结果 ( int32 ) 推送到计算堆栈上。\n        /// </summary>\n        Div_Un,\n        /// <summary>\n        /// 将两个值相除并将余数推送到计算堆栈上。\n        /// </summary>\n        Rem,\n        /// <summary>\n        /// 将两个无符号值相除并将余数推送到计算堆栈上。\n        /// </summary>\n        Rem_Un,\n        /// <summary>\n        /// 计算两个值的按位“与”并将结果推送到计算堆栈上。\n        /// </summary>\n        And,\n        /// <summary>\n        /// 计算位于堆栈顶部的两个整数值的按位求补并将结果推送到计算堆栈上。\n        /// </summary>\n        Or,\n        /// <summary>\n        /// 计算位于计算堆栈顶部的两个值的按位异或，并且将结果推送到计算堆栈上。\n        /// </summary>\n        Xor,\n        /// <summary>\n        /// 将整数值左移（用零填充）指定的位数，并将结果推送到计算堆栈上。\n        /// </summary>\n        Shl,\n        /// <summary>\n        /// 将整数值右移（保留符号）指定的位数，并将结果推送到计算堆栈上。\n        /// </summary>\n        Shr,\n        /// <summary>\n        /// 将无符号整数值右移（用零填充）指定的位数，并将结果推送到计算堆栈上。\n        /// </summary>\n        Shr_Un,\n        /// <summary>\n        /// 对一个值执行求反并将结果推送到计算堆栈上。\n        /// </summary>\n        Neg,\n        /// <summary>\n        /// 计算堆栈顶部整数值的按位求补并将结果作为相同的类型推送到计算堆栈上。\n        /// </summary>\n        Not,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 int8，然后将其扩展（填充）为 int32。\n        /// </summary>\n        Conv_I1,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 int16，然后将其扩展（填充）为 int32。\n        /// </summary>\n        Conv_I2,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 int32。\n        /// </summary>\n        Conv_I4,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 int64。\n        /// </summary>\n        Conv_I8,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 float32。\n        /// </summary>\n        Conv_R4,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 float64。\n        /// </summary>\n        Conv_R8,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 unsigned int32，然后将其扩展为 int32。\n        /// </summary>\n        Conv_U4,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 unsigned int64，然后将其扩展为 int64。\n        /// </summary>\n        Conv_U8,\n        /// <summary>\n        /// 对对象调用后期绑定方法，并且将返回值推送到计算堆栈上。\n        /// </summary>\n        Callvirt,\n        /// <summary>\n        /// 将位于对象（&、* 或 native int 类型）地址的值类型复制到目标对象（&、* 或 native int 类型）的地址。\n        /// </summary>\n        Cpobj,\n        /// <summary>\n        /// 将地址指向的值类型对象复制到计算堆栈的顶部。\n        /// </summary>\n        Ldobj,\n        /// <summary>\n        /// 推送对元数据中存储的字符串的新对象引用。\n        /// </summary>\n        Ldstr,\n        /// <summary>\n        /// 创建一个值类型的新对象或新实例，并将对象引用（O 类型）推送到计算堆栈上。\n        /// </summary>\n        Newobj,\n        /// <summary>\n        /// 尝试将引用传递的对象转换为指定的类。\n        /// </summary>\n        Castclass,\n        /// <summary>\n        /// 测试对象引用（O 类型）是否为特定类的实例。\n        /// </summary>\n        Isinst,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号整数值转换为 float32。\n        /// </summary>\n        Conv_R_Un,\n        /// <summary>\n        /// 将值类型的已装箱的表示形式转换为其未装箱的形式。\n        /// </summary>\n        Unbox,\n        /// <summary>\n        /// 引发当前位于计算堆栈上的异常对象。\n        /// </summary>\n        Throw,\n        /// <summary>\n        /// 查找对象中其引用当前位于计算堆栈的字段的值。\n        /// </summary>\n        Ldfld,\n        /// <summary>\n        /// 查找对象中其引用当前位于计算堆栈的字段的地址。\n        /// </summary>\n        Ldflda,\n        /// <summary>\n        /// 用新值替换在对象引用或指针的字段中存储的值。\n        /// </summary>\n        Stfld,\n        /// <summary>\n        /// 将静态字段的值推送到计算堆栈上。\n        /// </summary>\n        Ldsfld,\n        /// <summary>\n        /// 将静态字段的地址推送到计算堆栈上。\n        /// </summary>\n        Ldsflda,\n        /// <summary>\n        /// 用来自计算堆栈的值替换静态字段的值。\n        /// </summary>\n        Stsfld,\n        /// <summary>\n        /// 将指定类型的值从计算堆栈复制到所提供的内存地址中。\n        /// </summary>\n        Stobj,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为有符号 int8 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I1_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为有符号 int16 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I2_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为有符号 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I4_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为有符号 int64，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I8_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为 unsigned int8 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U1_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为 unsigned int16 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U2_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为 unsigned int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U4_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为 unsigned int64，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U8_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为有符号 native int，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I_Un,\n        /// <summary>\n        /// 将位于计算堆栈顶部的无符号值转换为 unsigned native int，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U_Un,\n        /// <summary>\n        /// 将值类转换为对象引用（O 类型）。\n        /// </summary>\n        Box,\n        /// <summary>\n        /// 将对新的从零开始的一维数组（其元素属于特定类型）的对象引用推送到计算堆栈上。\n        /// </summary>\n        Newarr,\n        /// <summary>\n        /// 将从零开始的、一维数组的元素的数目推送到计算堆栈上。\n        /// </summary>\n        Ldlen,\n        /// <summary>\n        /// 将位于指定数组索引的数组元素的地址作为 & 类型（托管指针）加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelema,\n        /// <summary>\n        /// 将位于指定数组索引处的 int8 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_I1,\n        /// <summary>\n        /// 将位于指定数组索引处的 unsigned int8 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_U1,\n        /// <summary>\n        /// 将位于指定数组索引处的 int16 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_I2,\n        /// <summary>\n        /// 将位于指定数组索引处的 unsigned int16 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_U2,\n        /// <summary>\n        /// 将位于指定数组索引处的 int32 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_I4,\n        /// <summary>\n        /// 将位于指定数组索引处的 unsigned int32 类型的元素作为 int32 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_U4,\n        /// <summary>\n        /// 将位于指定数组索引处的 int64 类型的元素作为 int64 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_I8,\n        /// <summary>\n        /// 将位于指定数组索引处的 native int 类型的元素作为 native int 加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_I,\n        /// <summary>\n        /// 将位于指定数组索引处的 float32 类型的元素作为 F 类型（浮点型）加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_R4,\n        /// <summary>\n        /// 将位于指定数组索引处的 float64 类型的元素作为 F 类型（浮点型）加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_R8,\n        /// <summary>\n        /// 将位于指定数组索引处的包含对象引用的元素作为 O 类型（对象引用）加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_Ref,\n        /// <summary>\n        /// 用计算堆栈上的 native int 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_I,\n        /// <summary>\n        /// 用计算堆栈上的 int8 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_I1,\n        /// <summary>\n        /// 用计算堆栈上的 int16 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_I2,\n        /// <summary>\n        /// 用计算堆栈上的 int32 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_I4,\n        /// <summary>\n        /// 用计算堆栈上的 int64 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_I8,\n        /// <summary>\n        /// 用计算堆栈上的 float32 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_R4,\n        /// <summary>\n        /// 用计算堆栈上的 float64 值替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_R8,\n        /// <summary>\n        /// 用计算堆栈上的对象 ref 值（O 类型）替换给定索引处的数组元素。\n        /// </summary>\n        Stelem_Ref,\n        /// <summary>\n        /// 按照指令中指定的类型，将指定数组索引中的元素加载到计算堆栈的顶部。\n        /// </summary>\n        Ldelem_Any,\n        /// <summary>\n        /// 用计算堆栈中的值替换给定索引处的数组元素，其类型在指令中指定。\n        /// </summary>\n        Stelem_Any,\n        /// <summary>\n        /// 将指令中指定类型的已装箱的表示形式转换成未装箱形式。\n        /// </summary>\n        Unbox_Any,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为有符号 int8 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I1,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为 unsigned int8 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U1,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为有符号 int16 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I2,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为 unsigned int16 并将其扩展为 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U2,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为有符号 int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I4,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为 unsigned int32，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U4,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为有符号 int64，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I8,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为 unsigned int64，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U8,\n        /// <summary>\n        /// 检索嵌入在类型化引用内的地址（& 类型）。\n        /// </summary>\n        Refanyval,\n        /// <summary>\n        /// 如果值不是有限数，则引发 ArithmeticException。\n        /// </summary>\n        Ckfinite,\n        /// <summary>\n        /// 将对特定类型实例的类型化引用推送到计算堆栈上。\n        /// </summary>\n        Mkrefany,\n        /// <summary>\n        /// 将元数据标记转换为其运行时表示形式，并将其推送到计算堆栈上。\n        /// </summary>\n        Ldtoken,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 unsigned int16，然后将其扩展为 int32。\n        /// </summary>\n        Conv_U2,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 unsigned int8，然后将其扩展为 int32。\n        /// </summary>\n        Conv_U1,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 native int。\n        /// </summary>\n        Conv_I,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为有符号 native int，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_I,\n        /// <summary>\n        /// 将位于计算堆栈顶部的有符号值转换为 unsigned native int，并在溢出时引发 OverflowException。\n        /// </summary>\n        Conv_Ovf_U,\n        /// <summary>\n        /// 将两个整数相加，执行溢出检查，并且将结果推送到计算堆栈上。\n        /// </summary>\n        Add_Ovf,\n        /// <summary>\n        /// 将两个无符号整数值相加，执行溢出检查，并且将结果推送到计算堆栈上。\n        /// </summary>\n        Add_Ovf_Un,\n        /// <summary>\n        /// 将两个整数值相乘，执行溢出检查，并将结果推送到计算堆栈上。\n        /// </summary>\n        Mul_Ovf,\n        /// <summary>\n        /// 将两个无符号整数值相乘，执行溢出检查，并将结果推送到计算堆栈上。\n        /// </summary>\n        Mul_Ovf_Un,\n        /// <summary>\n        /// 从另一值中减去一个整数值，执行溢出检查，并且将结果推送到计算堆栈上。\n        /// </summary>\n        Sub_Ovf,\n        /// <summary>\n        /// 从另一值中减去一个无符号整数值，执行溢出检查，并且将结果推送到计算堆栈上。\n        /// </summary>\n        Sub_Ovf_Un,\n        /// <summary>\n        /// 将控制从异常块的 fault 或 finally 子句转移回公共语言结构 (CLI) 异常处理程序。\n        /// </summary>\n        Endfinally,\n        /// <summary>\n        /// 退出受保护的代码区域，无条件将控制转移到特定目标指令。\n        /// </summary>\n        Leave,\n        /// <summary>\n        /// 退出受保护的代码区域，无条件将控制转移到目标指令（缩写形式）。\n        /// </summary>\n        Leave_S,\n        /// <summary>\n        /// 在所提供的地址存储 native int 类型的值。\n        /// </summary>\n        Stind_I,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值转换为 unsigned native int，然后将其扩展为 native int。\n        /// </summary>\n        Conv_U,\n        /// <summary>\n        /// 返回指向当前方法的参数列表的非托管指针。\n        /// </summary>\n        Arglist,\n        /// <summary>\n        /// 比较两个值。如果这两个值相等，则将整数值 1 (int32) 推送到计算堆栈上；否则，将 0 (int32) 推送到计算堆栈上。\n        /// </summary>\n        Ceq,\n        /// <summary>\n        /// 比较两个值。如果第一个值大于第二个值，则将整数值 1 (int32) 推送到计算堆栈上；反之，将 0 (int32) 推送到计算堆栈上。\n        /// </summary>\n        Cgt,\n        /// <summary>\n        /// 比较两个无符号的或不可排序的值。如果第一个值大于第二个值，则将整数值 1 (int32) 推送到计算堆栈上；反之，将 0 (int32) 推送到计算堆栈上。\n        /// </summary>\n        Cgt_Un,\n        /// <summary>\n        /// 比较两个值。如果第一个值小于第二个值，则将整数值 1 (int32) 推送到计算堆栈上；反之，将 0 (int32) 推送到计算堆栈上。\n        /// </summary>\n        Clt,\n        /// <summary>\n        /// 比较无符号的或不可排序的值 value1 和 value2。如果 value1 小于 value2，则将整数值 1 (int32 ) 推送到计算堆栈上；反之，将 0 ( int32 ) 推送到计算堆栈上。\n        /// </summary>\n        Clt_Un,\n        /// <summary>\n        /// 将指向实现特定方法的本机代码的非托管指针（native int 类型）推送到计算堆栈上。\n        /// </summary>\n        Ldftn,\n        /// <summary>\n        /// 将指向实现与指定对象关联的特定虚方法的本机代码的非托管指针（native int 类型）推送到计算堆栈上。\n        /// </summary>\n        Ldvirtftn,\n        /// <summary>\n        /// 将参数（由指定索引值引用）加载到堆栈上。\n        /// </summary>\n        Ldarg,\n        /// <summary>\n        /// 将参数地址加载到计算堆栈上。\n        /// </summary>\n        Ldarga,\n        /// <summary>\n        /// 将位于计算堆栈顶部的值存储到位于指定索引的参数槽中。\n        /// </summary>\n        Starg,\n        /// <summary>\n        /// 将指定索引处的局部变量加载到计算堆栈上。\n        /// </summary>\n        Ldloc,\n        /// <summary>\n        /// 将位于特定索引处的局部变量的地址加载到计算堆栈上。\n        /// </summary>\n        Ldloca,\n        /// <summary>\n        /// 从计算堆栈的顶部弹出当前值并将其存储到指定索引处的局部变量列表中。\n        /// </summary>\n        Stloc,\n        /// <summary>\n        /// 从本地动态内存池分配特定数目的字节并将第一个分配的字节的地址（瞬态指针，* 类型）推送到计算堆栈上。\n        /// </summary>\n        Localloc,\n        /// <summary>\n        /// 将控制从异常的 filter 子句转移回公共语言结构 (CLI) 异常处理程序。\n        /// </summary>\n        Endfilter,\n        /// <summary>\n        /// 指示当前位于计算堆栈上的地址可能没有与紧接的 ldind、stind、ldfld、stfld、ldobj、stobj、initblk 或 cpblk 指令的自然大小对齐。\n        /// </summary>\n        Unaligned,\n        /// <summary>\n        /// 指定当前位于计算堆栈顶部的地址可以是易失的，并且读取该位置的结果不能被缓存，或者对该地址的多个存储区不能被取消。\n        /// </summary>\n        Volatile,\n        /// <summary>\n        /// 执行后缀的方法调用指令，以便在执行实际调用指令前移除当前方法的堆栈帧。\n        /// </summary>\n        Tail,\n        /// <summary>\n        /// 将位于指定地址的值类型的每个字段初始化为空引用或适当的基元类型的 0。\n        /// </summary>\n        Initobj,\n        /// <summary>\n        /// 约束要对其进行虚方法调用的类型。\n        /// </summary>\n        Constrained,\n        /// <summary>\n        /// 将指定数目的字节从源地址复制到目标地址。\n        /// </summary>\n        Cpblk,\n        /// <summary>\n        /// 将位于特定地址的内存的指定块初始化为给定大小和初始值。\n        /// </summary>\n        Initblk,\n        No,\n        /// <summary>\n        /// 再次引发当前异常。\n        /// </summary>\n        Rethrow,\n        /// <summary>\n        /// 将提供的值类型的大小（以字节为单位）推送到计算堆栈上。\n        /// </summary>\n        Sizeof,\n        /// <summary>\n        /// 检索嵌入在类型化引用内的类型标记。\n        /// </summary>\n        Refanytype,\n        /// <summary>\n        /// 指定后面的数组地址操作在运行时不执行类型检查，并且返回可变性受限的托管指针。\n        /// </summary>\n        Readonly,\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Stack/RuntimeStack.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing ILRuntime.CLR.Method;\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Other;\nusing ILRuntime.Runtime.Intepreter;\n\nnamespace ILRuntime.Runtime.Stack\n{\n    unsafe public class RuntimeStack : IDisposable\n    {\n        ILIntepreter intepreter;\n        StackObject* pointer;\n        StackObject* endOfMemory;\n        StackObject* valueTypePtr;\n\n        IntPtr nativePointer;\n\n#if DEBUG\n        IList<object> managedStack = new List<object>(32);\n#else\n        IList<object> managedStack = new UncheckedList<object>(32);\n#endif\n\n        Stack<StackFrame> frames = new Stack<StackFrame>();\n        const int MAXIMAL_STACK_OBJECTS = 1024 * 16;\n\n        public Stack<StackFrame> Frames { get { return frames; } }\n        public RuntimeStack(ILIntepreter intepreter)\n        {\n            this.intepreter = intepreter;\n\n            nativePointer = System.Runtime.InteropServices.Marshal.AllocHGlobal(sizeof(StackObject) * MAXIMAL_STACK_OBJECTS);\n            pointer = (StackObject*)nativePointer.ToPointer();\n            endOfMemory = Add(pointer, MAXIMAL_STACK_OBJECTS);\n            valueTypePtr = endOfMemory - 1;\n        }\n\n        ~RuntimeStack()\n        {\n            Dispose();\n        }\n\n        public StackObject* StackBase\n        {\n            get\n            {\n                return pointer;\n            }\n        }\n\n        public StackObject* ValueTypeStackPointer\n        {\n            get\n            {\n                return valueTypePtr;\n            }\n        }\n\n        public StackObject* ValueTypeStackBase\n        {\n            get\n            {\n                return endOfMemory - 1;\n            }\n        }\n\n        public IList<object> ManagedStack { get { return managedStack; } }\n\n        public void ResetValueTypePointer()\n        {\n            valueTypePtr = endOfMemory - 1;\n        }\n\n        public void InitializeFrame(ILMethod method, StackObject* esp, out StackFrame res)\n        {\n            if (esp < pointer || esp >= endOfMemory)\n                throw new StackOverflowException();\n            if (frames.Count > 0 && frames.Peek().BasePointer > esp)\n                throw new StackOverflowException();\n            res = new StackFrame();\n            res.LocalVarPointer = esp;\n            res.Method = method;\n#if DEBUG\n            res.Address = new IntegerReference();\n            for (int i = 0; i < method.LocalVariableCount; i++)\n            {\n                var p = Add(esp, i);\n                p->ObjectType = ObjectTypes.Null;\n            }\n#endif\n            res.BasePointer = method.LocalVariableCount > 0 ? Add(esp, method.LocalVariableCount + 1) : esp;\n            res.ManagedStackBase = managedStack.Count;\n            res.ValueTypeBasePointer = valueTypePtr;\n            //frames.Push(res);\n        }\n        public void PushFrame(ref StackFrame frame)\n        {\n            frames.Push(frame);\n        }\n\n        public StackObject* PopFrame(ref StackFrame frame, StackObject* esp)\n        {\n            if (frames.Count > 0 && frames.Peek().BasePointer == frame.BasePointer)\n                frames.Pop();\n            else\n                throw new NotSupportedException();\n            StackObject* returnVal = esp - 1;\n            var method = frame.Method;\n            StackObject* ret = ILIntepreter.Minus(frame.LocalVarPointer, method.ParameterCount);\n            int mStackBase = frame.ManagedStackBase;\n            if (method.HasThis)\n                ret--;\n            if(method.ReturnType != intepreter.AppDomain.VoidType)\n            {\n                *ret = *returnVal;\n                if(ret->ObjectType == ObjectTypes.Object)\n                {\n                    ret->Value = mStackBase;\n                    managedStack[mStackBase] = managedStack[returnVal->Value];\n                    mStackBase++;\n                }\n                else if(ret->ObjectType == ObjectTypes.ValueTypeObjectReference)\n                {\n                    StackObject* oriAddr = frame.ValueTypeBasePointer;\n                    RelocateValueType(ret, ref frame.ValueTypeBasePointer, ref mStackBase);\n                    *(StackObject**)&ret->Value = oriAddr;\n                }\n                ret++;\n            }\n#if DEBUG\n            ((List<object>)managedStack).RemoveRange(mStackBase, managedStack.Count - mStackBase);\n#else\n            ((UncheckedList<object>)managedStack).RemoveRange(mStackBase, managedStack.Count - mStackBase);\n#endif\n            valueTypePtr = frame.ValueTypeBasePointer;\n            return ret;\n        }\n\n        void RelocateValueType(StackObject* src, ref StackObject* dst, ref int mStackBase)\n        {\n            StackObject* descriptor = *(StackObject**)&src->Value;\n            if (descriptor > dst)\n                throw new StackOverflowException();\n            *dst = *descriptor;\n            int cnt = descriptor->ValueLow;\n            StackObject* endAddr = ILIntepreter.Minus(dst, cnt + 1);\n            for(int i = 0; i < cnt; i++)\n            {\n                StackObject* addr = ILIntepreter.Minus(descriptor, i + 1);\n                StackObject* tarVal = ILIntepreter.Minus(dst, i + 1);\n                *tarVal = *addr;\n                switch (addr->ObjectType)\n                {\n                    case ObjectTypes.Object:\n                    case ObjectTypes.ArrayReference:\n                    case ObjectTypes.FieldReference:\n                        if (tarVal->Value >= mStackBase)\n                        {\n                            int oldIdx = addr->Value;\n                            tarVal->Value = mStackBase;\n                            managedStack[mStackBase] = managedStack[oldIdx];\n                            mStackBase++;\n                        }\n                        break;\n                    case ObjectTypes.ValueTypeObjectReference:\n                        var newAddr = endAddr;\n                        RelocateValueType(addr, ref endAddr, ref mStackBase);\n                        *(StackObject**)&tarVal->Value = newAddr;\n                        break;\n                }\n            }\n            dst = endAddr;\n        }\n\n        public void AllocValueType(StackObject* ptr, IType type)\n        {\n            if (type.IsValueType)\n            {\n                int fieldCount = 0;\n                if(type is ILType)\n                {\n                    fieldCount = ((ILType)type).TotalFieldCount;\n                }\n                else\n                {\n                    fieldCount = ((CLRType)type).TotalFieldCount;\n                }\n                ptr->ObjectType = ObjectTypes.ValueTypeObjectReference;\n                var dst = valueTypePtr;\n                *(StackObject**)&ptr->Value = dst;\n                dst->ObjectType = ObjectTypes.ValueTypeDescriptor;\n                dst->Value = type.GetHashCode();\n                dst->ValueLow = fieldCount;\n                valueTypePtr = ILIntepreter.Minus(valueTypePtr, fieldCount + 1);\n                if (valueTypePtr <= StackBase)\n                    throw new StackOverflowException();\n                InitializeValueTypeObject(type, dst);\n            }\n            else\n                throw new ArgumentException(type.FullName + \" is not a value type.\", \"type\");\n        }\n\n        void InitializeValueTypeObject(IType type, StackObject* ptr)\n        {\n            if (type is ILType)\n            {\n                ILType t = (ILType)type;\n                for (int i = 0; i < t.FieldTypes.Length; i++)\n                {\n                    var ft = t.FieldTypes[i];\n                    StackObject* val = ILIntepreter.Minus(ptr, t.FieldStartIndex + i + 1);\n                    if (ft.IsPrimitive)\n                        StackObject.Initialized(val, ft);\n                    else\n                    {\n                        if (ft.IsValueType)\n                        {\n                            AllocValueType(val, ft);\n                        }\n                        else\n                        {\n                            val->ObjectType = ObjectTypes.Object;\n                            val->Value = managedStack.Count;\n                            managedStack.Add(null);\n                        }\n                    }\n                }\n                if (type.BaseType != null && type.BaseType is ILType)\n                    InitializeValueTypeObject((ILType)type.BaseType, ptr);\n            }\n            else\n            {\n                CLRType t = (CLRType)type;\n                var cnt = t.TotalFieldCount;\n                for(int i = 0; i < cnt; i++)\n                {\n                    var it = t.OrderedFieldTypes[i] as CLRType;\n                    StackObject* val = ILIntepreter.Minus(ptr, i + 1);\n                    if (it.IsPrimitive)\n                        StackObject.Initialized(val, it);\n                    else\n                    {\n                        if (it.IsValueType)\n                        {\n                            if (it.ValueTypeBinder != null)\n                                AllocValueType(val, it);\n                            else\n                            {\n                                val->ObjectType = ObjectTypes.Object;\n                                val->Value = managedStack.Count;\n                                managedStack.Add(it.CreateDefaultInstance());\n                            }\n                        }\n                        else\n                        {\n                            val->ObjectType = ObjectTypes.Object;\n                            val->Value = managedStack.Count;\n                            managedStack.Add(null);\n                        }\n                    }\n                }\n            }\n        }\n\n        public void ClearValueTypeObject(IType type, StackObject* ptr)\n        {\n            if (type is ILType)\n            {\n                ILType t = (ILType)type;\n                for (int i = 0; i < t.FieldTypes.Length; i++)\n                {\n                    var ft = t.FieldTypes[i];\n                    StackObject* val = ILIntepreter.Minus(ptr, t.FieldStartIndex + i + 1);\n                    if (ft.IsPrimitive)\n                        StackObject.Initialized(val, ft);\n                    else\n                    {\n                        switch (val->ObjectType)\n                        {\n                            case ObjectTypes.ValueTypeObjectReference:\n                                ClearValueTypeObject(ft, *(StackObject**)&val->Value);\n                                break;\n                            default:\n                                if (ft.IsValueType)\n                                {\n                                    if(ft is ILType)\n                                    {\n                                        throw new NotImplementedException();\n                                    }\n                                    else\n                                    {\n                                        managedStack[val->Value] = ((CLRType)ft).CreateDefaultInstance();\n                                    }\n                                }\n                                else\n                                    managedStack[val->Value] = null;\n                                break;\n                        }\n                    }\n                }\n                if (type.BaseType != null && type.BaseType is ILType)\n                    ClearValueTypeObject((ILType)type.BaseType, ptr);\n            }\n            else\n            {\n                CLRType t = (CLRType)type;\n                var cnt = t.TotalFieldCount;\n                for (int i = 0; i < cnt; i++)\n                {\n                    var vt = t.OrderedFieldTypes[i] as CLRType;\n                    StackObject* val = ILIntepreter.Minus(ptr, i + 1);\n                    if (vt.IsPrimitive)\n                        StackObject.Initialized(val, vt);\n                    else\n                    {\n                        switch (val->ObjectType)\n                        {\n                            case ObjectTypes.ValueTypeObjectReference:\n                                {\n                                    var dst = *(StackObject**)&val->Value;\n                                    ClearValueTypeObject(vt, *(StackObject**)&val->Value);\n                                }\n                                break;\n                            default:\n                                if (vt.IsValueType)\n                                {\n                                    managedStack[val->Value] = vt.CreateDefaultInstance();\n                                }\n                                else\n                                    managedStack[val->Value] = null;\n                                break;\n                        }\n                    }\n                }\n            }\n        }\n\n        public void FreeValueTypeObject(StackObject* esp)\n        {\n            int start = int.MaxValue;\n            int end = int.MinValue;\n            StackObject* endAddr;\n            CountValueTypeManaged(esp, ref start, ref end, &endAddr);\n\n            if (endAddr == valueTypePtr)\n                valueTypePtr = *(StackObject**)&esp->Value;\n            else\n                throw new NotSupportedException();\n            if (start != int.MaxValue)\n            {\n                if (end == managedStack.Count - 1)\n                {\n#if DEBUG\n                    ((List<object>)managedStack).RemoveRange(start, managedStack.Count - start);\n#else\n                    ((UncheckedList<object>)managedStack).RemoveRange(start, managedStack.Count - start);\n#endif\n                }\n                else\n                    throw new NotSupportedException();\n            }\n        }\n\n        void CountValueTypeManaged(StackObject* esp, ref int start, ref int end, StackObject** endAddr)\n        {\n            StackObject* descriptor = *(StackObject**)&esp->Value;\n            int cnt = descriptor->ValueLow;\n            *endAddr = ILIntepreter.Minus(descriptor, cnt + 1);\n            for (int i = 0; i < cnt; i++)\n            {\n                StackObject* addr = ILIntepreter.Minus(descriptor, i + 1);\n                switch (addr->ObjectType)\n                {\n                    case ObjectTypes.Object:\n                    case ObjectTypes.ArrayReference:\n                    case ObjectTypes.FieldReference:\n                        {\n                            if (start == int.MaxValue)\n                            {\n                                start = addr->Value;\n                                end = start;\n                            }\n                            else if (addr->Value == end + 1)\n                                end++;\n                            else\n                                throw new NotSupportedException();\n                        }\n                        break;\n                    case ObjectTypes.ValueTypeObjectReference:\n                        CountValueTypeManaged(addr, ref start, ref end, endAddr);\n                        break;\n                }\n\n            }\n        }\n\n        public void Dispose()\n        {\n            if (nativePointer != IntPtr.Zero)\n            {\n                System.Runtime.InteropServices.Marshal.FreeHGlobal(nativePointer);\n                nativePointer = IntPtr.Zero;\n            }\n        }\n\n        StackObject* Add(StackObject* a, int b)\n        {\n            return (StackObject*)((long)a + sizeof(StackObject) * b);\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Stack/StackFrame.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.Method;\n\nnamespace ILRuntime.Runtime.Stack\n{\n    public class IntegerReference\n    {\n        public int Value { get; set; }\n    }\n    unsafe public struct StackFrame\n    {\n        public ILMethod Method;\n        public StackObject* LocalVarPointer;\n        public StackObject* BasePointer;\n        public StackObject* ValueTypeBasePointer;\n        public IntegerReference Address;\n        public int ManagedStackBase;\n    }\n}\n"
  },
  {
    "path": "SGFUnity/ILRuntime/Runtime/Stack/StackObject.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ILRuntime.CLR.TypeSystem;\nusing ILRuntime.Runtime.Enviorment;\nusing ILRuntime.Runtime.Intepreter;\nnamespace ILRuntime.Runtime.Stack\n{\n    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]\n    public struct StackObject\n    {\n        public static StackObject Null = new StackObject() { ObjectType = ObjectTypes.Null, Value = -1, ValueLow = 0 };\n        public ObjectTypes ObjectType;\n        public int Value;\n        public int ValueLow;\n\n        //IL2CPP can't process esp->ToObject() properly, so I can only use static function for this\n        public static unsafe object ToObject(StackObject* esp, ILRuntime.Runtime.Enviorment.AppDomain appdomain, IList<object> mStack)\n        {\n            switch (esp->ObjectType)\n            {\n                case ObjectTypes.Integer:\n                    return esp->Value;\n                case ObjectTypes.Long:\n                    {\n                        return *(long*)&esp->Value;\n                    }\n                case ObjectTypes.Float:\n                    {\n                        return *(float*)&esp->Value;\n                    }\n                case ObjectTypes.Double:\n                    {\n                        return *(double*)&esp->Value;\n                    }\n                case ObjectTypes.Object:\n                    return mStack[esp->Value];\n                case ObjectTypes.FieldReference:\n                    {\n                        ILTypeInstance instance = mStack[esp->Value] as ILTypeInstance;\n                        if (instance != null)\n                        {\n                            return instance[esp->ValueLow];\n                        }\n                        else\n                        {\n                            var obj = mStack[esp->Value];\n                            IType t = null;\n                            if (obj is CrossBindingAdaptorType)\n                            {\n                                t = appdomain.GetType(((CrossBindingAdaptor)((CrossBindingAdaptorType)obj).ILInstance.Type.FirstCLRBaseType).BaseCLRType);\n                            }\n                            else\n                                t = appdomain.GetType(obj.GetType());\n\n                            return ((CLRType)t).GetFieldValue(esp->ValueLow, obj);\n                        }\n                    }\n                case ObjectTypes.ArrayReference:\n                    {\n                        Array instance = mStack[esp->Value] as Array;\n                        return instance.GetValue(esp->ValueLow);\n                    }\n                case ObjectTypes.StaticFieldReference:\n                    {\n                        var t = appdomain.GetType(esp->Value);\n                        if (t is CLR.TypeSystem.ILType)\n                        {\n                            CLR.TypeSystem.ILType type = (CLR.TypeSystem.ILType)t;\n                            return type.StaticInstance[esp->ValueLow];\n                        }\n                        else\n                        {\n                            CLR.TypeSystem.CLRType type = (CLR.TypeSystem.CLRType)t;\n                            return type.GetFieldValue(esp->ValueLow, null);\n                        }\n                    }\n                case ObjectTypes.StackObjectReference:\n                    {\n                        return ToObject((*(StackObject**)&esp->Value), appdomain, mStack);\n                    }\n                case ObjectTypes.ValueTypeObjectReference:\n                    {\n                        StackObject* dst = *(StackObject**)&esp->Value;\n                        IType type = appdomain.GetType(dst->Value);\n                        if (type is ILType)\n                        {\n                            ILType iltype = (ILType)type;\n                            var ins = iltype.Instantiate(false);\n                            for (int i = 0; i < dst->ValueLow; i++)\n                            {\n                                var addr = ILIntepreter.Minus(dst, i + 1);\n                                ins.AssignFromStack(i, addr, appdomain, mStack);\n                            }\n                            return ins;\n                        }\n                        else\n                        {\n                            return ((CLRType)type).ValueTypeBinder.ToObject(dst, mStack);\n                        }\n                    }\n                case ObjectTypes.Null:\n                    return null;\n                default:\n                    throw new NotImplementedException();\n            }\n        }\n\n        public unsafe static void Initialized(ref StackObject esp, int idx, Type t, IType fieldType, IList<object> mStack)\n        {\n            if (t.IsPrimitive)\n            {\n                if (t == typeof(int) || t == typeof(uint) || t == typeof(short) || t == typeof(ushort) || t == typeof(byte) || t == typeof(sbyte) || t == typeof(char) || t == typeof(bool))\n                {\n                    esp.ObjectType = ObjectTypes.Integer;\n                    esp.Value = 0;\n                    esp.ValueLow = 0;\n                }\n                else if (t == typeof(long) || t == typeof(ulong))\n                {\n                    esp.ObjectType = ObjectTypes.Long;\n                    esp.Value = 0;\n                    esp.ValueLow = 0;\n                }\n                else if (t == typeof(float))\n                {\n                    esp.ObjectType = ObjectTypes.Float;\n                    esp.Value = 0;\n                    esp.ValueLow = 0;\n                }\n                else if (t == typeof(double))\n                {\n                    esp.ObjectType = ObjectTypes.Double;\n                    esp.Value = 0;\n                    esp.ValueLow = 0;\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                if (fieldType.IsValueType)\n                {\n                    esp.ObjectType = ObjectTypes.Object;\n                    esp.Value = idx;\n                    if (fieldType is CLRType)\n                    {\n                        mStack[idx] = ((CLRType)fieldType).CreateDefaultInstance();\n                    }\n                    else\n                    {\n                        mStack[idx] = ((ILType)fieldType).Instantiate();\n                    }\n                }\n                else\n                    esp = Null;\n            }\n        }\n\n        //IL2CPP can't process esp->Initialized() properly, so I can only use static function for this\n        public unsafe static void Initialized(StackObject* esp, IType type)\n        {\n            var t = type.TypeForCLR;\n            if (type.IsPrimitive)\n            {\n                if (t == typeof(int) || t == typeof(uint) || t == typeof(short) || t == typeof(ushort) || t == typeof(byte) || t == typeof(sbyte) || t == typeof(char) || t == typeof(bool))\n                {\n                    esp->ObjectType = ObjectTypes.Integer;\n                    esp->Value = 0;\n                    esp->ValueLow = 0;\n                }\n                else if (t == typeof(long) || t == typeof(ulong))\n                {\n                    esp->ObjectType = ObjectTypes.Long;\n                    esp->Value = 0;\n                    esp->ValueLow = 0;\n                }\n                else if (t == typeof(float))\n                {\n                    esp->ObjectType = ObjectTypes.Float;\n                    esp->Value = 0;\n                    esp->ValueLow = 0;\n                }\n                else if (t == typeof(double))\n                {\n                    esp->ObjectType = ObjectTypes.Double;\n                    esp->Value = 0;\n                    esp->ValueLow = 0;\n                }\n                else\n                    throw new NotImplementedException();\n            }\n            else\n            {\n                *esp = Null;\n            }\n        }\n    }\n\n    public enum ObjectTypes\n    {\n        Null,\n        Integer,\n        Long,\n        Float,\n        Double,\n        StackObjectReference,//Value = pointer, \n        StaticFieldReference,\n        ValueTypeObjectReference,\n        ValueTypeDescriptor,\n        Object,\n        FieldReference,//Value = objIdx, ValueLow = fieldIdx\n        ArrayReference,//Value = objIdx, ValueLow = elemIdx\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono/Actions.cs",
    "content": "//\n// Actions.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\n#if !NET_3_5 && !NET_4_0\n\nnamespace Mono {\n\t//delegate void Action ();\n    delegate void Action<T1, T2> (T1 arg1, T2 arg2);\n\t//delegate void Action<T1, T2, T3> (T1 arg1, T2 arg2, T3 arg3);\n\t//delegate void Action<T1, T2, T3, T4> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);\n}\n\n#endif\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono/Empty.cs",
    "content": "//\n// Empty.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Collections.Generic;\n\nnamespace Mono {\n\n\tstatic class Empty<T> {\n\n\t\tpublic static readonly T [] Array = new T [0];\n\t}\n}\n\nnamespace Mono.Cecil {\n\n\tstatic partial class Mixin {\n\n\t\tpublic static bool IsNullOrEmpty<T> (T [] self)\n\t\t{\n\t\t\treturn self == null || self.Length == 0;\n\t\t}\n\n\t\tpublic static bool IsNullOrEmpty<T> (Collection<T> self)\n\t\t{\n\t\t\treturn self == null || self.size == 0;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono/Funcs.cs",
    "content": "//\n// Funcs.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\n#if !NET_3_5 && !NET_4_0\n\nnamespace Mono {\n    delegate TResult Func<TResult> ();\n    delegate TResult Func<T, TResult> (T arg1);\n    delegate TResult Func<T1, T2, TResult> (T1 arg1, T2 arg2);\n\t//delegate TResult Func<T1, T2, T3, TResult> (T1 arg1, T2 arg2, T3 arg3);\n\t//delegate TResult Func<T1, T2, T3, T4, TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);\n}\n\n#endif\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ArrayType.cs",
    "content": "//\n// ArrayType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\nusing Mono.Collections.Generic;\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic struct ArrayDimension {\n\n\t\tint? lower_bound;\n\t\tint? upper_bound;\n\n\t\tpublic int? LowerBound {\n\t\t\tget { return lower_bound; }\n\t\t\tset { lower_bound = value; }\n\t\t}\n\n\t\tpublic int? UpperBound {\n\t\t\tget { return upper_bound; }\n\t\t\tset { upper_bound = value; }\n\t\t}\n\n\t\tpublic bool IsSized {\n\t\t\tget { return lower_bound.HasValue || upper_bound.HasValue; }\n\t\t}\n\n\t\tpublic ArrayDimension (int? lowerBound, int? upperBound)\n\t\t{\n\t\t\tthis.lower_bound = lowerBound;\n\t\t\tthis.upper_bound = upperBound;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn !IsSized\n\t\t\t\t? string.Empty\n\t\t\t\t: lower_bound + \"...\" + upper_bound;\n\t\t}\n\t}\n\n\tpublic sealed class ArrayType : TypeSpecification {\n\n\t\tCollection<ArrayDimension> dimensions;\n\n\t\tpublic Collection<ArrayDimension> Dimensions {\n\t\t\tget {\n\t\t\t\tif (dimensions != null)\n\t\t\t\t\treturn dimensions;\n\n\t\t\t\tdimensions = new Collection<ArrayDimension> ();\n\t\t\t\tdimensions.Add (new ArrayDimension ());\n\t\t\t\treturn dimensions;\n\t\t\t}\n\t\t}\n\n\t\tpublic int Rank {\n\t\t\tget { return dimensions == null ? 1 : dimensions.Count; }\n\t\t}\n\n\t\tpublic bool IsVector {\n\t\t\tget {\n\t\t\t\tif (dimensions == null)\n\t\t\t\t\treturn true;\n\n\t\t\t\tif (dimensions.Count > 1)\n\t\t\t\t\treturn false;\n\n\t\t\t\tvar dimension = dimensions [0];\n\n\t\t\t\treturn !dimension.IsSized;\n\t\t\t}\n\t\t}\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return base.Name + Suffix; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return base.FullName + Suffix; }\n\t\t}\n\n\t\tstring Suffix {\n\t\t\tget {\n\t\t\t\tif (IsVector)\n\t\t\t\t\treturn \"[]\";\n\n\t\t\t\tvar suffix = new StringBuilder ();\n\t\t\t\tsuffix.Append (\"[\");\n\t\t\t\tfor (int i = 0; i < dimensions.Count; i++) {\n\t\t\t\t\tif (i > 0)\n\t\t\t\t\t\tsuffix.Append (\",\");\n\n\t\t\t\t\tsuffix.Append (dimensions [i].ToString ());\n\t\t\t\t}\n\t\t\t\tsuffix.Append (\"]\");\n\n\t\t\t\treturn suffix.ToString ();\n\t\t\t}\n\t\t}\n\n\t\tpublic override bool IsArray {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic ArrayType (TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.etype = MD.ElementType.Array;\n\t\t}\n\n\t\tpublic ArrayType (TypeReference type, int rank)\n\t\t\t: this (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\n\t\t\tif (rank == 1)\n\t\t\t\treturn;\n\n\t\t\tdimensions = new Collection<ArrayDimension> (rank);\n\t\t\tfor (int i = 0; i < rank; i++)\n\t\t\t\tdimensions.Add (new ArrayDimension ());\n\t\t\tthis.etype = MD.ElementType.Array;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyDefinition.cs",
    "content": "//\n// AssemblyDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class AssemblyDefinition : ICustomAttributeProvider, ISecurityDeclarationProvider\n    {\n\n        AssemblyNameDefinition name;\n\n        internal ModuleDefinition main_module;\n        Collection<ModuleDefinition> modules;\n        Collection<CustomAttribute> custom_attributes;\n        Collection<SecurityDeclaration> security_declarations;\n\n        public AssemblyNameDefinition Name\n        {\n            get { return name; }\n            set { name = value; }\n        }\n\n        public string FullName\n        {\n            get { return name != null ? name.FullName : string.Empty; }\n        }\n\n        public MetadataToken MetadataToken\n        {\n            get { return new MetadataToken(TokenType.Assembly, 1); }\n            set { }\n        }\n\n        public Collection<ModuleDefinition> Modules\n        {\n            get\n            {\n                if (modules != null)\n                    return modules;\n\n                if (main_module.HasImage)\n                    return main_module.Read(ref modules, this, (_, reader) => reader.ReadModules());\n\n                return modules = new Collection<ModuleDefinition>(1) { main_module };\n            }\n        }\n\n        public ModuleDefinition MainModule\n        {\n            get { return main_module; }\n        }\n\n        public MethodDefinition EntryPoint\n        {\n            get { return main_module.EntryPoint; }\n            set { main_module.EntryPoint = value; }\n        }\n\n        public bool HasCustomAttributes\n        {\n            get\n            {\n                if (custom_attributes != null)\n                    return custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, main_module);\n            }\n        }\n\n        public Collection<CustomAttribute> CustomAttributes\n        {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, main_module)); }\n        }\n\n        public bool HasSecurityDeclarations\n        {\n            get\n            {\n                if (security_declarations != null)\n                    return security_declarations.Count > 0;\n\n                return Mixin.GetHasSecurityDeclarations(this, main_module);\n            }\n        }\n\n        public Collection<SecurityDeclaration> SecurityDeclarations\n        {\n            get { return security_declarations ?? (Mixin.GetSecurityDeclarations(this, ref security_declarations, main_module)); }\n        }\n\n        internal AssemblyDefinition()\n        {\n        }\n\n\n\n        public static AssemblyDefinition ReadAssembly(string fileName)\n        {\n            return ReadAssembly(ModuleDefinition.ReadModule(fileName));\n        }\n\n        public static AssemblyDefinition ReadAssembly(string fileName, ReaderParameters parameters)\n        {\n            return ReadAssembly(ModuleDefinition.ReadModule(fileName, parameters));\n        }\n\n        public static AssemblyDefinition ReadAssembly(Stream stream)\n        {\n            return ReadAssembly(ModuleDefinition.ReadModule(stream));\n        }\n\n        public static AssemblyDefinition ReadAssembly(Stream stream, ReaderParameters parameters)\n        {\n            return ReadAssembly(ModuleDefinition.ReadModule(stream, parameters));\n        }\n\n        static AssemblyDefinition ReadAssembly(ModuleDefinition module)\n        {\n            var assembly = module.Assembly;\n            if (assembly == null)\n                throw new ArgumentException();\n\n            return assembly;\n        }\n\n\n\n        public override string ToString()\n        {\n            return this.FullName;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyFlags.cs",
    "content": "//\n// AssemblyFlags.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum AssemblyAttributes : uint {\n\t\tPublicKey\t\t\t\t\t \t= 0x0001,\n\t\tSideBySideCompatible\t\t\t= 0x0000,\n\t\tRetargetable\t\t\t\t\t= 0x0100,\n\t\tWindowsRuntime\t\t\t\t\t= 0x0200,\n\t\tDisableJITCompileOptimizer\t\t= 0x4000,\n\t\tEnableJITCompileTracking\t\t= 0x8000,\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyHashAlgorithm.cs",
    "content": "//\n// AssemblyHashAlgorithm.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum AssemblyHashAlgorithm : uint {\n\t\tNone\t\t= 0x0000,\n\t\tReserved\t= 0x8003,\t// MD5\n\t\tSHA1\t\t= 0x8004\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyLinkedResource.cs",
    "content": "//\n// AssemblyLinkedResource.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class AssemblyLinkedResource : Resource {\n\n\t\tAssemblyNameReference reference;\n\n\t\tpublic AssemblyNameReference Assembly {\n\t\t\tget { return reference; }\n\t\t\tset { reference = value; }\n\t\t}\n\n\t\tpublic override ResourceType ResourceType {\n\t\t\tget { return ResourceType.AssemblyLinked; }\n\t\t}\n\n\t\tpublic AssemblyLinkedResource (string name, ManifestResourceAttributes flags)\n\t\t\t: base (name, flags)\n\t\t{\n\t\t}\n\n\t\tpublic AssemblyLinkedResource (string name, ManifestResourceAttributes flags, AssemblyNameReference reference)\n\t\t\t: base (name, flags)\n\t\t{\n\t\t\tthis.reference = reference;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyNameDefinition.cs",
    "content": "//\n// AssemblyNameDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class AssemblyNameDefinition : AssemblyNameReference {\n\n\t\tpublic override byte [] Hash {\n\t\t\tget { return Empty<byte>.Array; }\n\t\t}\n\n\t\tinternal AssemblyNameDefinition ()\n\t\t{\n\t\t\tthis.token = new MetadataToken (TokenType.Assembly, 1);\n\t\t}\n\n\t\tpublic AssemblyNameDefinition (string name, Version version)\n\t\t\t: base (name, version)\n\t\t{\n\t\t\tthis.token = new MetadataToken (TokenType.Assembly, 1);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyNameReference.cs",
    "content": "//\n// AssemblyNameReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Globalization;\nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace Mono.Cecil\n{\n\n    public class AssemblyNameReference : IMetadataScope\n    {\n\n        string name;\n        string culture;\n        Version version;\n        uint attributes;\n        byte[] public_key;\n        byte[] public_key_token;\n        AssemblyHashAlgorithm hash_algorithm;\n        byte[] hash;\n\n        internal MetadataToken token;\n\n        string full_name;\n\n        public string Name\n        {\n            get { return name; }\n            set\n            {\n                name = value;\n                full_name = null;\n            }\n        }\n\n        public string Culture\n        {\n            get { return culture; }\n            set\n            {\n                culture = value;\n                full_name = null;\n            }\n        }\n\n        public Version Version\n        {\n            get { return version; }\n            set\n            {\n                version = value;\n                full_name = null;\n            }\n        }\n\n        public AssemblyAttributes Attributes\n        {\n            get { return (AssemblyAttributes)attributes; }\n            set { attributes = (uint)value; }\n        }\n\n        public bool HasPublicKey\n        {\n            get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.PublicKey); }\n            set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.PublicKey, value); }\n        }\n\n        public bool IsSideBySideCompatible\n        {\n            get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.SideBySideCompatible); }\n            set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.SideBySideCompatible, value); }\n        }\n\n        public bool IsRetargetable\n        {\n            get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.Retargetable); }\n            set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.Retargetable, value); }\n        }\n\n        public bool IsWindowsRuntime\n        {\n            get { return Mixin.GetAttributes(attributes,(uint)AssemblyAttributes.WindowsRuntime); }\n            set { attributes =Mixin.SetAttributes(attributes,(uint)AssemblyAttributes.WindowsRuntime, value); }\n        }\n\n        public byte[] PublicKey\n        {\n            get { return public_key ?? Empty<byte>.Array; }\n            set\n            {\n                public_key = value;\n                HasPublicKey = !Mixin.IsNullOrEmpty(public_key);\n                public_key_token = Empty<byte>.Array;\n                full_name = null;\n            }\n        }\n\n        public byte[] PublicKeyToken\n        {\n            get\n            {\n                if (Mixin.IsNullOrEmpty(public_key_token) && !Mixin.IsNullOrEmpty(public_key))\n                {\n                    var hash = HashPublicKey();\n                    // we need the last 8 bytes in reverse order\n                    byte[] local_public_key_token = new byte[8];\n                    Array.Copy(hash, (hash.Length - 8), local_public_key_token, 0, 8);\n                    Array.Reverse(local_public_key_token, 0, 8);\n                    public_key_token = local_public_key_token; // publish only once finished (required for thread-safety)\n                }\n                return public_key_token ?? Empty<byte>.Array;\n            }\n            set\n            {\n                public_key_token = value;\n                full_name = null;\n            }\n        }\n\n        byte[] HashPublicKey()\n        {\n            HashAlgorithm algorithm;\n\n            switch (hash_algorithm)\n            {\n                case AssemblyHashAlgorithm.Reserved:\n\n                    throw new NotSupportedException();\n\n                default:\n                    // None default to SHA1\n                    algorithm = new SHA1Managed();\n                    break;\n\n            }\n\n            using (algorithm)\n                return algorithm.ComputeHash(public_key);\n        }\n\n        public virtual MetadataScopeType MetadataScopeType\n        {\n            get { return MetadataScopeType.AssemblyNameReference; }\n        }\n\n        public string FullName\n        {\n            get\n            {\n                if (full_name != null)\n                    return full_name;\n\n                const string sep = \", \";\n\n                var builder = new StringBuilder();\n                builder.Append(name);\n                if (version != null)\n                {\n                    builder.Append(sep);\n                    builder.Append(\"Version=\");\n                    builder.Append(version.ToString());\n                }\n                builder.Append(sep);\n                builder.Append(\"Culture=\");\n                builder.Append(string.IsNullOrEmpty(culture) ? \"neutral\" : culture);\n                builder.Append(sep);\n                builder.Append(\"PublicKeyToken=\");\n\n                var pk_token = PublicKeyToken;\n                if (!Mixin.IsNullOrEmpty(pk_token) && pk_token.Length > 0)\n                {\n                    for (int i = 0; i < pk_token.Length; i++)\n                    {\n                        builder.Append(pk_token[i].ToString(\"x2\"));\n                    }\n                }\n                else\n                    builder.Append(\"null\");\n\n                return full_name = builder.ToString();\n            }\n        }\n\n        public static AssemblyNameReference Parse(string fullName)\n        {\n            if (fullName == null)\n                throw new ArgumentNullException(\"fullName\");\n            if (fullName.Length == 0)\n                throw new ArgumentException(\"Name can not be empty\");\n\n            var name = new AssemblyNameReference();\n            var tokens = fullName.Split(',');\n            for (int i = 0; i < tokens.Length; i++)\n            {\n                var token = tokens[i].Trim();\n\n                if (i == 0)\n                {\n                    name.Name = token;\n                    continue;\n                }\n\n                var parts = token.Split('=');\n                if (parts.Length != 2)\n                    throw new ArgumentException(\"Malformed name\");\n\n                switch (parts[0].ToLowerInvariant())\n                {\n                    case \"version\":\n                        name.Version = new Version(parts[1]);\n                        break;\n                    case \"culture\":\n                        name.Culture = parts[1];\n                        break;\n                    case \"publickeytoken\":\n                        var pk_token = parts[1];\n                        if (pk_token == \"null\")\n                            break;\n\n                        name.PublicKeyToken = new byte[pk_token.Length / 2];\n                        for (int j = 0; j < name.PublicKeyToken.Length; j++)\n                            name.PublicKeyToken[j] = Byte.Parse(pk_token.Substring(j * 2, 2), NumberStyles.HexNumber);\n\n                        break;\n                }\n            }\n\n            return name;\n        }\n\n        public AssemblyHashAlgorithm HashAlgorithm\n        {\n            get { return hash_algorithm; }\n            set { hash_algorithm = value; }\n        }\n\n        public virtual byte[] Hash\n        {\n            get { return hash; }\n            set { hash = value; }\n        }\n\n        public MetadataToken MetadataToken\n        {\n            get { return token; }\n            set { token = value; }\n        }\n\n        internal AssemblyNameReference()\n        {\n        }\n\n        public AssemblyNameReference(string name, Version version)\n        {\n            if (name == null)\n                throw new ArgumentNullException(\"name\");\n\n            this.name = name;\n            this.version = version;\n            this.hash_algorithm = AssemblyHashAlgorithm.None;\n            this.token = new MetadataToken(TokenType.AssemblyRef);\n        }\n\n        public override string ToString()\n        {\n            return this.FullName;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyReader.cs",
    "content": "//\n// AssemblyReader.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nusing Mono.Collections.Generic;\nusing Mono.Cecil.Cil;\nusing Mono.Cecil.Metadata;\nusing Mono.Cecil.PE;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil\n{\n\n    abstract class ModuleReader\n    {\n\n        readonly protected Image image;\n        readonly protected ModuleDefinition module;\n\n        protected ModuleReader(Image image, ReadingMode mode)\n        {\n            this.image = image;\n            this.module = new ModuleDefinition(image);\n            this.module.ReadingMode = mode;\n        }\n\n        protected abstract void ReadModule();\n\n        protected void ReadModuleManifest(MetadataReader reader)\n        {\n            reader.Populate(module);\n\n            ReadAssembly(reader);\n        }\n\n        void ReadAssembly(MetadataReader reader)\n        {\n            var name = reader.ReadAssemblyNameDefinition();\n            if (name == null)\n            {\n                module.kind = ModuleKind.NetModule;\n                return;\n            }\n\n            var assembly = new AssemblyDefinition();\n            assembly.Name = name;\n\n            module.assembly = assembly;\n            assembly.main_module = module;\n        }\n\n        public static ModuleDefinition CreateModuleFrom(Image image, ReaderParameters parameters)\n        {\n            var module = ReadModule(image, parameters);\n\n            ReadSymbols(module, parameters);\n\n            if (parameters.AssemblyResolver != null)\n                module.assembly_resolver = parameters.AssemblyResolver;\n\n            if (parameters.MetadataResolver != null)\n                module.metadata_resolver = parameters.MetadataResolver;\n\n            return module;\n        }\n\n        static void ReadSymbols(ModuleDefinition module, ReaderParameters parameters)\n        {\n            var symbol_reader_provider = parameters.SymbolReaderProvider;\n\n            if (symbol_reader_provider == null && parameters.ReadSymbols)\n                symbol_reader_provider = SymbolProvider.GetPlatformReaderProvider();\n\n            if (symbol_reader_provider != null)\n            {\n                module.SymbolReaderProvider = symbol_reader_provider;\n\n                var reader = parameters.SymbolStream != null\n                    ? symbol_reader_provider.GetSymbolReader(module, parameters.SymbolStream)\n                    : symbol_reader_provider.GetSymbolReader(module, module.FullyQualifiedName);\n\n                module.ReadSymbols(reader);\n            }\n        }\n\n        static ModuleDefinition ReadModule(Image image, ReaderParameters parameters)\n        {\n            var reader = CreateModuleReader(image, parameters.ReadingMode);\n            reader.ReadModule();\n            return reader.module;\n        }\n\n        static ModuleReader CreateModuleReader(Image image, ReadingMode mode)\n        {\n            switch (mode)\n            {\n                case ReadingMode.Immediate:\n                    return new ImmediateModuleReader(image);\n                case ReadingMode.Deferred:\n                    return new DeferredModuleReader(image);\n                default:\n                    throw new ArgumentException();\n            }\n        }\n    }\n\n    sealed class ImmediateModuleReader : ModuleReader\n    {\n\n        public ImmediateModuleReader(Image image)\n            : base(image, ReadingMode.Immediate)\n        {\n        }\n\n        protected override void ReadModule()\n        {\n            this.module.Read(this.module, (module, reader) =>\n            {\n                ReadModuleManifest(reader);\n                ReadModule(module);\n                return module;\n            });\n        }\n\n        public static void ReadModule(ModuleDefinition module)\n        {\n            if (module.HasAssemblyReferences)\n                Read(module.AssemblyReferences);\n            if (module.HasResources)\n                Read(module.Resources);\n            if (module.HasModuleReferences)\n                Read(module.ModuleReferences);\n            if (module.HasTypes)\n                ReadTypes(module.Types);\n            if (module.HasExportedTypes)\n                Read(module.ExportedTypes);\n            if (module.HasCustomAttributes)\n                Read(module.CustomAttributes);\n\n            var assembly = module.Assembly;\n            if (assembly == null)\n                return;\n\n            if (assembly.HasCustomAttributes)\n                Read(assembly.CustomAttributes);\n            if (assembly.HasSecurityDeclarations)\n                Read(assembly.SecurityDeclarations);\n        }\n\n        static void ReadTypes(Collection<TypeDefinition> types)\n        {\n            for (int i = 0; i < types.Count; i++)\n                ReadType(types[i]);\n        }\n\n        static void ReadType(TypeDefinition type)\n        {\n            ReadGenericParameters(type);\n\n            if (type.HasInterfaces)\n                Read(type.Interfaces);\n\n            if (type.HasNestedTypes)\n                ReadTypes(type.NestedTypes);\n\n            if (type.HasLayoutInfo)\n                Read(type.ClassSize);\n\n            if (type.HasFields)\n                ReadFields(type);\n\n            if (type.HasMethods)\n                ReadMethods(type);\n\n            if (type.HasProperties)\n                ReadProperties(type);\n\n            if (type.HasEvents)\n                ReadEvents(type);\n\n            ReadSecurityDeclarations(type);\n            ReadCustomAttributes(type);\n        }\n\n        static void ReadGenericParameters(IGenericParameterProvider provider)\n        {\n            if (!provider.HasGenericParameters)\n                return;\n\n            var parameters = provider.GenericParameters;\n\n            for (int i = 0; i < parameters.Count; i++)\n            {\n                var parameter = parameters[i];\n\n                if (parameter.HasConstraints)\n                    Read(parameter.Constraints);\n\n                if (parameter.HasCustomAttributes)\n                    Read(parameter.CustomAttributes);\n            }\n        }\n\n        static void ReadSecurityDeclarations(ISecurityDeclarationProvider provider)\n        {\n            if (provider.HasSecurityDeclarations)\n                Read(provider.SecurityDeclarations);\n        }\n\n        static void ReadCustomAttributes(ICustomAttributeProvider provider)\n        {\n            if (provider.HasCustomAttributes)\n                Read(provider.CustomAttributes);\n        }\n\n        static void ReadFields(TypeDefinition type)\n        {\n            var fields = type.Fields;\n\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var field = fields[i];\n\n                if (field.HasConstant)\n                    Read(field.Constant);\n\n                if (field.HasLayoutInfo)\n                    Read(field.Offset);\n\n                if (field.RVA > 0)\n                    Read(field.InitialValue);\n\n                if (field.HasMarshalInfo)\n                    Read(field.MarshalInfo);\n\n                ReadCustomAttributes(field);\n            }\n        }\n\n        static void ReadMethods(TypeDefinition type)\n        {\n            var methods = type.Methods;\n\n            for (int i = 0; i < methods.Count; i++)\n            {\n                var method = methods[i];\n\n                ReadGenericParameters(method);\n\n                if (method.HasParameters)\n                    ReadParameters(method);\n\n                if (method.HasOverrides)\n                    Read(method.Overrides);\n\n                if (method.IsPInvokeImpl)\n                    Read(method.PInvokeInfo);\n\n                ReadSecurityDeclarations(method);\n                ReadCustomAttributes(method);\n\n                var return_type = method.MethodReturnType;\n                if (return_type.HasConstant)\n                    Read(return_type.Constant);\n\n                if (return_type.HasMarshalInfo)\n                    Read(return_type.MarshalInfo);\n\n                ReadCustomAttributes(return_type);\n            }\n        }\n\n        static void ReadParameters(MethodDefinition method)\n        {\n            var parameters = method.Parameters;\n\n            for (int i = 0; i < parameters.Count; i++)\n            {\n                var parameter = parameters[i];\n\n                if (parameter.HasConstant)\n                    Read(parameter.Constant);\n\n                if (parameter.HasMarshalInfo)\n                    Read(parameter.MarshalInfo);\n\n                ReadCustomAttributes(parameter);\n            }\n        }\n\n        static void ReadProperties(TypeDefinition type)\n        {\n            var properties = type.Properties;\n\n            for (int i = 0; i < properties.Count; i++)\n            {\n                var property = properties[i];\n\n                Read(property.GetMethod);\n\n                if (property.HasConstant)\n                    Read(property.Constant);\n\n                ReadCustomAttributes(property);\n            }\n        }\n\n        static void ReadEvents(TypeDefinition type)\n        {\n            var events = type.Events;\n\n            for (int i = 0; i < events.Count; i++)\n            {\n                var @event = events[i];\n\n                Read(@event.AddMethod);\n\n                ReadCustomAttributes(@event);\n            }\n        }\n\n        static void Read(object collection)\n        {\n        }\n    }\n\n    sealed class DeferredModuleReader : ModuleReader\n    {\n\n        public DeferredModuleReader(Image image)\n            : base(image, ReadingMode.Deferred)\n        {\n        }\n\n        protected override void ReadModule()\n        {\n            this.module.Read(this.module, (module, reader) =>\n            {\n                ReadModuleManifest(reader);\n                return module;\n            });\n        }\n    }\n\n    sealed class MetadataReader : ByteBuffer\n    {\n\n        readonly internal Image image;\n        readonly internal ModuleDefinition module;\n        readonly internal MetadataSystem metadata;\n\n        internal IGenericContext context;\n        internal CodeReader code;\n\n        uint Position\n        {\n            get { return (uint)base.position; }\n            set { base.position = (int)value; }\n        }\n\n        public MetadataReader(ModuleDefinition module)\n            : base(module.Image.MetadataSection.Data)\n        {\n            this.image = module.Image;\n            this.module = module;\n            this.metadata = module.MetadataSystem;\n            this.code = new CodeReader(image.MetadataSection, this);\n        }\n\n        int GetCodedIndexSize(CodedIndex index)\n        {\n            return image.GetCodedIndexSize(index);\n        }\n\n        uint ReadByIndexSize(int size)\n        {\n            if (size == 4)\n                return ReadUInt32();\n            else\n                return ReadUInt16();\n        }\n\n        byte[] ReadBlob()\n        {\n            var blob_heap = image.BlobHeap;\n            if (blob_heap == null)\n            {\n                position += 2;\n                return Empty<byte>.Array;\n            }\n\n            return blob_heap.Read(ReadBlobIndex());\n        }\n\n        byte[] ReadBlob(uint signature)\n        {\n            var blob_heap = image.BlobHeap;\n            if (blob_heap == null)\n                return Empty<byte>.Array;\n\n            return blob_heap.Read(signature);\n        }\n\n        uint ReadBlobIndex()\n        {\n            var blob_heap = image.BlobHeap;\n            return ReadByIndexSize(blob_heap != null ? blob_heap.IndexSize : 2);\n        }\n\n        string ReadString()\n        {\n            return image.StringHeap.Read(ReadByIndexSize(image.StringHeap.IndexSize));\n        }\n\n        uint ReadStringIndex()\n        {\n            return ReadByIndexSize(image.StringHeap.IndexSize);\n        }\n\n        uint ReadTableIndex(Table table)\n        {\n            return ReadByIndexSize(image.GetTableIndexSize(table));\n        }\n\n        MetadataToken ReadMetadataToken(CodedIndex index)\n        {\n            return Mixin.GetMetadataToken(index, ReadByIndexSize(GetCodedIndexSize(index)));\n        }\n\n        int MoveTo(Table table)\n        {\n            var info = image.TableHeap[table];\n            if (info.Length != 0)\n                Position = info.Offset;\n\n            return (int)info.Length;\n        }\n\n        bool MoveTo(Table table, uint row)\n        {\n            var info = image.TableHeap[table];\n            var length = info.Length;\n            if (length == 0 || row > length)\n                return false;\n\n            Position = info.Offset + (info.RowSize * (row - 1));\n            return true;\n        }\n\n        public AssemblyNameDefinition ReadAssemblyNameDefinition()\n        {\n            if (MoveTo(Table.Assembly) == 0)\n                return null;\n\n            var name = new AssemblyNameDefinition();\n\n            name.HashAlgorithm = (AssemblyHashAlgorithm)ReadUInt32();\n\n            PopulateVersionAndFlags(name);\n\n            name.PublicKey = ReadBlob();\n\n            PopulateNameAndCulture(name);\n\n            return name;\n        }\n\n        public ModuleDefinition Populate(ModuleDefinition module)\n        {\n            if (MoveTo(Table.Module) == 0)\n                return module;\n\n            Advance(2); // Generation\n\n            module.Name = ReadString();\n            module.Mvid = image.GuidHeap.Read(ReadByIndexSize(image.GuidHeap.IndexSize));\n\n            return module;\n        }\n\n        void InitializeAssemblyReferences()\n        {\n            if (metadata.AssemblyReferences != null)\n                return;\n\n            int length = MoveTo(Table.AssemblyRef);\n            var references = metadata.AssemblyReferences = new AssemblyNameReference[length];\n\n            for (uint i = 0; i < length; i++)\n            {\n                var reference = new AssemblyNameReference();\n                reference.token = new MetadataToken(TokenType.AssemblyRef, i + 1);\n\n                PopulateVersionAndFlags(reference);\n\n                var key_or_token = ReadBlob();\n\n                if (reference.HasPublicKey)\n                    reference.PublicKey = key_or_token;\n                else\n                    reference.PublicKeyToken = key_or_token;\n\n                PopulateNameAndCulture(reference);\n\n                reference.Hash = ReadBlob();\n\n                references[i] = reference;\n            }\n        }\n\n        public Collection<AssemblyNameReference> ReadAssemblyReferences()\n        {\n            InitializeAssemblyReferences();\n\n            return new Collection<AssemblyNameReference>(metadata.AssemblyReferences);\n        }\n\n        public MethodDefinition ReadEntryPoint()\n        {\n            if (module.Image.EntryPointToken == 0)\n                return null;\n\n            var token = new MetadataToken(module.Image.EntryPointToken);\n            return GetMethodDefinition(token.RID);\n        }\n\n        public Collection<ModuleDefinition> ReadModules()\n        {\n            var modules = new Collection<ModuleDefinition>(1);\n            modules.Add(this.module);\n\n            int length = MoveTo(Table.File);\n            for (uint i = 1; i <= length; i++)\n            {\n                var attributes = (FileAttributes)ReadUInt32();\n                var name = ReadString();\n                ReadBlobIndex();\n\n                if (attributes != FileAttributes.ContainsMetaData)\n                    continue;\n\n                var parameters = new ReaderParameters\n                {\n                    ReadingMode = module.ReadingMode,\n                    SymbolReaderProvider = module.SymbolReaderProvider,\n                };\n\n                modules.Add(ModuleDefinition.ReadModule(\n                    GetModuleFileName(name), parameters));\n            }\n\n            return modules;\n        }\n\n        string GetModuleFileName(string name)\n        {\n            if (module.FullyQualifiedName == null)\n                throw new NotSupportedException();\n\n            var path = Path.GetDirectoryName(module.FullyQualifiedName);\n            return Path.Combine(path, name);\n        }\n\n        void InitializeModuleReferences()\n        {\n            if (metadata.ModuleReferences != null)\n                return;\n\n            int length = MoveTo(Table.ModuleRef);\n            var references = metadata.ModuleReferences = new ModuleReference[length];\n\n            for (uint i = 0; i < length; i++)\n            {\n                var reference = new ModuleReference(ReadString());\n                reference.token = new MetadataToken(TokenType.ModuleRef, i + 1);\n\n                references[i] = reference;\n            }\n        }\n\n        public Collection<ModuleReference> ReadModuleReferences()\n        {\n            InitializeModuleReferences();\n\n            return new Collection<ModuleReference>(metadata.ModuleReferences);\n        }\n\n        public bool HasFileResource()\n        {\n            int length = MoveTo(Table.File);\n            if (length == 0)\n                return false;\n\n            for (uint i = 1; i <= length; i++)\n                if (ReadFileRecord(i).Col1 == FileAttributes.ContainsNoMetaData)\n                    return true;\n\n            return false;\n        }\n\n        public Collection<Resource> ReadResources()\n        {\n            int length = MoveTo(Table.ManifestResource);\n            var resources = new Collection<Resource>(length);\n\n            for (int i = 1; i <= length; i++)\n            {\n                var offset = ReadUInt32();\n                var flags = (ManifestResourceAttributes)ReadUInt32();\n                var name = ReadString();\n                var implementation = ReadMetadataToken(CodedIndex.Implementation);\n\n                Resource resource;\n\n                if (implementation.RID == 0)\n                {\n                    resource = new EmbeddedResource(name, flags, offset, this);\n                }\n                else if (implementation.TokenType == TokenType.AssemblyRef)\n                {\n                    resource = new AssemblyLinkedResource(name, flags)\n                    {\n                        Assembly = (AssemblyNameReference)GetTypeReferenceScope(implementation),\n                    };\n                }\n                else if (implementation.TokenType == TokenType.File)\n                {\n                    var file_record = ReadFileRecord(implementation.RID);\n\n                    resource = new LinkedResource(name, flags)\n                    {\n                        File = file_record.Col2,\n                        hash = ReadBlob(file_record.Col3)\n                    };\n                }\n                else\n                    throw new NotSupportedException();\n\n                resources.Add(resource);\n            }\n\n            return resources;\n        }\n\n        Row<FileAttributes, string, uint> ReadFileRecord(uint rid)\n        {\n            var position = this.position;\n\n            if (!MoveTo(Table.File, rid))\n                throw new ArgumentException();\n\n            var record = new Row<FileAttributes, string, uint>(\n                (FileAttributes)ReadUInt32(),\n                ReadString(),\n                ReadBlobIndex());\n\n            this.position = position;\n\n            return record;\n        }\n\n        public MemoryStream GetManagedResourceStream(uint offset)\n        {\n            var rva = image.Resources.VirtualAddress;\n            var section = image.GetSectionAtVirtualAddress(rva);\n            var position = (rva - section.VirtualAddress) + offset;\n            var buffer = section.Data;\n\n            var length = buffer[position]\n                | (buffer[position + 1] << 8)\n                | (buffer[position + 2] << 16)\n                | (buffer[position + 3] << 24);\n\n            return new MemoryStream(buffer, (int)position + 4, length);\n        }\n\n        void PopulateVersionAndFlags(AssemblyNameReference name)\n        {\n            name.Version = new Version(\n                ReadUInt16(),\n                ReadUInt16(),\n                ReadUInt16(),\n                ReadUInt16());\n\n            name.Attributes = (AssemblyAttributes)ReadUInt32();\n        }\n\n        void PopulateNameAndCulture(AssemblyNameReference name)\n        {\n            name.Name = ReadString();\n            name.Culture = ReadString();\n        }\n\n        public TypeDefinitionCollection ReadTypes()\n        {\n            InitializeTypeDefinitions();\n            var mtypes = metadata.Types;\n            var type_count = mtypes.Length - metadata.NestedTypes.Count;\n            var types = new TypeDefinitionCollection(module, type_count);\n\n            for (int i = 0; i < mtypes.Length; i++)\n            {\n                var type = mtypes[i];\n                if (IsNested(type.Attributes))\n                    continue;\n\n                types.Add(type);\n            }\n\n            if (image.HasTable(Table.MethodPtr) || image.HasTable(Table.FieldPtr))\n                CompleteTypes();\n\n            return types;\n        }\n\n        void CompleteTypes()\n        {\n            var types = metadata.Types;\n\n            for (int i = 0; i < types.Length; i++)\n            {\n                var type = types[i];\n\n                InitializeCollection(type.Fields);\n                InitializeCollection(type.Methods);\n            }\n        }\n\n        void InitializeTypeDefinitions()\n        {\n            if (metadata.Types != null)\n                return;\n\n            InitializeNestedTypes();\n            InitializeFields();\n            InitializeMethods();\n\n            int length = MoveTo(Table.TypeDef);\n            var types = metadata.Types = new TypeDefinition[length];\n\n            for (uint i = 0; i < length; i++)\n            {\n                if (types[i] != null)\n                    continue;\n\n                types[i] = ReadType(i + 1);\n            }\n        }\n\n        static bool IsNested(TypeAttributes attributes)\n        {\n            switch (attributes & TypeAttributes.VisibilityMask)\n            {\n                case TypeAttributes.NestedAssembly:\n                case TypeAttributes.NestedFamANDAssem:\n                case TypeAttributes.NestedFamily:\n                case TypeAttributes.NestedFamORAssem:\n                case TypeAttributes.NestedPrivate:\n                case TypeAttributes.NestedPublic:\n                    return true;\n                default:\n                    return false;\n            }\n        }\n\n        public bool HasNestedTypes(TypeDefinition type)\n        {\n            uint[] mapping;\n            InitializeNestedTypes();\n\n            if (!metadata.TryGetNestedTypeMapping(type, out mapping))\n                return false;\n\n            return mapping.Length > 0;\n        }\n\n        public Collection<TypeDefinition> ReadNestedTypes(TypeDefinition type)\n        {\n            InitializeNestedTypes();\n            uint[] mapping;\n            if (!metadata.TryGetNestedTypeMapping(type, out mapping))\n                return new MemberDefinitionCollection<TypeDefinition>(type);\n\n            var nested_types = new MemberDefinitionCollection<TypeDefinition>(type, mapping.Length);\n\n            for (int i = 0; i < mapping.Length; i++)\n            {\n                var nested_type = GetTypeDefinition(mapping[i]);\n\n                if (nested_type != null)\n                    nested_types.Add(nested_type);\n            }\n\n            metadata.RemoveNestedTypeMapping(type);\n\n            return nested_types;\n        }\n\n        void InitializeNestedTypes()\n        {\n            if (metadata.NestedTypes != null)\n                return;\n\n            var length = MoveTo(Table.NestedClass);\n\n            metadata.NestedTypes = new Dictionary<uint, uint[]>(length);\n            metadata.ReverseNestedTypes = new Dictionary<uint, uint>(length);\n\n            if (length == 0)\n                return;\n\n            for (int i = 1; i <= length; i++)\n            {\n                var nested = ReadTableIndex(Table.TypeDef);\n                var declaring = ReadTableIndex(Table.TypeDef);\n\n                AddNestedMapping(declaring, nested);\n            }\n        }\n\n        void AddNestedMapping(uint declaring, uint nested)\n        {\n            metadata.SetNestedTypeMapping(declaring, AddMapping(metadata.NestedTypes, declaring, nested));\n            metadata.SetReverseNestedTypeMapping(nested, declaring);\n        }\n\n        static TValue[] AddMapping<TKey, TValue>(Dictionary<TKey, TValue[]> cache, TKey key, TValue value)\n        {\n            TValue[] mapped;\n            if (!cache.TryGetValue(key, out mapped))\n            {\n                mapped = new[] { value };\n                return mapped;\n            }\n\n            var new_mapped = new TValue[mapped.Length + 1];\n            Array.Copy(mapped, new_mapped, mapped.Length);\n            new_mapped[mapped.Length] = value;\n            return new_mapped;\n        }\n\n        TypeDefinition ReadType(uint rid)\n        {\n            if (!MoveTo(Table.TypeDef, rid))\n                return null;\n\n            var attributes = (TypeAttributes)ReadUInt32();\n            var name = ReadString();\n            var @namespace = ReadString();\n            var type = new TypeDefinition(@namespace, name, attributes);\n            type.token = new MetadataToken(TokenType.TypeDef, rid);\n            type.scope = module;\n            type.module = module;\n\n            metadata.AddTypeDefinition(type);\n\n            this.context = type;\n\n            type.BaseType = GetTypeDefOrRef(ReadMetadataToken(CodedIndex.TypeDefOrRef));\n\n            type.fields_range = ReadFieldsRange(rid);\n            type.methods_range = ReadMethodsRange(rid);\n\n            if (IsNested(attributes))\n                type.DeclaringType = GetNestedTypeDeclaringType(type);\n\n            return type;\n        }\n\n        TypeDefinition GetNestedTypeDeclaringType(TypeDefinition type)\n        {\n            uint declaring_rid;\n            if (!metadata.TryGetReverseNestedTypeMapping(type, out declaring_rid))\n                return null;\n\n            metadata.RemoveReverseNestedTypeMapping(type);\n            return GetTypeDefinition(declaring_rid);\n        }\n\n        Range ReadFieldsRange(uint type_index)\n        {\n            return ReadListRange(type_index, Table.TypeDef, Table.Field);\n        }\n\n        Range ReadMethodsRange(uint type_index)\n        {\n            return ReadListRange(type_index, Table.TypeDef, Table.Method);\n        }\n\n        Range ReadListRange(uint current_index, Table current, Table target)\n        {\n            var list = new Range();\n\n            list.Start = ReadTableIndex(target);\n\n            uint next_index;\n            var current_table = image.TableHeap[current];\n\n            if (current_index == current_table.Length)\n                next_index = image.TableHeap[target].Length + 1;\n            else\n            {\n                var position = Position;\n                Position += (uint)(current_table.RowSize - image.GetTableIndexSize(target));\n                next_index = ReadTableIndex(target);\n                Position = position;\n            }\n\n            list.Length = next_index - list.Start;\n\n            return list;\n        }\n\n        public Row<short, int> ReadTypeLayout(TypeDefinition type)\n        {\n            InitializeTypeLayouts();\n            Row<ushort, uint> class_layout;\n            var rid = type.token.RID;\n            if (!metadata.ClassLayouts.TryGetValue(rid, out class_layout))\n                return new Row<short, int>(Mixin.NoDataMarker, Mixin.NoDataMarker);\n\n            type.PackingSize = (short)class_layout.Col1;\n            type.ClassSize = (int)class_layout.Col2;\n\n            metadata.ClassLayouts.Remove(rid);\n\n            return new Row<short, int>((short)class_layout.Col1, (int)class_layout.Col2);\n        }\n\n        void InitializeTypeLayouts()\n        {\n            if (metadata.ClassLayouts != null)\n                return;\n\n            int length = MoveTo(Table.ClassLayout);\n\n            var class_layouts = metadata.ClassLayouts = new Dictionary<uint, Row<ushort, uint>>(length);\n\n            for (uint i = 0; i < length; i++)\n            {\n                var packing_size = ReadUInt16();\n                var class_size = ReadUInt32();\n\n                var parent = ReadTableIndex(Table.TypeDef);\n\n                class_layouts.Add(parent, new Row<ushort, uint>(packing_size, class_size));\n            }\n        }\n\n        public TypeReference GetTypeDefOrRef(MetadataToken token)\n        {\n            return (TypeReference)LookupToken(token);\n        }\n\n        public TypeDefinition GetTypeDefinition(uint rid)\n        {\n            InitializeTypeDefinitions();\n\n            var type = metadata.GetTypeDefinition(rid);\n            if (type != null)\n                return type;\n\n            return ReadTypeDefinition(rid);\n        }\n\n        TypeDefinition ReadTypeDefinition(uint rid)\n        {\n            if (!MoveTo(Table.TypeDef, rid))\n                return null;\n\n            return ReadType(rid);\n        }\n\n        void InitializeTypeReferences()\n        {\n            if (metadata.TypeReferences != null)\n                return;\n\n            metadata.TypeReferences = new TypeReference[image.GetTableLength(Table.TypeRef)];\n        }\n\n        public TypeReference GetTypeReference(string scope, string full_name)\n        {\n            InitializeTypeReferences();\n\n            var length = metadata.TypeReferences.Length;\n\n            for (uint i = 1; i <= length; i++)\n            {\n                var type = GetTypeReference(i);\n\n                if (type.FullName != full_name)\n                    continue;\n\n                if (string.IsNullOrEmpty(scope))\n                    return type;\n\n                if (type.Scope.Name == scope)\n                    return type;\n            }\n\n            return null;\n        }\n\n        TypeReference GetTypeReference(uint rid)\n        {\n            InitializeTypeReferences();\n\n            var type = metadata.GetTypeReference(rid);\n            if (type != null)\n                return type;\n\n            return ReadTypeReference(rid);\n        }\n\n        TypeReference ReadTypeReference(uint rid)\n        {\n            if (!MoveTo(Table.TypeRef, rid))\n                return null;\n\n            TypeReference declaring_type = null;\n            IMetadataScope scope;\n\n            var scope_token = ReadMetadataToken(CodedIndex.ResolutionScope);\n\n            var name = ReadString();\n            var @namespace = ReadString();\n\n            var type = new TypeReference(\n                @namespace,\n                name,\n                module,\n                null);\n\n            type.token = new MetadataToken(TokenType.TypeRef, rid);\n\n            metadata.AddTypeReference(type);\n\n            if (scope_token.TokenType == TokenType.TypeRef)\n            {\n                declaring_type = GetTypeDefOrRef(scope_token);\n\n                scope = declaring_type != null\n                    ? declaring_type.Scope\n                    : module;\n            }\n            else\n                scope = GetTypeReferenceScope(scope_token);\n\n            type.scope = scope;\n            type.DeclaringType = declaring_type;\n\n            MetadataSystem.TryProcessPrimitiveTypeReference(type);\n\n            return type;\n        }\n\n        IMetadataScope GetTypeReferenceScope(MetadataToken scope)\n        {\n            switch (scope.TokenType)\n            {\n                case TokenType.AssemblyRef:\n                    InitializeAssemblyReferences();\n                    return metadata.AssemblyReferences[(int)scope.RID - 1];\n                case TokenType.ModuleRef:\n                    InitializeModuleReferences();\n                    return metadata.ModuleReferences[(int)scope.RID - 1];\n                case TokenType.Module:\n                    return module;\n                default:\n                    throw new NotSupportedException();\n            }\n        }\n\n        public IEnumerable<TypeReference> GetTypeReferences()\n        {\n            InitializeTypeReferences();\n\n            var length = image.GetTableLength(Table.TypeRef);\n\n            var type_references = new TypeReference[length];\n\n            for (uint i = 1; i <= length; i++)\n                type_references[i - 1] = GetTypeReference(i);\n\n            return type_references;\n        }\n\n        TypeReference GetTypeSpecification(uint rid)\n        {\n            if (!MoveTo(Table.TypeSpec, rid))\n                return null;\n\n            var reader = ReadSignature(ReadBlobIndex());\n            var type = reader.ReadTypeSignature();\n            if (type.token.RID == 0)\n                type.token = new MetadataToken(TokenType.TypeSpec, rid);\n\n            return type;\n        }\n\n        SignatureReader ReadSignature(uint signature)\n        {\n            return new SignatureReader(signature, this);\n        }\n\n        public bool HasInterfaces(TypeDefinition type)\n        {\n            InitializeInterfaces();\n            MetadataToken[] mapping;\n\n            return metadata.TryGetInterfaceMapping(type, out mapping);\n        }\n\n        public Collection<TypeReference> ReadInterfaces(TypeDefinition type)\n        {\n            InitializeInterfaces();\n            MetadataToken[] mapping;\n\n            if (!metadata.TryGetInterfaceMapping(type, out mapping))\n                return new Collection<TypeReference>();\n\n            var interfaces = new Collection<TypeReference>(mapping.Length);\n\n            this.context = type;\n\n            for (int i = 0; i < mapping.Length; i++)\n                interfaces.Add(GetTypeDefOrRef(mapping[i]));\n\n            metadata.RemoveInterfaceMapping(type);\n\n            return interfaces;\n        }\n\n        void InitializeInterfaces()\n        {\n            if (metadata.Interfaces != null)\n                return;\n\n            int length = MoveTo(Table.InterfaceImpl);\n\n            metadata.Interfaces = new Dictionary<uint, MetadataToken[]>(length);\n\n            for (int i = 0; i < length; i++)\n            {\n                var type = ReadTableIndex(Table.TypeDef);\n                var @interface = ReadMetadataToken(CodedIndex.TypeDefOrRef);\n\n                AddInterfaceMapping(type, @interface);\n            }\n        }\n\n        void AddInterfaceMapping(uint type, MetadataToken @interface)\n        {\n            metadata.SetInterfaceMapping(type, AddMapping(metadata.Interfaces, type, @interface));\n        }\n\n        public Collection<FieldDefinition> ReadFields(TypeDefinition type)\n        {\n            var fields_range = type.fields_range;\n            if (fields_range.Length == 0)\n                return new MemberDefinitionCollection<FieldDefinition>(type);\n\n            var fields = new MemberDefinitionCollection<FieldDefinition>(type, (int)fields_range.Length);\n            this.context = type;\n\n            if (!MoveTo(Table.FieldPtr, fields_range.Start))\n            {\n                if (!MoveTo(Table.Field, fields_range.Start))\n                    return fields;\n\n                for (uint i = 0; i < fields_range.Length; i++)\n                    ReadField(fields_range.Start + i, fields);\n            }\n            else\n                ReadPointers(Table.FieldPtr, Table.Field, fields_range, fields, ReadField);\n\n            return fields;\n        }\n\n        void ReadField(uint field_rid, Collection<FieldDefinition> fields)\n        {\n            var attributes = (FieldAttributes)ReadUInt16();\n            var name = ReadString();\n            var signature = ReadBlobIndex();\n\n            var field = new FieldDefinition(name, attributes, ReadFieldType(signature));\n            field.token = new MetadataToken(TokenType.Field, field_rid);\n            metadata.AddFieldDefinition(field);\n\n            if (IsDeleted(field))\n                return;\n\n            fields.Add(field);\n        }\n\n        void InitializeFields()\n        {\n            if (metadata.Fields != null)\n                return;\n\n            metadata.Fields = new FieldDefinition[image.GetTableLength(Table.Field)];\n        }\n\n        TypeReference ReadFieldType(uint signature)\n        {\n            var reader = ReadSignature(signature);\n\n            const byte field_sig = 0x6;\n\n            if (reader.ReadByte() != field_sig)\n                throw new NotSupportedException();\n\n            return reader.ReadTypeSignature();\n        }\n\n        public int ReadFieldRVA(FieldDefinition field)\n        {\n            InitializeFieldRVAs();\n            var rid = field.token.RID;\n\n            RVA rva;\n            if (!metadata.FieldRVAs.TryGetValue(rid, out rva))\n                return 0;\n\n            var size = GetFieldTypeSize(field.FieldType);\n\n            if (size == 0 || rva == 0)\n                return 0;\n\n            metadata.FieldRVAs.Remove(rid);\n\n            field.InitialValue = GetFieldInitializeValue(size, rva);\n\n            return (int)rva;\n        }\n\n        byte[] GetFieldInitializeValue(int size, RVA rva)\n        {\n            var section = image.GetSectionAtVirtualAddress(rva);\n            if (section == null)\n                return Empty<byte>.Array;\n\n            var value = new byte[size];\n            Buffer.BlockCopy(section.Data, (int)(rva - section.VirtualAddress), value, 0, size);\n            return value;\n        }\n\n        static int GetFieldTypeSize(TypeReference type)\n        {\n            int size = 0;\n\n            switch (type.etype)\n            {\n                case ElementType.Boolean:\n                case ElementType.U1:\n                case ElementType.I1:\n                    size = 1;\n                    break;\n                case ElementType.U2:\n                case ElementType.I2:\n                case ElementType.Char:\n                    size = 2;\n                    break;\n                case ElementType.U4:\n                case ElementType.I4:\n                case ElementType.R4:\n                    size = 4;\n                    break;\n                case ElementType.U8:\n                case ElementType.I8:\n                case ElementType.R8:\n                    size = 8;\n                    break;\n                case ElementType.Ptr:\n                case ElementType.FnPtr:\n                    size = IntPtr.Size;\n                    break;\n                case ElementType.CModOpt:\n                case ElementType.CModReqD:\n                    return GetFieldTypeSize(((IModifierType)type).ElementType);\n                default:\n                    var field_type = Mixin.CheckedResolve(type);\n                    if (field_type.HasLayoutInfo)\n                        size = field_type.ClassSize;\n\n                    break;\n            }\n\n            return size;\n        }\n\n        void InitializeFieldRVAs()\n        {\n            if (metadata.FieldRVAs != null)\n                return;\n\n            int length = MoveTo(Table.FieldRVA);\n\n            var field_rvas = metadata.FieldRVAs = new Dictionary<uint, uint>(length);\n\n            for (int i = 0; i < length; i++)\n            {\n                var rva = ReadUInt32();\n                var field = ReadTableIndex(Table.Field);\n\n                field_rvas.Add(field, rva);\n            }\n        }\n\n        public int ReadFieldLayout(FieldDefinition field)\n        {\n            InitializeFieldLayouts();\n            var rid = field.token.RID;\n            uint offset;\n            if (!metadata.FieldLayouts.TryGetValue(rid, out offset))\n                return Mixin.NoDataMarker;\n\n            metadata.FieldLayouts.Remove(rid);\n\n            return (int)offset;\n        }\n\n        void InitializeFieldLayouts()\n        {\n            if (metadata.FieldLayouts != null)\n                return;\n\n            int length = MoveTo(Table.FieldLayout);\n\n            var field_layouts = metadata.FieldLayouts = new Dictionary<uint, uint>(length);\n\n            for (int i = 0; i < length; i++)\n            {\n                var offset = ReadUInt32();\n                var field = ReadTableIndex(Table.Field);\n\n                field_layouts.Add(field, offset);\n            }\n        }\n\n        public bool HasEvents(TypeDefinition type)\n        {\n            InitializeEvents();\n\n            Range range;\n            if (!metadata.TryGetEventsRange(type, out range))\n                return false;\n\n            return range.Length > 0;\n        }\n\n        public Collection<EventDefinition> ReadEvents(TypeDefinition type)\n        {\n            InitializeEvents();\n            Range range;\n\n            if (!metadata.TryGetEventsRange(type, out range))\n                return new MemberDefinitionCollection<EventDefinition>(type);\n\n            var events = new MemberDefinitionCollection<EventDefinition>(type, (int)range.Length);\n\n            metadata.RemoveEventsRange(type);\n\n            if (range.Length == 0)\n                return events;\n\n            this.context = type;\n\n            if (!MoveTo(Table.EventPtr, range.Start))\n            {\n                if (!MoveTo(Table.Event, range.Start))\n                    return events;\n\n                for (uint i = 0; i < range.Length; i++)\n                    ReadEvent(range.Start + i, events);\n            }\n            else\n                ReadPointers(Table.EventPtr, Table.Event, range, events, ReadEvent);\n\n            return events;\n        }\n\n        void ReadEvent(uint event_rid, Collection<EventDefinition> events)\n        {\n            var attributes = (EventAttributes)ReadUInt16();\n            var name = ReadString();\n            var event_type = GetTypeDefOrRef(ReadMetadataToken(CodedIndex.TypeDefOrRef));\n\n            var @event = new EventDefinition(name, attributes, event_type);\n            @event.token = new MetadataToken(TokenType.Event, event_rid);\n\n            if (IsDeleted(@event))\n                return;\n\n            events.Add(@event);\n        }\n\n        void InitializeEvents()\n        {\n            if (metadata.Events != null)\n                return;\n\n            int length = MoveTo(Table.EventMap);\n\n            metadata.Events = new Dictionary<uint, Range>(length);\n\n            for (uint i = 1; i <= length; i++)\n            {\n                var type_rid = ReadTableIndex(Table.TypeDef);\n                Range events_range = ReadEventsRange(i);\n                metadata.AddEventsRange(type_rid, events_range);\n            }\n        }\n\n        Range ReadEventsRange(uint rid)\n        {\n            return ReadListRange(rid, Table.EventMap, Table.Event);\n        }\n\n        public bool HasProperties(TypeDefinition type)\n        {\n            InitializeProperties();\n\n            Range range;\n            if (!metadata.TryGetPropertiesRange(type, out range))\n                return false;\n\n            return range.Length > 0;\n        }\n\n        public Collection<PropertyDefinition> ReadProperties(TypeDefinition type)\n        {\n            InitializeProperties();\n\n            Range range;\n\n            if (!metadata.TryGetPropertiesRange(type, out range))\n                return new MemberDefinitionCollection<PropertyDefinition>(type);\n\n            metadata.RemovePropertiesRange(type);\n\n            var properties = new MemberDefinitionCollection<PropertyDefinition>(type, (int)range.Length);\n\n            if (range.Length == 0)\n                return properties;\n\n            this.context = type;\n\n            if (!MoveTo(Table.PropertyPtr, range.Start))\n            {\n                if (!MoveTo(Table.Property, range.Start))\n                    return properties;\n                for (uint i = 0; i < range.Length; i++)\n                    ReadProperty(range.Start + i, properties);\n            }\n            else\n                ReadPointers(Table.PropertyPtr, Table.Property, range, properties, ReadProperty);\n\n            return properties;\n        }\n\n        void ReadProperty(uint property_rid, Collection<PropertyDefinition> properties)\n        {\n            var attributes = (PropertyAttributes)ReadUInt16();\n            var name = ReadString();\n            var signature = ReadBlobIndex();\n\n            var reader = ReadSignature(signature);\n            const byte property_signature = 0x8;\n\n            var calling_convention = reader.ReadByte();\n\n            if ((calling_convention & property_signature) == 0)\n                throw new NotSupportedException();\n\n            var has_this = (calling_convention & 0x20) != 0;\n\n            reader.ReadCompressedUInt32(); // count\n\n            var property = new PropertyDefinition(name, attributes, reader.ReadTypeSignature());\n            property.HasThis = has_this;\n            property.token = new MetadataToken(TokenType.Property, property_rid);\n\n            if (IsDeleted(property))\n                return;\n\n            properties.Add(property);\n        }\n\n        void InitializeProperties()\n        {\n            if (metadata.Properties != null)\n                return;\n\n            int length = MoveTo(Table.PropertyMap);\n\n            metadata.Properties = new Dictionary<uint, Range>(length);\n\n            for (uint i = 1; i <= length; i++)\n            {\n                var type_rid = ReadTableIndex(Table.TypeDef);\n                var properties_range = ReadPropertiesRange(i);\n                metadata.AddPropertiesRange(type_rid, properties_range);\n            }\n        }\n\n        Range ReadPropertiesRange(uint rid)\n        {\n            return ReadListRange(rid, Table.PropertyMap, Table.Property);\n        }\n\n        MethodSemanticsAttributes ReadMethodSemantics(MethodDefinition method)\n        {\n            InitializeMethodSemantics();\n            Row<MethodSemanticsAttributes, MetadataToken> row;\n            if (!metadata.Semantics.TryGetValue(method.token.RID, out row))\n                return MethodSemanticsAttributes.None;\n\n            var type = method.DeclaringType;\n\n            switch (row.Col1)\n            {\n                case MethodSemanticsAttributes.AddOn:\n                    GetEvent(type, row.Col2).add_method = method;\n                    break;\n                case MethodSemanticsAttributes.Fire:\n                    GetEvent(type, row.Col2).invoke_method = method;\n                    break;\n                case MethodSemanticsAttributes.RemoveOn:\n                    GetEvent(type, row.Col2).remove_method = method;\n                    break;\n                case MethodSemanticsAttributes.Getter:\n                    GetProperty(type, row.Col2).get_method = method;\n                    break;\n                case MethodSemanticsAttributes.Setter:\n                    GetProperty(type, row.Col2).set_method = method;\n                    break;\n                case MethodSemanticsAttributes.Other:\n                    switch (row.Col2.TokenType)\n                    {\n                        case TokenType.Event:\n                            {\n                                var @event = GetEvent(type, row.Col2);\n                                if (@event.other_methods == null)\n                                    @event.other_methods = new Collection<MethodDefinition>();\n\n                                @event.other_methods.Add(method);\n                                break;\n                            }\n                        case TokenType.Property:\n                            {\n                                var property = GetProperty(type, row.Col2);\n                                if (property.other_methods == null)\n                                    property.other_methods = new Collection<MethodDefinition>();\n\n                                property.other_methods.Add(method);\n\n                                break;\n                            }\n                        default:\n                            throw new NotSupportedException();\n                    }\n                    break;\n                default:\n                    throw new NotSupportedException();\n            }\n\n            metadata.Semantics.Remove(method.token.RID);\n\n            return row.Col1;\n        }\n\n        static EventDefinition GetEvent(TypeDefinition type, MetadataToken token)\n        {\n            if (token.TokenType != TokenType.Event)\n                throw new ArgumentException();\n\n            return GetMember(type.Events, token);\n        }\n\n        static PropertyDefinition GetProperty(TypeDefinition type, MetadataToken token)\n        {\n            if (token.TokenType != TokenType.Property)\n                throw new ArgumentException();\n\n            return GetMember(type.Properties, token);\n        }\n\n        static TMember GetMember<TMember>(Collection<TMember> members, MetadataToken token) where TMember : IMemberDefinition\n        {\n            for (int i = 0; i < members.Count; i++)\n            {\n                var member = members[i];\n                if (member.MetadataToken == token)\n                    return member;\n            }\n\n            throw new ArgumentException();\n        }\n\n        void InitializeMethodSemantics()\n        {\n            if (metadata.Semantics != null)\n                return;\n\n            int length = MoveTo(Table.MethodSemantics);\n\n            var semantics = metadata.Semantics = new Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>>(0);\n\n            for (uint i = 0; i < length; i++)\n            {\n                var attributes = (MethodSemanticsAttributes)ReadUInt16();\n                var method_rid = ReadTableIndex(Table.Method);\n                var association = ReadMetadataToken(CodedIndex.HasSemantics);\n\n                semantics[method_rid] = new Row<MethodSemanticsAttributes, MetadataToken>(attributes, association);\n            }\n        }\n\n        public PropertyDefinition ReadMethods(PropertyDefinition property)\n        {\n            ReadAllSemantics(property.DeclaringType);\n            return property;\n        }\n\n        public EventDefinition ReadMethods(EventDefinition @event)\n        {\n            ReadAllSemantics(@event.DeclaringType);\n            return @event;\n        }\n\n        public MethodSemanticsAttributes ReadAllSemantics(MethodDefinition method)\n        {\n            ReadAllSemantics(method.DeclaringType);\n\n            return method.SemanticsAttributes;\n        }\n\n        void ReadAllSemantics(TypeDefinition type)\n        {\n            var methods = type.Methods;\n            for (int i = 0; i < methods.Count; i++)\n            {\n                var method = methods[i];\n                if (method.sem_attrs_ready)\n                    continue;\n\n                method.sem_attrs = ReadMethodSemantics(method);\n                method.sem_attrs_ready = true;\n            }\n        }\n\n        Range ReadParametersRange(uint method_rid)\n        {\n            return ReadListRange(method_rid, Table.Method, Table.Param);\n        }\n\n        public Collection<MethodDefinition> ReadMethods(TypeDefinition type)\n        {\n            var methods_range = type.methods_range;\n            if (methods_range.Length == 0)\n                return new MemberDefinitionCollection<MethodDefinition>(type);\n\n            var methods = new MemberDefinitionCollection<MethodDefinition>(type, (int)methods_range.Length);\n            if (!MoveTo(Table.MethodPtr, methods_range.Start))\n            {\n                if (!MoveTo(Table.Method, methods_range.Start))\n                    return methods;\n\n                for (uint i = 0; i < methods_range.Length; i++)\n                    ReadMethod(methods_range.Start + i, methods);\n            }\n            else\n                ReadPointers(Table.MethodPtr, Table.Method, methods_range, methods, ReadMethod);\n\n            return methods;\n        }\n\n        void ReadPointers<TMember>(Table ptr, Table table, Range range, Collection<TMember> members, Action<uint, Collection<TMember>> reader)\n            where TMember : IMemberDefinition\n        {\n            for (uint i = 0; i < range.Length; i++)\n            {\n                MoveTo(ptr, range.Start + i);\n\n                var rid = ReadTableIndex(table);\n                MoveTo(table, rid);\n\n                reader(rid, members);\n            }\n        }\n\n        static bool IsDeleted(IMemberDefinition member)\n        {\n            return member.IsSpecialName && member.Name == \"_Deleted\";\n        }\n\n        void InitializeMethods()\n        {\n            if (metadata.Methods != null)\n                return;\n\n            metadata.Methods = new MethodDefinition[image.GetTableLength(Table.Method)];\n        }\n\n        void ReadMethod(uint method_rid, Collection<MethodDefinition> methods)\n        {\n            var method = new MethodDefinition();\n            method.rva = ReadUInt32();\n            method.ImplAttributes = (MethodImplAttributes)ReadUInt16();\n            method.Attributes = (MethodAttributes)ReadUInt16();\n            method.Name = ReadString();\n            method.token = new MetadataToken(TokenType.Method, method_rid);\n\n            if (IsDeleted(method))\n                return;\n\n            methods.Add(method); // attach method\n\n            var signature = ReadBlobIndex();\n            var param_range = ReadParametersRange(method_rid);\n\n            this.context = method;\n\n            ReadMethodSignature(signature, method);\n            metadata.AddMethodDefinition(method);\n\n            if (param_range.Length == 0)\n                return;\n\n            var position = base.position;\n            ReadParameters(method, param_range);\n            base.position = position;\n        }\n\n        void ReadParameters(MethodDefinition method, Range param_range)\n        {\n            if (!MoveTo(Table.ParamPtr, param_range.Start))\n            {\n                if (!MoveTo(Table.Param, param_range.Start))\n                    return;\n\n                for (uint i = 0; i < param_range.Length; i++)\n                    ReadParameter(param_range.Start + i, method);\n            }\n            else\n                ReadParameterPointers(method, param_range);\n        }\n\n        void ReadParameterPointers(MethodDefinition method, Range range)\n        {\n            for (uint i = 0; i < range.Length; i++)\n            {\n                MoveTo(Table.ParamPtr, range.Start + i);\n\n                var rid = ReadTableIndex(Table.Param);\n\n                MoveTo(Table.Param, rid);\n\n                ReadParameter(rid, method);\n            }\n        }\n\n        void ReadParameter(uint param_rid, MethodDefinition method)\n        {\n            var attributes = (ParameterAttributes)ReadUInt16();\n            var sequence = ReadUInt16();\n            var name = ReadString();\n\n            var parameter = sequence == 0\n                ? method.MethodReturnType.Parameter\n                : method.Parameters[sequence - 1];\n\n            parameter.token = new MetadataToken(TokenType.Param, param_rid);\n            parameter.Name = name;\n            parameter.Attributes = attributes;\n        }\n\n        void ReadMethodSignature(uint signature, IMethodSignature method)\n        {\n            var reader = ReadSignature(signature);\n            reader.ReadMethodSignature(method);\n        }\n\n        public PInvokeInfo ReadPInvokeInfo(MethodDefinition method)\n        {\n            InitializePInvokes();\n            Row<PInvokeAttributes, uint, uint> row;\n\n            var rid = method.token.RID;\n\n            if (!metadata.PInvokes.TryGetValue(rid, out row))\n                return null;\n\n            metadata.PInvokes.Remove(rid);\n\n            return new PInvokeInfo(\n                row.Col1,\n                image.StringHeap.Read(row.Col2),\n                module.ModuleReferences[(int)row.Col3 - 1]);\n        }\n\n        void InitializePInvokes()\n        {\n            if (metadata.PInvokes != null)\n                return;\n\n            int length = MoveTo(Table.ImplMap);\n\n            var pinvokes = metadata.PInvokes = new Dictionary<uint, Row<PInvokeAttributes, uint, uint>>(length);\n\n            for (int i = 1; i <= length; i++)\n            {\n                var attributes = (PInvokeAttributes)ReadUInt16();\n                var method = ReadMetadataToken(CodedIndex.MemberForwarded);\n                var name = ReadStringIndex();\n                var scope = ReadTableIndex(Table.File);\n\n                if (method.TokenType != TokenType.Method)\n                    continue;\n\n                pinvokes.Add(method.RID, new Row<PInvokeAttributes, uint, uint>(attributes, name, scope));\n            }\n        }\n\n        public bool HasGenericParameters(IGenericParameterProvider provider)\n        {\n            InitializeGenericParameters();\n\n            Range range;\n            if (!metadata.TryGetGenericParameterRange(provider, out range))\n                return false;\n\n            return range.Length > 0;\n        }\n\n        public Collection<GenericParameter> ReadGenericParameters(IGenericParameterProvider provider)\n        {\n            InitializeGenericParameters();\n\n            Range range;\n            if (!metadata.TryGetGenericParameterRange(provider, out range)\n                || !MoveTo(Table.GenericParam, range.Start))\n                return new GenericParameterCollection(provider);\n\n            metadata.RemoveGenericParameterRange(provider);\n\n            var generic_parameters = new GenericParameterCollection(provider, (int)range.Length);\n\n            for (uint i = 0; i < range.Length; i++)\n            {\n                ReadUInt16(); // index\n                var flags = (GenericParameterAttributes)ReadUInt16();\n                ReadMetadataToken(CodedIndex.TypeOrMethodDef);\n                var name = ReadString();\n\n                var parameter = new GenericParameter(name, provider);\n                parameter.token = new MetadataToken(TokenType.GenericParam, range.Start + i);\n                parameter.Attributes = flags;\n\n                generic_parameters.Add(parameter);\n            }\n\n            return generic_parameters;\n        }\n\n        void InitializeGenericParameters()\n        {\n            if (metadata.GenericParameters != null)\n                return;\n\n            metadata.GenericParameters = InitializeRanges(\n                Table.GenericParam, () =>\n                {\n                    Advance(4);\n                    var next = ReadMetadataToken(CodedIndex.TypeOrMethodDef);\n                    ReadStringIndex();\n                    return next;\n                });\n        }\n\n        Dictionary<MetadataToken, Range> InitializeRanges(Table table, Func<MetadataToken> get_next)\n        {\n            int length = MoveTo(table);\n            var ranges = new Dictionary<MetadataToken, Range>(length);\n\n            if (length == 0)\n                return ranges;\n\n            MetadataToken owner = MetadataToken.Zero;\n            Range range = new Range(1, 0);\n\n            for (uint i = 1; i <= length; i++)\n            {\n                var next = get_next();\n\n                if (i == 1)\n                {\n                    owner = next;\n                    range.Length++;\n                }\n                else if (next != owner)\n                {\n                    if (owner.RID != 0)\n                        ranges.Add(owner, range);\n                    range = new Range(i, 1);\n                    owner = next;\n                }\n                else\n                    range.Length++;\n            }\n\n            if (owner != MetadataToken.Zero && !ranges.ContainsKey(owner))\n                ranges.Add(owner, range);\n\n            return ranges;\n        }\n\n        public bool HasGenericConstraints(GenericParameter generic_parameter)\n        {\n            InitializeGenericConstraints();\n\n            MetadataToken[] mapping;\n            if (!metadata.TryGetGenericConstraintMapping(generic_parameter, out mapping))\n                return false;\n\n            return mapping.Length > 0;\n        }\n\n        public Collection<TypeReference> ReadGenericConstraints(GenericParameter generic_parameter)\n        {\n            InitializeGenericConstraints();\n\n            MetadataToken[] mapping;\n            if (!metadata.TryGetGenericConstraintMapping(generic_parameter, out mapping))\n                return new Collection<TypeReference>();\n\n            var constraints = new Collection<TypeReference>(mapping.Length);\n\n            this.context = (IGenericContext)generic_parameter.Owner;\n\n            for (int i = 0; i < mapping.Length; i++)\n                constraints.Add(GetTypeDefOrRef(mapping[i]));\n\n            metadata.RemoveGenericConstraintMapping(generic_parameter);\n\n            return constraints;\n        }\n\n        void InitializeGenericConstraints()\n        {\n            if (metadata.GenericConstraints != null)\n                return;\n\n            var length = MoveTo(Table.GenericParamConstraint);\n\n            metadata.GenericConstraints = new Dictionary<uint, MetadataToken[]>(length);\n\n            for (int i = 1; i <= length; i++)\n                AddGenericConstraintMapping(\n                    ReadTableIndex(Table.GenericParam),\n                    ReadMetadataToken(CodedIndex.TypeDefOrRef));\n        }\n\n        void AddGenericConstraintMapping(uint generic_parameter, MetadataToken constraint)\n        {\n            metadata.SetGenericConstraintMapping(\n                generic_parameter,\n                AddMapping(metadata.GenericConstraints, generic_parameter, constraint));\n        }\n\n        public bool HasOverrides(MethodDefinition method)\n        {\n            InitializeOverrides();\n            MetadataToken[] mapping;\n\n            if (!metadata.TryGetOverrideMapping(method, out mapping))\n                return false;\n\n            return mapping.Length > 0;\n        }\n\n        public Collection<MethodReference> ReadOverrides(MethodDefinition method)\n        {\n            InitializeOverrides();\n\n            MetadataToken[] mapping;\n            if (!metadata.TryGetOverrideMapping(method, out mapping))\n                return new Collection<MethodReference>();\n\n            var overrides = new Collection<MethodReference>(mapping.Length);\n\n            this.context = method;\n\n            for (int i = 0; i < mapping.Length; i++)\n                overrides.Add((MethodReference)LookupToken(mapping[i]));\n\n            metadata.RemoveOverrideMapping(method);\n\n            return overrides;\n        }\n\n        void InitializeOverrides()\n        {\n            if (metadata.Overrides != null)\n                return;\n\n            var length = MoveTo(Table.MethodImpl);\n\n            metadata.Overrides = new Dictionary<uint, MetadataToken[]>(length);\n\n            for (int i = 1; i <= length; i++)\n            {\n                ReadTableIndex(Table.TypeDef);\n\n                var method = ReadMetadataToken(CodedIndex.MethodDefOrRef);\n                if (method.TokenType != TokenType.Method)\n                    throw new NotSupportedException();\n\n                var @override = ReadMetadataToken(CodedIndex.MethodDefOrRef);\n\n                AddOverrideMapping(method.RID, @override);\n            }\n        }\n\n        void AddOverrideMapping(uint method_rid, MetadataToken @override)\n        {\n            metadata.SetOverrideMapping(\n                method_rid,\n                AddMapping(metadata.Overrides, method_rid, @override));\n        }\n\n        public MethodBody ReadMethodBody(MethodDefinition method)\n        {\n            return code.ReadMethodBody(method);\n        }\n\n        public CallSite ReadCallSite(MetadataToken token)\n        {\n            if (!MoveTo(Table.StandAloneSig, token.RID))\n                return null;\n\n            var signature = ReadBlobIndex();\n\n            var call_site = new CallSite();\n\n            ReadMethodSignature(signature, call_site);\n\n            call_site.MetadataToken = token;\n\n            return call_site;\n        }\n\n        public VariableDefinitionCollection ReadVariables(MetadataToken local_var_token)\n        {\n            if (!MoveTo(Table.StandAloneSig, local_var_token.RID))\n                return null;\n\n            var reader = ReadSignature(ReadBlobIndex());\n            const byte local_sig = 0x7;\n\n            if (reader.ReadByte() != local_sig)\n                throw new NotSupportedException();\n\n            var count = reader.ReadCompressedUInt32();\n            if (count == 0)\n                return null;\n\n            var variables = new VariableDefinitionCollection((int)count);\n\n            for (int i = 0; i < count; i++)\n                variables.Add(new VariableDefinition(reader.ReadTypeSignature()));\n\n            return variables;\n        }\n\n        public IMetadataTokenProvider LookupToken(MetadataToken token)\n        {\n            var rid = token.RID;\n\n            if (rid == 0)\n                return null;\n\n            IMetadataTokenProvider element;\n            var position = this.position;\n            var context = this.context;\n\n            switch (token.TokenType)\n            {\n                case TokenType.TypeDef:\n                    element = GetTypeDefinition(rid);\n                    break;\n                case TokenType.TypeRef:\n                    element = GetTypeReference(rid);\n                    break;\n                case TokenType.TypeSpec:\n                    element = GetTypeSpecification(rid);\n                    break;\n                case TokenType.Field:\n                    element = GetFieldDefinition(rid);\n                    break;\n                case TokenType.Method:\n                    element = GetMethodDefinition(rid);\n                    break;\n                case TokenType.MemberRef:\n                    element = GetMemberReference(rid);\n                    break;\n                case TokenType.MethodSpec:\n                    element = GetMethodSpecification(rid);\n                    break;\n                default:\n                    return null;\n            }\n\n            this.position = position;\n            this.context = context;\n\n            return element;\n        }\n\n        public FieldDefinition GetFieldDefinition(uint rid)\n        {\n            InitializeTypeDefinitions();\n\n            var field = metadata.GetFieldDefinition(rid);\n            if (field != null)\n                return field;\n\n            return LookupField(rid);\n        }\n\n        FieldDefinition LookupField(uint rid)\n        {\n            var type = metadata.GetFieldDeclaringType(rid);\n            if (type == null)\n                return null;\n\n            InitializeCollection(type.Fields);\n\n            return metadata.GetFieldDefinition(rid);\n        }\n\n        public MethodDefinition GetMethodDefinition(uint rid)\n        {\n            InitializeTypeDefinitions();\n\n            var method = metadata.GetMethodDefinition(rid);\n            if (method != null)\n                return method;\n\n            return LookupMethod(rid);\n        }\n\n        MethodDefinition LookupMethod(uint rid)\n        {\n            var type = metadata.GetMethodDeclaringType(rid);\n            if (type == null)\n                return null;\n\n            InitializeCollection(type.Methods);\n\n            return metadata.GetMethodDefinition(rid);\n        }\n\n        MethodSpecification GetMethodSpecification(uint rid)\n        {\n            if (!MoveTo(Table.MethodSpec, rid))\n                return null;\n\n            var element_method = (MethodReference)LookupToken(\n                ReadMetadataToken(CodedIndex.MethodDefOrRef));\n            var signature = ReadBlobIndex();\n\n            var method_spec = ReadMethodSpecSignature(signature, element_method);\n            method_spec.token = new MetadataToken(TokenType.MethodSpec, rid);\n            return method_spec;\n        }\n\n        MethodSpecification ReadMethodSpecSignature(uint signature, MethodReference method)\n        {\n            var reader = ReadSignature(signature);\n            const byte methodspec_sig = 0x0a;\n\n            var call_conv = reader.ReadByte();\n\n            if (call_conv != methodspec_sig)\n                throw new NotSupportedException();\n\n            var instance = new GenericInstanceMethod(method);\n\n            reader.ReadGenericInstanceSignature(method, instance);\n\n            return instance;\n        }\n\n        MemberReference GetMemberReference(uint rid)\n        {\n            InitializeMemberReferences();\n\n            var member = metadata.GetMemberReference(rid);\n            if (member != null)\n                return member;\n\n            member = ReadMemberReference(rid);\n            if (member != null && !member.ContainsGenericParameter)\n                metadata.AddMemberReference(member);\n            return member;\n        }\n\n        MemberReference ReadMemberReference(uint rid)\n        {\n            if (!MoveTo(Table.MemberRef, rid))\n                return null;\n\n            var token = ReadMetadataToken(CodedIndex.MemberRefParent);\n            var name = ReadString();\n            var signature = ReadBlobIndex();\n\n            MemberReference member;\n\n            switch (token.TokenType)\n            {\n                case TokenType.TypeDef:\n                case TokenType.TypeRef:\n                case TokenType.TypeSpec:\n                    member = ReadTypeMemberReference(token, name, signature);\n                    break;\n                case TokenType.Method:\n                    member = ReadMethodMemberReference(token, name, signature);\n                    break;\n                default:\n                    throw new NotSupportedException();\n            }\n\n            member.token = new MetadataToken(TokenType.MemberRef, rid);\n\n            return member;\n        }\n\n        MemberReference ReadTypeMemberReference(MetadataToken type, string name, uint signature)\n        {\n            var declaring_type = GetTypeDefOrRef(type);\n\n            if (!declaring_type.IsArray)\n                this.context = declaring_type;\n\n            var member = ReadMemberReferenceSignature(signature, declaring_type);\n            member.Name = name;\n\n            return member;\n        }\n\n        MemberReference ReadMemberReferenceSignature(uint signature, TypeReference declaring_type)\n        {\n            var reader = ReadSignature(signature);\n            const byte field_sig = 0x6;\n\n            if (reader.buffer[reader.position] == field_sig)\n            {\n                reader.position++;\n                var field = new FieldReference();\n                field.DeclaringType = declaring_type;\n                field.FieldType = reader.ReadTypeSignature();\n                return field;\n            }\n            else\n            {\n                var method = new MethodReference();\n                method.DeclaringType = declaring_type;\n                reader.ReadMethodSignature(method);\n                return method;\n            }\n        }\n\n        MemberReference ReadMethodMemberReference(MetadataToken token, string name, uint signature)\n        {\n            var method = GetMethodDefinition(token.RID);\n\n            this.context = method;\n\n            var member = ReadMemberReferenceSignature(signature, method.DeclaringType);\n            member.Name = name;\n\n            return member;\n        }\n\n        void InitializeMemberReferences()\n        {\n            if (metadata.MemberReferences != null)\n                return;\n\n            metadata.MemberReferences = new MemberReference[image.GetTableLength(Table.MemberRef)];\n        }\n\n        public IEnumerable<MemberReference> GetMemberReferences()\n        {\n            InitializeMemberReferences();\n\n            var length = image.GetTableLength(Table.MemberRef);\n\n            var type_system = module.TypeSystem;\n\n            var context = new MethodReference(string.Empty, type_system.Void);\n            context.DeclaringType = new TypeReference(string.Empty, string.Empty, module, type_system.Corlib);\n\n            var member_references = new MemberReference[length];\n\n            for (uint i = 1; i <= length; i++)\n            {\n                this.context = context;\n                member_references[i - 1] = GetMemberReference(i);\n            }\n\n            return member_references;\n        }\n\n        void InitializeConstants()\n        {\n            if (metadata.Constants != null)\n                return;\n\n            var length = MoveTo(Table.Constant);\n\n            var constants = metadata.Constants = new Dictionary<MetadataToken, Row<ElementType, uint>>(length);\n\n            for (uint i = 1; i <= length; i++)\n            {\n                var type = (ElementType)ReadUInt16();\n                var owner = ReadMetadataToken(CodedIndex.HasConstant);\n                var signature = ReadBlobIndex();\n\n                constants.Add(owner, new Row<ElementType, uint>(type, signature));\n            }\n        }\n\n        public object ReadConstant(IConstantProvider owner)\n        {\n            InitializeConstants();\n\n            Row<ElementType, uint> row;\n            if (!metadata.Constants.TryGetValue(owner.MetadataToken, out row))\n                return Mixin.NoValue;\n\n            metadata.Constants.Remove(owner.MetadataToken);\n\n            switch (row.Col1)\n            {\n                case ElementType.Class:\n                case ElementType.Object:\n                    return null;\n                case ElementType.String:\n                    return ReadConstantString(ReadBlob(row.Col2));\n                default:\n                    return ReadConstantPrimitive(row.Col1, row.Col2);\n            }\n        }\n\n        static string ReadConstantString(byte[] blob)\n        {\n            var length = blob.Length;\n            if ((length & 1) == 1)\n                length--;\n\n            return Encoding.Unicode.GetString(blob, 0, length);\n        }\n\n        object ReadConstantPrimitive(ElementType type, uint signature)\n        {\n            var reader = ReadSignature(signature);\n            return reader.ReadConstantSignature(type);\n        }\n\n        void InitializeCustomAttributes()\n        {\n            if (metadata.CustomAttributes != null)\n                return;\n\n            metadata.CustomAttributes = InitializeRanges(\n                Table.CustomAttribute, () =>\n                {\n                    var next = ReadMetadataToken(CodedIndex.HasCustomAttribute);\n                    ReadMetadataToken(CodedIndex.CustomAttributeType);\n                    ReadBlobIndex();\n                    return next;\n                });\n        }\n\n        public bool HasCustomAttributes(ICustomAttributeProvider owner)\n        {\n            InitializeCustomAttributes();\n\n            Range range;\n            if (!metadata.TryGetCustomAttributeRange(owner, out range))\n                return false;\n\n            return range.Length > 0;\n        }\n\n        public Collection<CustomAttribute> ReadCustomAttributes(ICustomAttributeProvider owner)\n        {\n            InitializeCustomAttributes();\n\n            Range range;\n            if (!metadata.TryGetCustomAttributeRange(owner, out range)\n                || !MoveTo(Table.CustomAttribute, range.Start))\n                return new Collection<CustomAttribute>();\n\n            var custom_attributes = new Collection<CustomAttribute>((int)range.Length);\n\n            for (int i = 0; i < range.Length; i++)\n            {\n                ReadMetadataToken(CodedIndex.HasCustomAttribute);\n\n                var constructor = (MethodReference)LookupToken(\n                    ReadMetadataToken(CodedIndex.CustomAttributeType));\n\n                var signature = ReadBlobIndex();\n\n                custom_attributes.Add(new CustomAttribute(signature, constructor));\n            }\n\n            metadata.RemoveCustomAttributeRange(owner);\n\n            return custom_attributes;\n        }\n\n        public byte[] ReadCustomAttributeBlob(uint signature)\n        {\n            return ReadBlob(signature);\n        }\n\n        public void ReadCustomAttributeSignature(CustomAttribute attribute)\n        {\n            var reader = ReadSignature(attribute.signature);\n\n            if (!reader.CanReadMore())\n                return;\n\n            if (reader.ReadUInt16() != 0x0001)\n                throw new InvalidOperationException();\n\n            var constructor = attribute.Constructor;\n            if (constructor.HasParameters)\n                reader.ReadCustomAttributeConstructorArguments(attribute, constructor.Parameters);\n\n            if (!reader.CanReadMore())\n                return;\n\n            var named = reader.ReadUInt16();\n\n            if (named == 0)\n                return;\n\n            reader.ReadCustomAttributeNamedArguments(named, ref attribute.fields, ref attribute.properties);\n        }\n\n        void InitializeMarshalInfos()\n        {\n            if (metadata.FieldMarshals != null)\n                return;\n\n            var length = MoveTo(Table.FieldMarshal);\n\n            var marshals = metadata.FieldMarshals = new Dictionary<MetadataToken, uint>(length);\n\n            for (int i = 0; i < length; i++)\n            {\n                var token = ReadMetadataToken(CodedIndex.HasFieldMarshal);\n                var signature = ReadBlobIndex();\n                if (token.RID == 0)\n                    continue;\n\n                marshals.Add(token, signature);\n            }\n        }\n\n        public bool HasMarshalInfo(IMarshalInfoProvider owner)\n        {\n            InitializeMarshalInfos();\n\n            return metadata.FieldMarshals.ContainsKey(owner.MetadataToken);\n        }\n\n        public MarshalInfo ReadMarshalInfo(IMarshalInfoProvider owner)\n        {\n            InitializeMarshalInfos();\n\n            uint signature;\n            if (!metadata.FieldMarshals.TryGetValue(owner.MetadataToken, out signature))\n                return null;\n\n            var reader = ReadSignature(signature);\n\n            metadata.FieldMarshals.Remove(owner.MetadataToken);\n\n            return reader.ReadMarshalInfo();\n        }\n\n        void InitializeSecurityDeclarations()\n        {\n            if (metadata.SecurityDeclarations != null)\n                return;\n\n            metadata.SecurityDeclarations = InitializeRanges(\n                Table.DeclSecurity, () =>\n                {\n                    ReadUInt16();\n                    var next = ReadMetadataToken(CodedIndex.HasDeclSecurity);\n                    ReadBlobIndex();\n                    return next;\n                });\n        }\n\n        public bool HasSecurityDeclarations(ISecurityDeclarationProvider owner)\n        {\n            InitializeSecurityDeclarations();\n\n            Range range;\n            if (!metadata.TryGetSecurityDeclarationRange(owner, out range))\n                return false;\n\n            return range.Length > 0;\n        }\n\n        public Collection<SecurityDeclaration> ReadSecurityDeclarations(ISecurityDeclarationProvider owner)\n        {\n            InitializeSecurityDeclarations();\n\n            Range range;\n            if (!metadata.TryGetSecurityDeclarationRange(owner, out range)\n                || !MoveTo(Table.DeclSecurity, range.Start))\n                return new Collection<SecurityDeclaration>();\n\n            var security_declarations = new Collection<SecurityDeclaration>((int)range.Length);\n\n            for (int i = 0; i < range.Length; i++)\n            {\n                var action = (SecurityAction)ReadUInt16();\n                ReadMetadataToken(CodedIndex.HasDeclSecurity);\n                var signature = ReadBlobIndex();\n\n                security_declarations.Add(new SecurityDeclaration(action, signature, module));\n            }\n\n            metadata.RemoveSecurityDeclarationRange(owner);\n\n            return security_declarations;\n        }\n\n        public byte[] ReadSecurityDeclarationBlob(uint signature)\n        {\n            return ReadBlob(signature);\n        }\n\n        public void ReadSecurityDeclarationSignature(SecurityDeclaration declaration)\n        {\n            var signature = declaration.signature;\n            var reader = ReadSignature(signature);\n\n            if (reader.buffer[reader.position] != '.')\n            {\n                ReadXmlSecurityDeclaration(signature, declaration);\n                return;\n            }\n\n            reader.position++;\n            var count = reader.ReadCompressedUInt32();\n            var attributes = new Collection<SecurityAttribute>((int)count);\n\n            for (int i = 0; i < count; i++)\n                attributes.Add(reader.ReadSecurityAttribute());\n\n            declaration.security_attributes = attributes;\n        }\n\n        void ReadXmlSecurityDeclaration(uint signature, SecurityDeclaration declaration)\n        {\n            var blob = ReadBlob(signature);\n            var attributes = new Collection<SecurityAttribute>(1);\n\n            var attribute = new SecurityAttribute(\n                module.TypeSystem.LookupType(\"System.Security.Permissions\", \"PermissionSetAttribute\"));\n\n            attribute.properties = new Collection<CustomAttributeNamedArgument>(1);\n            attribute.properties.Add(\n                new CustomAttributeNamedArgument(\n                    \"XML\",\n                    new CustomAttributeArgument(\n                        module.TypeSystem.String,\n                        Encoding.Unicode.GetString(blob, 0, blob.Length))));\n\n            attributes.Add(attribute);\n\n            declaration.security_attributes = attributes;\n        }\n\n        public Collection<ExportedType> ReadExportedTypes()\n        {\n            var length = MoveTo(Table.ExportedType);\n            if (length == 0)\n                return new Collection<ExportedType>();\n\n            var exported_types = new Collection<ExportedType>(length);\n\n            for (int i = 1; i <= length; i++)\n            {\n                var attributes = (TypeAttributes)ReadUInt32();\n                var identifier = ReadUInt32();\n                var name = ReadString();\n                var @namespace = ReadString();\n                var implementation = ReadMetadataToken(CodedIndex.Implementation);\n\n                ExportedType declaring_type = null;\n                IMetadataScope scope = null;\n\n                switch (implementation.TokenType)\n                {\n                    case TokenType.AssemblyRef:\n                    case TokenType.File:\n                        scope = GetExportedTypeScope(implementation);\n                        break;\n                    case TokenType.ExportedType:\n                        // FIXME: if the table is not properly sorted\n                        declaring_type = exported_types[(int)implementation.RID - 1];\n                        break;\n                }\n\n                var exported_type = new ExportedType(@namespace, name, module, scope)\n                {\n                    Attributes = attributes,\n                    Identifier = (int)identifier,\n                    DeclaringType = declaring_type,\n                };\n                exported_type.token = new MetadataToken(TokenType.ExportedType, i);\n\n                exported_types.Add(exported_type);\n            }\n\n            return exported_types;\n        }\n\n        IMetadataScope GetExportedTypeScope(MetadataToken token)\n        {\n            var position = this.position;\n            IMetadataScope scope;\n\n            switch (token.TokenType)\n            {\n                case TokenType.AssemblyRef:\n                    InitializeAssemblyReferences();\n                    scope = metadata.AssemblyReferences[(int)token.RID - 1];\n                    break;\n                case TokenType.File:\n                    InitializeModuleReferences();\n                    scope = GetModuleReferenceFromFile(token);\n                    break;\n                default:\n                    throw new NotSupportedException();\n            }\n\n            this.position = position;\n            return scope;\n        }\n\n        ModuleReference GetModuleReferenceFromFile(MetadataToken token)\n        {\n            if (!MoveTo(Table.File, token.RID))\n                return null;\n\n            ReadUInt32();\n            var file_name = ReadString();\n            var modules = module.ModuleReferences;\n\n            ModuleReference reference;\n            for (int i = 0; i < modules.Count; i++)\n            {\n                reference = modules[i];\n                if (reference.Name == file_name)\n                    return reference;\n            }\n\n            reference = new ModuleReference(file_name);\n            modules.Add(reference);\n            return reference;\n        }\n\n        static void InitializeCollection(object o)\n        {\n        }\n    }\n\n    sealed class SignatureReader : ByteBuffer\n    {\n\n        readonly MetadataReader reader;\n        readonly uint start, sig_length;\n\n        TypeSystem TypeSystem\n        {\n            get { return reader.module.TypeSystem; }\n        }\n\n        public SignatureReader(uint blob, MetadataReader reader)\n            : base(reader.buffer)\n        {\n            this.reader = reader;\n\n            MoveToBlob(blob);\n\n            this.sig_length = ReadCompressedUInt32();\n            this.start = (uint)position;\n        }\n\n        void MoveToBlob(uint blob)\n        {\n            position = (int)(reader.image.BlobHeap.Offset + blob);\n        }\n\n        MetadataToken ReadTypeTokenSignature()\n        {\n            return Mixin.GetMetadataToken(CodedIndex.TypeDefOrRef, ReadCompressedUInt32());\n        }\n\n        GenericParameter GetGenericParameter(GenericParameterType type, uint var)\n        {\n            var context = reader.context;\n            int index = (int)var;\n\n            if (context == null)\n                return GetUnboundGenericParameter(type, index);\n\n            IGenericParameterProvider provider;\n\n            switch (type)\n            {\n                case GenericParameterType.Type:\n                    provider = context.Type;\n                    break;\n                case GenericParameterType.Method:\n                    provider = context.Method;\n                    break;\n                default:\n                    throw new NotSupportedException();\n            }\n\n            if (!context.IsDefinition)\n                CheckGenericContext(provider, index);\n\n            if (index >= provider.GenericParameters.Count)\n                return GetUnboundGenericParameter(type, index);\n\n            return provider.GenericParameters[index];\n        }\n\n        GenericParameter GetUnboundGenericParameter(GenericParameterType type, int index)\n        {\n            return new GenericParameter(index, type, reader.module);\n        }\n\n        static void CheckGenericContext(IGenericParameterProvider owner, int index)\n        {\n            var owner_parameters = owner.GenericParameters;\n\n            for (int i = owner_parameters.Count; i <= index; i++)\n                owner_parameters.Add(new GenericParameter(owner));\n        }\n\n        public void ReadGenericInstanceSignature(IGenericParameterProvider provider, IGenericInstance instance)\n        {\n            var arity = ReadCompressedUInt32();\n\n            if (!provider.IsDefinition)\n                CheckGenericContext(provider, (int)arity - 1);\n\n            var instance_arguments = instance.GenericArguments;\n\n            for (int i = 0; i < arity; i++)\n                instance_arguments.Add(ReadTypeSignature());\n        }\n\n        ArrayType ReadArrayTypeSignature()\n        {\n            var array = new ArrayType(ReadTypeSignature());\n\n            var rank = ReadCompressedUInt32();\n\n            var sizes = new uint[ReadCompressedUInt32()];\n            for (int i = 0; i < sizes.Length; i++)\n                sizes[i] = ReadCompressedUInt32();\n\n            var low_bounds = new int[ReadCompressedUInt32()];\n            for (int i = 0; i < low_bounds.Length; i++)\n                low_bounds[i] = ReadCompressedInt32();\n\n            array.Dimensions.Clear();\n\n            for (int i = 0; i < rank; i++)\n            {\n                int? lower = null, upper = null;\n\n                if (i < low_bounds.Length)\n                    lower = low_bounds[i];\n\n                if (i < sizes.Length)\n                    upper = lower + (int)sizes[i] - 1;\n\n                array.Dimensions.Add(new ArrayDimension(lower, upper));\n            }\n\n            return array;\n        }\n\n        TypeReference GetTypeDefOrRef(MetadataToken token)\n        {\n            return reader.GetTypeDefOrRef(token);\n        }\n\n        public TypeReference ReadTypeSignature()\n        {\n            return ReadTypeSignature((ElementType)ReadByte());\n        }\n\n        TypeReference ReadTypeSignature(ElementType etype)\n        {\n            switch (etype)\n            {\n                case ElementType.ValueType:\n                    {\n                        var value_type = GetTypeDefOrRef(ReadTypeTokenSignature());\n                        value_type.IsValueType = true;\n                        return value_type;\n                    }\n                case ElementType.Class:\n                    return GetTypeDefOrRef(ReadTypeTokenSignature());\n                case ElementType.Ptr:\n                    return new PointerType(ReadTypeSignature());\n                case ElementType.FnPtr:\n                    {\n                        var fptr = new FunctionPointerType();\n                        ReadMethodSignature(fptr);\n                        return fptr;\n                    }\n                case ElementType.ByRef:\n                    return new ByReferenceType(ReadTypeSignature());\n                case ElementType.Pinned:\n                    return new PinnedType(ReadTypeSignature());\n                case ElementType.SzArray:\n                    return new ArrayType(ReadTypeSignature());\n                case ElementType.Array:\n                    return ReadArrayTypeSignature();\n                case ElementType.CModOpt:\n                    return new OptionalModifierType(\n                        GetTypeDefOrRef(ReadTypeTokenSignature()), ReadTypeSignature());\n                case ElementType.CModReqD:\n                    return new RequiredModifierType(\n                        GetTypeDefOrRef(ReadTypeTokenSignature()), ReadTypeSignature());\n                case ElementType.Sentinel:\n                    return new SentinelType(ReadTypeSignature());\n                case ElementType.Var:\n                    return GetGenericParameter(GenericParameterType.Type, ReadCompressedUInt32());\n                case ElementType.MVar:\n                    return GetGenericParameter(GenericParameterType.Method, ReadCompressedUInt32());\n                case ElementType.GenericInst:\n                    {\n                        var is_value_type = ReadByte() == (byte)ElementType.ValueType;\n                        var element_type = GetTypeDefOrRef(ReadTypeTokenSignature());\n                        var generic_instance = new GenericInstanceType(element_type);\n\n                        ReadGenericInstanceSignature(element_type, generic_instance);\n\n                        if (is_value_type)\n                        {\n                            generic_instance.IsValueType = true;\n                            element_type.GetElementType().IsValueType = true;\n                        }\n\n                        return generic_instance;\n                    }\n                case ElementType.Object: return TypeSystem.Object;\n                case ElementType.Void: return TypeSystem.Void;\n                case ElementType.TypedByRef: return TypeSystem.TypedReference;\n                case ElementType.I: return TypeSystem.IntPtr;\n                case ElementType.U: return TypeSystem.UIntPtr;\n                default: return GetPrimitiveType(etype);\n            }\n        }\n\n        public void ReadMethodSignature(IMethodSignature method)\n        {\n            var calling_convention = ReadByte();\n\n            const byte has_this = 0x20;\n            const byte explicit_this = 0x40;\n\n            if ((calling_convention & has_this) != 0)\n            {\n                method.HasThis = true;\n                calling_convention = (byte)(calling_convention & ~has_this);\n            }\n\n            if ((calling_convention & explicit_this) != 0)\n            {\n                method.ExplicitThis = true;\n                calling_convention = (byte)(calling_convention & ~explicit_this);\n            }\n\n            method.CallingConvention = (MethodCallingConvention)calling_convention;\n\n            var generic_context = method as MethodReference;\n            if (generic_context != null && !generic_context.DeclaringType.IsArray)\n                reader.context = generic_context;\n\n            if ((calling_convention & 0x10) != 0)\n            {\n                var arity = ReadCompressedUInt32();\n\n                if (generic_context != null && !generic_context.IsDefinition)\n                    CheckGenericContext(generic_context, (int)arity - 1);\n            }\n\n            var param_count = ReadCompressedUInt32();\n\n            method.MethodReturnType.ReturnType = ReadTypeSignature();\n\n            if (param_count == 0)\n                return;\n\n            Collection<ParameterDefinition> parameters;\n\n            var method_ref = method as MethodReference;\n            if (method_ref != null)\n                parameters = method_ref.parameters = new ParameterDefinitionCollection(method, (int)param_count);\n            else\n                parameters = method.Parameters;\n\n            for (int i = 0; i < param_count; i++)\n                parameters.Add(new ParameterDefinition(ReadTypeSignature()));\n        }\n\n        public object ReadConstantSignature(ElementType type)\n        {\n            return ReadPrimitiveValue(type);\n        }\n\n        public void ReadCustomAttributeConstructorArguments(CustomAttribute attribute, Collection<ParameterDefinition> parameters)\n        {\n            var count = parameters.Count;\n            if (count == 0)\n                return;\n\n            attribute.arguments = new Collection<CustomAttributeArgument>(count);\n\n            for (int i = 0; i < count; i++)\n                attribute.arguments.Add(\n                    ReadCustomAttributeFixedArgument(parameters[i].ParameterType));\n        }\n\n        CustomAttributeArgument ReadCustomAttributeFixedArgument(TypeReference type)\n        {\n            if (type.IsArray)\n                return ReadCustomAttributeFixedArrayArgument((ArrayType)type);\n\n            return ReadCustomAttributeElement(type);\n        }\n\n        public void ReadCustomAttributeNamedArguments(ushort count, ref Collection<CustomAttributeNamedArgument> fields, ref Collection<CustomAttributeNamedArgument> properties)\n        {\n            for (int i = 0; i < count; i++)\n                ReadCustomAttributeNamedArgument(ref fields, ref properties);\n        }\n\n        void ReadCustomAttributeNamedArgument(ref Collection<CustomAttributeNamedArgument> fields, ref Collection<CustomAttributeNamedArgument> properties)\n        {\n            var kind = ReadByte();\n            var type = ReadCustomAttributeFieldOrPropType();\n            var name = ReadUTF8String();\n\n            Collection<CustomAttributeNamedArgument> container;\n            switch (kind)\n            {\n                case 0x53:\n                    container = GetCustomAttributeNamedArgumentCollection(ref fields);\n                    break;\n                case 0x54:\n                    container = GetCustomAttributeNamedArgumentCollection(ref properties);\n                    break;\n                default:\n                    throw new NotSupportedException();\n            }\n\n            container.Add(new CustomAttributeNamedArgument(name, ReadCustomAttributeFixedArgument(type)));\n        }\n\n        static Collection<CustomAttributeNamedArgument> GetCustomAttributeNamedArgumentCollection(ref Collection<CustomAttributeNamedArgument> collection)\n        {\n            if (collection != null)\n                return collection;\n\n            return collection = new Collection<CustomAttributeNamedArgument>();\n        }\n\n        CustomAttributeArgument ReadCustomAttributeFixedArrayArgument(ArrayType type)\n        {\n            var length = ReadUInt32();\n\n            if (length == 0xffffffff)\n                return new CustomAttributeArgument(type, null);\n\n            if (length == 0)\n                return new CustomAttributeArgument(type, Empty<CustomAttributeArgument>.Array);\n\n            var arguments = new CustomAttributeArgument[length];\n            var element_type = type.ElementType;\n\n            for (int i = 0; i < length; i++)\n                arguments[i] = ReadCustomAttributeElement(element_type);\n\n            return new CustomAttributeArgument(type, arguments);\n        }\n\n        CustomAttributeArgument ReadCustomAttributeElement(TypeReference type)\n        {\n            if (type.IsArray)\n                return ReadCustomAttributeFixedArrayArgument((ArrayType)type);\n\n            return new CustomAttributeArgument(\n                type,\n                type.etype == ElementType.Object\n                    ? ReadCustomAttributeElement(ReadCustomAttributeFieldOrPropType())\n                    : ReadCustomAttributeElementValue(type));\n        }\n\n        object ReadCustomAttributeElementValue(TypeReference type)\n        {\n            var etype = type.etype;\n\n            switch (etype)\n            {\n                case ElementType.String:\n                    return ReadUTF8String();\n                case ElementType.None:\n                    if (Mixin.IsTypeOf(type,\"System\", \"Type\"))\n                        return ReadTypeReference();\n\n                    return ReadCustomAttributeEnum(type);\n                default:\n                    return ReadPrimitiveValue(etype);\n            }\n        }\n\n        object ReadPrimitiveValue(ElementType type)\n        {\n            switch (type)\n            {\n                case ElementType.Boolean:\n                    return ReadByte() == 1;\n                case ElementType.I1:\n                    return (sbyte)ReadByte();\n                case ElementType.U1:\n                    return ReadByte();\n                case ElementType.Char:\n                    return (char)ReadUInt16();\n                case ElementType.I2:\n                    return ReadInt16();\n                case ElementType.U2:\n                    return ReadUInt16();\n                case ElementType.I4:\n                    return ReadInt32();\n                case ElementType.U4:\n                    return ReadUInt32();\n                case ElementType.I8:\n                    return ReadInt64();\n                case ElementType.U8:\n                    return ReadUInt64();\n                case ElementType.R4:\n                    return ReadSingle();\n                case ElementType.R8:\n                    return ReadDouble();\n                default:\n                    throw new NotImplementedException(type.ToString());\n            }\n        }\n\n        TypeReference GetPrimitiveType(ElementType etype)\n        {\n            switch (etype)\n            {\n                case ElementType.Boolean:\n                    return TypeSystem.Boolean;\n                case ElementType.Char:\n                    return TypeSystem.Char;\n                case ElementType.I1:\n                    return TypeSystem.SByte;\n                case ElementType.U1:\n                    return TypeSystem.Byte;\n                case ElementType.I2:\n                    return TypeSystem.Int16;\n                case ElementType.U2:\n                    return TypeSystem.UInt16;\n                case ElementType.I4:\n                    return TypeSystem.Int32;\n                case ElementType.U4:\n                    return TypeSystem.UInt32;\n                case ElementType.I8:\n                    return TypeSystem.Int64;\n                case ElementType.U8:\n                    return TypeSystem.UInt64;\n                case ElementType.R4:\n                    return TypeSystem.Single;\n                case ElementType.R8:\n                    return TypeSystem.Double;\n                case ElementType.String:\n                    return TypeSystem.String;\n                default:\n                    throw new NotImplementedException(etype.ToString());\n            }\n        }\n\n        TypeReference ReadCustomAttributeFieldOrPropType()\n        {\n            var etype = (ElementType)ReadByte();\n\n            switch (etype)\n            {\n                case ElementType.Boxed:\n                    return TypeSystem.Object;\n                case ElementType.SzArray:\n                    return new ArrayType(ReadCustomAttributeFieldOrPropType());\n                case ElementType.Enum:\n                    return ReadTypeReference();\n                case ElementType.Type:\n                    return TypeSystem.LookupType(\"System\", \"Type\");\n                default:\n                    return GetPrimitiveType(etype);\n            }\n        }\n\n        public TypeReference ReadTypeReference()\n        {\n            return TypeParser.ParseType(reader.module, ReadUTF8String());\n        }\n\n        object ReadCustomAttributeEnum(TypeReference enum_type)\n        {\n            try\n            {\n                TypeDefinition type = null;\n                type = Mixin.CheckedResolve(enum_type);\n                if (!type.IsEnum)\n                    throw new ArgumentException();\n                return ReadCustomAttributeElementValue(Mixin.GetEnumUnderlyingType(type));\n            }\n            catch\n            {\n                //Resolve failed\n                string name = enum_type.FullName + \", \" + enum_type.scope.Name;\n                Type type = Type.GetType(name);\n                if (type == null || !type.IsEnum)\n                    return new ArgumentException();\n                var fields = type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);\n                Type eType = null;\n                foreach(var i in fields)\n                {\n                    eType = i.FieldType;\n                    break;\n                }\n\n                object val;\n                if(eType == typeof(int))\n                {\n                    val = ReadPrimitiveValue(ElementType.I4);\n                }\n                else if (eType == typeof(long))\n                {\n                    val = ReadPrimitiveValue(ElementType.I8);\n                }\n                else if (eType == typeof(short))\n                {\n                    val = ReadPrimitiveValue(ElementType.I2);\n                }\n                else if (eType == typeof(byte))\n                {\n                    val = ReadPrimitiveValue(ElementType.U1);\n                }\n                else if (eType == typeof(uint))\n                {\n                    val = ReadPrimitiveValue(ElementType.U4);\n                }\n                else if (eType == typeof(ulong))\n                {\n                    val = ReadPrimitiveValue(ElementType.U8);\n                }\n                else if (eType == typeof(ushort))\n                {\n                    val = ReadPrimitiveValue(ElementType.U2);\n                }\n                else\n                {\n                    val = ReadPrimitiveValue(ElementType.Void);\n                }\n\n                return Enum.ToObject(type, val);\n            }\n            \n        }\n\n        public SecurityAttribute ReadSecurityAttribute()\n        {\n            var attribute = new SecurityAttribute(ReadTypeReference());\n\n            ReadCompressedUInt32();\n\n            ReadCustomAttributeNamedArguments(\n                (ushort)ReadCompressedUInt32(),\n                ref attribute.fields,\n                ref attribute.properties);\n\n            return attribute;\n        }\n\n        public MarshalInfo ReadMarshalInfo()\n        {\n            var native = ReadNativeType();\n            switch (native)\n            {\n                case NativeType.Array:\n                    {\n                        var array = new ArrayMarshalInfo();\n                        if (CanReadMore())\n                            array.element_type = ReadNativeType();\n                        if (CanReadMore())\n                            array.size_parameter_index = (int)ReadCompressedUInt32();\n                        if (CanReadMore())\n                            array.size = (int)ReadCompressedUInt32();\n                        if (CanReadMore())\n                            array.size_parameter_multiplier = (int)ReadCompressedUInt32();\n                        return array;\n                    }\n                case NativeType.SafeArray:\n                    {\n                        var array = new SafeArrayMarshalInfo();\n                        if (CanReadMore())\n                            array.element_type = ReadVariantType();\n                        return array;\n                    }\n                case NativeType.FixedArray:\n                    {\n                        var array = new FixedArrayMarshalInfo();\n                        if (CanReadMore())\n                            array.size = (int)ReadCompressedUInt32();\n                        if (CanReadMore())\n                            array.element_type = ReadNativeType();\n                        return array;\n                    }\n                case NativeType.FixedSysString:\n                    {\n                        var sys_string = new FixedSysStringMarshalInfo();\n                        if (CanReadMore())\n                            sys_string.size = (int)ReadCompressedUInt32();\n                        return sys_string;\n                    }\n                case NativeType.CustomMarshaler:\n                    {\n                        var marshaler = new CustomMarshalInfo();\n                        var guid_value = ReadUTF8String();\n                        marshaler.guid = !string.IsNullOrEmpty(guid_value) ? new Guid(guid_value) : Guid.Empty;\n                        marshaler.unmanaged_type = ReadUTF8String();\n                        marshaler.managed_type = ReadTypeReference();\n                        marshaler.cookie = ReadUTF8String();\n                        return marshaler;\n                    }\n                default:\n                    return new MarshalInfo(native);\n            }\n        }\n\n        NativeType ReadNativeType()\n        {\n            return (NativeType)ReadByte();\n        }\n\n        VariantType ReadVariantType()\n        {\n            return (VariantType)ReadByte();\n        }\n\n        string ReadUTF8String()\n        {\n            if (buffer[position] == 0xff)\n            {\n                position++;\n                return null;\n            }\n\n            var length = (int)ReadCompressedUInt32();\n            if (length == 0)\n                return string.Empty;\n\n            var @string = Encoding.UTF8.GetString(buffer, position,\n                buffer[position + length - 1] == 0 ? length - 1 : length);\n\n            position += length;\n            return @string;\n        }\n\n        public bool CanReadMore()\n        {\n            return position - start < sig_length;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/AssemblyWriter.cs",
    "content": "//\n// AssemblyWriter.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nusing Mono.Collections.Generic;\nusing Mono.Cecil.Cil;\nusing Mono.Cecil.Metadata;\nusing Mono.Cecil.PE;\n\nusing RVA = System.UInt32;\nusing RID = System.UInt32;\nusing CodedRID = System.UInt32;\nusing StringIndex = System.UInt32;\nusing BlobIndex = System.UInt32;\n\nnamespace Mono.Cecil {\n\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/BaseAssemblyResolver.cs",
    "content": "//\n// BaseAssemblyResolver.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic delegate AssemblyDefinition AssemblyResolveEventHandler (object sender, AssemblyNameReference reference);\n\n\tpublic sealed class AssemblyResolveEventArgs : EventArgs {\n\n\t\treadonly AssemblyNameReference reference;\n\n\t\tpublic AssemblyNameReference AssemblyReference {\n\t\t\tget { return reference; }\n\t\t}\n\n\t\tpublic AssemblyResolveEventArgs (AssemblyNameReference reference)\n\t\t{\n\t\t\tthis.reference = reference;\n\t\t}\n\t}\n\n\n\tpublic class AssemblyResolutionException : FileNotFoundException {\n\n\t\treadonly AssemblyNameReference reference;\n\n\t\tpublic AssemblyNameReference AssemblyReference {\n\t\t\tget { return reference; }\n\t\t}\n\n\t\tpublic AssemblyResolutionException (AssemblyNameReference reference)\n\t\t\t: base (string.Format (\"Failed to resolve assembly: '{0}'\", reference))\n\t\t{\n\t\t\tthis.reference = reference;\n\t\t}\n\n\n\t}\n\n\tpublic abstract class BaseAssemblyResolver : IAssemblyResolver {\n\n\t\tstatic readonly bool on_mono = Type.GetType (\"Mono.Runtime\") != null;\n\n\t\treadonly Collection<string> directories;\n\n\n\n\t\tpublic void AddSearchDirectory (string directory)\n\t\t{\n\t\t\tdirectories.Add (directory);\n\t\t}\n\n\t\tpublic void RemoveSearchDirectory (string directory)\n\t\t{\n\t\t\tdirectories.Remove (directory);\n\t\t}\n\n\t\tpublic string [] GetSearchDirectories ()\n\t\t{\n\t\t\tvar directories = new string [this.directories.size];\n\t\t\tArray.Copy (this.directories.items, directories, directories.Length);\n\t\t\treturn directories;\n\t\t}\n\n\t\tpublic virtual AssemblyDefinition Resolve (string fullName)\n\t\t{\n\t\t\treturn Resolve (fullName, new ReaderParameters ());\n\t\t}\n\n\t\tpublic virtual AssemblyDefinition Resolve (string fullName, ReaderParameters parameters)\n\t\t{\n\t\t\tif (fullName == null)\n\t\t\t\tthrow new ArgumentNullException (\"fullName\");\n\n\t\t\treturn Resolve (AssemblyNameReference.Parse (fullName), parameters);\n\t\t}\n\n\t\tpublic event AssemblyResolveEventHandler ResolveFailure;\n\n\t\tprotected BaseAssemblyResolver ()\n\t\t{\n\t\t\tdirectories = new Collection<string> (2) { \".\", \"bin\" };\n\t\t}\n\n\t\tAssemblyDefinition GetAssembly (string file, ReaderParameters parameters)\n\t\t{\n\t\t\tif (parameters.AssemblyResolver == null)\n\t\t\t\tparameters.AssemblyResolver = this;\n\n\t\t\treturn ModuleDefinition.ReadModule (file, parameters).Assembly;\n\t\t}\n\n\t\tpublic virtual AssemblyDefinition Resolve (AssemblyNameReference name)\n\t\t{\n\t\t\treturn Resolve (name, new ReaderParameters ());\n\t\t}\n\n\t\tpublic virtual AssemblyDefinition Resolve (AssemblyNameReference name, ReaderParameters parameters)\n\t\t{\n\t\t\tif (name == null)\n\t\t\t\tthrow new ArgumentNullException (\"name\");\n            if (parameters == null)\n\t\t\t\tparameters = new ReaderParameters ();\n\n\t\t\tvar assembly = SearchDirectory (name, directories, parameters);\n\t\t\tif (assembly != null)\n\t\t\t\treturn assembly;\n\n\n\n\t\t\tif (ResolveFailure != null) {\n\t\t\t\tassembly = ResolveFailure (this, name);\n\t\t\t\tif (assembly != null)\n\t\t\t\t\treturn assembly;\n\t\t\t}\n\n\t\t\tthrow new AssemblyResolutionException (name);\n\t\t}\n\n\t\tAssemblyDefinition SearchDirectory (AssemblyNameReference name, IEnumerable<string> directories, ReaderParameters parameters)\n\t\t{\n\t\t\tvar extensions = new [] { \".exe\", \".dll\" };\n\t\t\tforeach (var directory in directories) {\n\t\t\t\tforeach (var extension in extensions) {\n\t\t\t\t\tstring file = Path.Combine (directory, name.Name + extension);\n\t\t\t\t\tif (File.Exists (file))\n\t\t\t\t\t\treturn GetAssembly (file, parameters);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\n\t\tstatic bool IsZero (Version version)\n\t\t{\n\t\t\treturn version == null || (version.Major == 0 && version.Minor == 0 && version.Build == 0 && version.Revision == 0);\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/CallSite.cs",
    "content": "//\n// CallSite.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class CallSite : IMethodSignature {\n\n\t\treadonly MethodReference signature;\n\n\t\tpublic bool HasThis {\n\t\t\tget { return signature.HasThis; }\n\t\t\tset { signature.HasThis = value; }\n\t\t}\n\n\t\tpublic bool ExplicitThis {\n\t\t\tget { return signature.ExplicitThis; }\n\t\t\tset { signature.ExplicitThis = value; }\n\t\t}\n\n\t\tpublic MethodCallingConvention CallingConvention {\n\t\t\tget { return signature.CallingConvention; }\n\t\t\tset { signature.CallingConvention = value; }\n\t\t}\n\n\t\tpublic bool HasParameters {\n\t\t\tget { return signature.HasParameters; }\n\t\t}\n\n\t\tpublic Collection<ParameterDefinition> Parameters {\n\t\t\tget { return signature.Parameters; }\n\t\t}\n\n\t\tpublic TypeReference ReturnType {\n\t\t\tget { return signature.MethodReturnType.ReturnType; }\n\t\t\tset { signature.MethodReturnType.ReturnType = value; }\n\t\t}\n\n\t\tpublic MethodReturnType MethodReturnType {\n\t\t\tget { return signature.MethodReturnType; }\n\t\t}\n\n\t\tpublic string Name {\n\t\t\tget { return string.Empty; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic string Namespace {\n\t\t\tget { return string.Empty; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic ModuleDefinition Module {\n\t\t\tget { return ReturnType.Module; }\n\t\t}\n\n\t\tpublic IMetadataScope Scope {\n\t\t\tget { return signature.ReturnType.Scope; }\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return signature.token; }\n\t\t\tset { signature.token = value; }\n\t\t}\n\n\t\tpublic string FullName {\n\t\t\tget {\n\t\t\t\tvar signature = new StringBuilder ();\n\t\t\t\tsignature.Append (ReturnType.FullName);\n\t\t\t\tMixin.MethodSignatureFullName (this,signature);\n\t\t\t\treturn signature.ToString ();\n\t\t\t}\n\t\t}\n\n\t\tinternal CallSite ()\n\t\t{\n\t\t\tthis.signature = new MethodReference ();\n\t\t\tthis.signature.token = new MetadataToken (TokenType.Signature, 0);\n\t\t}\n\n\t\tpublic CallSite (TypeReference returnType)\n\t\t\t: this ()\n\t\t{\n\t\t\tif (returnType == null)\n\t\t\t\tthrow new ArgumentNullException (\"returnType\");\n\n\t\t\tthis.signature.ReturnType = returnType;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn FullName;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/CustomAttribute.cs",
    "content": "//\n// CustomAttribute.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic struct CustomAttributeArgument {\n\n\t\treadonly TypeReference type;\n\t\treadonly object value;\n\n\t\tpublic TypeReference Type {\n\t\t\tget { return type; }\n\t\t}\n\n\t\tpublic object Value {\n\t\t\tget { return value; }\n\t\t}\n\n\t\tpublic CustomAttributeArgument (TypeReference type, object value)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.type = type;\n\t\t\tthis.value = value;\n\t\t}\n\t}\n\n\tpublic struct CustomAttributeNamedArgument {\n\n\t\treadonly string name;\n\t\treadonly CustomAttributeArgument argument;\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t}\n\n\t\tpublic CustomAttributeArgument Argument {\n\t\t\tget { return argument; }\n\t\t}\n\n\t\tpublic CustomAttributeNamedArgument (string name, CustomAttributeArgument argument)\n\t\t{\n\t\t\tMixin.CheckName (name);\n\t\t\tthis.name = name;\n\t\t\tthis.argument = argument;\n\t\t}\n\t}\n\n\tpublic interface ICustomAttribute {\n\n\t\tTypeReference AttributeType { get; }\n\n\t\tbool HasFields { get; }\n\t\tbool HasProperties { get; }\n\t\tCollection<CustomAttributeNamedArgument> Fields { get; }\n\t\tCollection<CustomAttributeNamedArgument> Properties { get; }\n\t}\n\n\tpublic sealed class CustomAttribute : ICustomAttribute {\n\n\t\treadonly internal uint signature;\n\t\tinternal bool resolved;\n\t\tMethodReference constructor;\n\t\tbyte [] blob;\n\t\tinternal Collection<CustomAttributeArgument> arguments;\n\t\tinternal Collection<CustomAttributeNamedArgument> fields;\n\t\tinternal Collection<CustomAttributeNamedArgument> properties;\n\n\t\tpublic MethodReference Constructor {\n\t\t\tget { return constructor; }\n\t\t\tset { constructor = value; }\n\t\t}\n\n\t\tpublic TypeReference AttributeType {\n\t\t\tget { return constructor.DeclaringType; }\n\t\t}\n\n\t\tpublic bool IsResolved {\n\t\t\tget { return resolved; }\n\t\t}\n\n\t\tpublic bool HasConstructorArguments {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn !Mixin.IsNullOrEmpty (arguments);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttributeArgument> ConstructorArguments {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn arguments ?? (arguments = new Collection<CustomAttributeArgument> ());\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasFields {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn !Mixin.IsNullOrEmpty (fields);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttributeNamedArgument> Fields {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn fields ?? (fields = new Collection<CustomAttributeNamedArgument> ());\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasProperties {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn !Mixin.IsNullOrEmpty (properties);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttributeNamedArgument> Properties {\n\t\t\tget {\n\t\t\t\tResolve ();\n\n\t\t\t\treturn properties ?? (properties = new Collection<CustomAttributeNamedArgument> ());\n\t\t\t}\n\t\t}\n\n\t\tinternal bool HasImage {\n\t\t\tget { return constructor != null && constructor.HasImage; }\n\t\t}\n\n\t\tinternal ModuleDefinition Module {\n\t\t\tget { return constructor.Module; }\n\t\t}\n\n\t\tinternal CustomAttribute (uint signature, MethodReference constructor)\n\t\t{\n\t\t\tthis.signature = signature;\n\t\t\tthis.constructor = constructor;\n\t\t\tthis.resolved = false;\n\t\t}\n\n\t\tpublic CustomAttribute (MethodReference constructor)\n\t\t{\n\t\t\tthis.constructor = constructor;\n\t\t\tthis.resolved = true;\n\t\t}\n\n\t\tpublic CustomAttribute (MethodReference constructor, byte [] blob)\n\t\t{\n\t\t\tthis.constructor = constructor;\n\t\t\tthis.resolved = false;\n\t\t\tthis.blob = blob;\n\t\t}\n\n\t\tpublic byte [] GetBlob ()\n\t\t{\n\t\t\tif (blob != null)\n\t\t\t\treturn blob;\n\n\t\t\tif (!HasImage)\n\t\t\t\tthrow new NotSupportedException ();\n\n\t\t\treturn Module.Read (ref blob, this, (attribute, reader) => reader.ReadCustomAttributeBlob (attribute.signature));\n\t\t}\n\n\t\tvoid Resolve ()\n\t\t{\n\t\t\tif (resolved || !HasImage)\n\t\t\t\treturn;\n\n\t\t\tModule.Read (this, (attribute, reader) => {\n\t\t\t\ttry {\n\t\t\t\t\treader.ReadCustomAttributeSignature (attribute);\n\t\t\t\t\tresolved = true;\n\t\t\t\t} catch (ResolutionException) {\n\t\t\t\t\tif (arguments != null)\n\t\t\t\t\t\targuments.Clear ();\n\t\t\t\t\tif (fields != null)\n\t\t\t\t\t\tfields.Clear ();\n\t\t\t\t\tif (properties != null)\n\t\t\t\t\t\tproperties.Clear ();\n\n\t\t\t\t\tresolved = false;\n\t\t\t\t}\n\t\t\t\treturn this;\n\t\t\t});\n\t\t}\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic static void CheckName (string name)\n\t\t{\n\t\t\tif (name == null)\n\t\t\t\tthrow new ArgumentNullException (\"name\");\n\t\t\tif (name.Length == 0)\n\t\t\t\tthrow new ArgumentException (\"Empty name\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/DefaultAssemblyResolver.cs",
    "content": "//\n// DefaultAssemblyResolver.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic class DefaultAssemblyResolver : BaseAssemblyResolver {\n\n\t\treadonly IDictionary<string, AssemblyDefinition> cache;\n\n\t\tpublic DefaultAssemblyResolver ()\n\t\t{\n\t\t\tcache = new Dictionary<string, AssemblyDefinition> (StringComparer.Ordinal);\n\t\t}\n\n\t\tpublic override AssemblyDefinition Resolve (AssemblyNameReference name)\n\t\t{\n\t\t\tif (name == null)\n\t\t\t\tthrow new ArgumentNullException (\"name\");\n\n\t\t\tAssemblyDefinition assembly;\n\t\t\tif (cache.TryGetValue (name.FullName, out assembly))\n\t\t\t\treturn assembly;\n\n\t\t\tassembly = base.Resolve (name);\n\t\t\tcache [name.FullName] = assembly;\n\n\t\t\treturn assembly;\n\t\t}\n\n\t\tprotected void RegisterAssembly (AssemblyDefinition assembly)\n\t\t{\n\t\t\tif (assembly == null)\n\t\t\t\tthrow new ArgumentNullException (\"assembly\");\n\n\t\t\tvar name = assembly.Name.FullName;\n\t\t\tif (cache.ContainsKey (name))\n\t\t\t\treturn;\n\n\t\t\tcache [name] = assembly;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/EmbeddedResource.cs",
    "content": "//\n// EmbeddedResource.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class EmbeddedResource : Resource {\n\n\t\treadonly MetadataReader reader;\n\n\t\tuint? offset;\n\t\tbyte [] data;\n\t\tStream stream;\n\n\t\tpublic override ResourceType ResourceType {\n\t\t\tget { return ResourceType.Embedded; }\n\t\t}\n\n\t\tpublic EmbeddedResource (string name, ManifestResourceAttributes attributes, byte [] data) :\n\t\t\tbase (name, attributes)\n\t\t{\n\t\t\tthis.data = data;\n\t\t}\n\n\t\tpublic EmbeddedResource (string name, ManifestResourceAttributes attributes, Stream stream) :\n\t\t\tbase (name, attributes)\n\t\t{\n\t\t\tthis.stream = stream;\n\t\t}\n\n\t\tinternal EmbeddedResource (string name, ManifestResourceAttributes attributes, uint offset, MetadataReader reader)\n\t\t\t: base (name, attributes)\n\t\t{\n\t\t\tthis.offset = offset;\n\t\t\tthis.reader = reader;\n\t\t}\n\n\t\tpublic Stream GetResourceStream ()\n\t\t{\n\t\t\tif (stream != null)\n\t\t\t\treturn stream;\n\n\t\t\tif (data != null)\n\t\t\t\treturn new MemoryStream (data);\n\n\t\t\tif (offset.HasValue)\n\t\t\t\treturn reader.GetManagedResourceStream (offset.Value);\n\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tpublic byte [] GetResourceData ()\n\t\t{\n\t\t\tif (stream != null)\n\t\t\t\treturn ReadStream (stream);\n\n\t\t\tif (data != null)\n\t\t\t\treturn data;\n\n\t\t\tif (offset.HasValue)\n\t\t\t\treturn reader.GetManagedResourceStream (offset.Value).ToArray ();\n\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tstatic byte [] ReadStream (Stream stream)\n\t\t{\n\t\t\tvar length = (int) stream.Length;\n\t\t\tvar data = new byte [length];\n\t\t\tint offset = 0, read;\n\n\t\t\twhile ((read = stream.Read (data, offset, length - offset)) > 0)\n\t\t\t\toffset += read;\n\n\t\t\treturn data;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/EventAttributes.cs",
    "content": "//\n// EventAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum EventAttributes : ushort {\n\t\tNone\t\t\t= 0x0000,\n\t\tSpecialName\t\t= 0x0200,\t// Event is special\n\t\tRTSpecialName\t= 0x0400\t // CLI provides 'special' behavior, depending upon the name of the event\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/EventDefinition.cs",
    "content": "//\n// EventDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class EventDefinition : EventReference, IMemberDefinition {\n\n\t\tushort attributes;\n\n\t\tCollection<CustomAttribute> custom_attributes;\n\n\t\tinternal MethodDefinition add_method;\n\t\tinternal MethodDefinition invoke_method;\n\t\tinternal MethodDefinition remove_method;\n\t\tinternal Collection<MethodDefinition> other_methods;\n\n\t\tpublic EventAttributes Attributes {\n\t\t\tget { return (EventAttributes) attributes; }\n\t\t\tset { attributes = (ushort) value; }\n\t\t}\n\n\t\tpublic MethodDefinition AddMethod {\n\t\t\tget {\n\t\t\t\tif (add_method != null)\n\t\t\t\t\treturn add_method;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn add_method;\n\t\t\t}\n\t\t\tset { add_method = value; }\n\t\t}\n\n\t\tpublic MethodDefinition InvokeMethod {\n\t\t\tget {\n\t\t\t\tif (invoke_method != null)\n\t\t\t\t\treturn invoke_method;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn invoke_method;\n\t\t\t}\n\t\t\tset { invoke_method = value; }\n\t\t}\n\n\t\tpublic MethodDefinition RemoveMethod {\n\t\t\tget {\n\t\t\t\tif (remove_method != null)\n\t\t\t\t\treturn remove_method;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn remove_method;\n\t\t\t}\n\t\t\tset { remove_method = value; }\n\t\t}\n\n\t\tpublic bool HasOtherMethods {\n\t\t\tget {\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods.Count > 0;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn !Mixin.IsNullOrEmpty (other_methods);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<MethodDefinition> OtherMethods {\n\t\t\tget {\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods;\n\n\t\t\t\tInitializeMethods ();\n\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods;\n\n\t\t\t\treturn other_methods = new Collection<MethodDefinition> ();\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasCustomAttributes {\n\t\t\tget {\n\t\t\t\tif (custom_attributes != null)\n\t\t\t\t\treturn custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttribute> CustomAttributes {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n\t\t}\n\n\t\t#region EventAttributes\n\n\t\tpublic bool IsSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) EventAttributes.SpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) EventAttributes.SpecialName, value); }\n\t\t}\n\n\t\tpublic bool IsRuntimeSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.RTSpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.RTSpecialName, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic new TypeDefinition DeclaringType {\n\t\t\tget { return (TypeDefinition) base.DeclaringType; }\n\t\t\tset { base.DeclaringType = value; }\n\t\t}\n\n\t\tpublic override bool IsDefinition {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic EventDefinition (string name, EventAttributes attributes, TypeReference eventType)\n\t\t\t: base (name, eventType)\n\t\t{\n\t\t\tthis.attributes = (ushort) attributes;\n\t\t\tthis.token = new MetadataToken (TokenType.Event);\n\t\t}\n\n\t\tvoid InitializeMethods ()\n\t\t{\n\t\t\tvar module = this.Module;\n\t\t\tlock (module.SyncRoot) {\n\t\t\t\tif (add_method != null\n\t\t\t\t\t|| invoke_method != null\n\t\t\t\t\t|| remove_method != null)\n\t\t\t\t\treturn;\n\n                if (!Mixin.HasImage(module))\n\t\t\t\t\treturn;\n\n\t\t\t\tmodule.Read (this, (@event, reader) => reader.ReadMethods (@event));\n\t\t\t}\n\t\t}\n\n\t\tpublic override EventDefinition Resolve ()\n\t\t{\n\t\t\treturn this;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/EventReference.cs",
    "content": "//\n// EventReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class EventReference : MemberReference {\n\n\t\tTypeReference event_type;\n\n\t\tpublic TypeReference EventType {\n\t\t\tget { return event_type; }\n\t\t\tset { event_type = value; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return event_type.FullName + \" \" + MemberFullName (); }\n\t\t}\n\n\t\tprotected EventReference (string name, TypeReference eventType)\n\t\t\t: base (name)\n\t\t{\n\t\t\tif (eventType == null)\n\t\t\t\tthrow new ArgumentNullException (\"eventType\");\n\n\t\t\tevent_type = eventType;\n\t\t}\n\n\t\tpublic abstract EventDefinition Resolve ();\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ExportedType.cs",
    "content": "//\n// ExportedType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic class ExportedType : IMetadataTokenProvider {\n\n\t\tstring @namespace;\n\t\tstring name;\n\t\tuint attributes;\n\t\tIMetadataScope scope;\n\t\tModuleDefinition module;\n\t\tint identifier;\n\t\tExportedType declaring_type;\n\t\tinternal MetadataToken token;\n\n\t\tpublic string Namespace {\n\t\t\tget { return @namespace; }\n\t\t\tset { @namespace = value; }\n\t\t}\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic TypeAttributes Attributes {\n\t\t\tget { return (TypeAttributes) attributes; }\n\t\t\tset { attributes = (uint) value; }\n\t\t}\n\n\t\tpublic IMetadataScope Scope {\n\t\t\tget {\n\t\t\t\tif (declaring_type != null)\n\t\t\t\t\treturn declaring_type.Scope;\n\n\t\t\t\treturn scope;\n\t\t\t}\n\t\t}\n\n\t\tpublic ExportedType DeclaringType {\n\t\t\tget { return declaring_type; }\n\t\t\tset { declaring_type = value; }\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return token; }\n\t\t\tset { token = value; }\n\t\t}\n\n\t\tpublic int Identifier {\n\t\t\tget { return identifier; }\n\t\t\tset { identifier = value; }\n\t\t}\n\n\t\t#region TypeAttributes\n\n\t\tpublic bool IsNotPublic {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); }\n\t\t}\n\n\t\tpublic bool IsPublic {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); }\n\t\t}\n\n\t\tpublic bool IsNestedPublic {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); }\n\t\t}\n\n\t\tpublic bool IsNestedPrivate {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); }\n\t\t}\n\n\t\tpublic bool IsNestedFamily {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); }\n\t\t}\n\n\t\tpublic bool IsNestedAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); }\n\t\t}\n\n\t\tpublic bool IsNestedFamilyAndAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); }\n\t\t}\n\n\t\tpublic bool IsNestedFamilyOrAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); }\n\t\t}\n\n\t\tpublic bool IsAutoLayout {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); }\n\t\t}\n\n\t\tpublic bool IsSequentialLayout {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); }\n\t\t}\n\n\t\tpublic bool IsExplicitLayout {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); }\n\t\t}\n\n\t\tpublic bool IsClass {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); }\n\t\t}\n\n\t\tpublic bool IsInterface {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); }\n\t\t}\n\n\t\tpublic bool IsAbstract {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.Abstract); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.Abstract, value); }\n\t\t}\n\n\t\tpublic bool IsSealed {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.Sealed); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.Sealed, value); }\n\t\t}\n\n\t\tpublic bool IsSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.SpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.SpecialName, value); }\n\t\t}\n\n\t\tpublic bool IsImport {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.Import); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.Import, value); }\n\t\t}\n\n\t\tpublic bool IsSerializable {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.Serializable); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.Serializable, value); }\n\t\t}\n\n\t\tpublic bool IsAnsiClass {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); }\n\t\t}\n\n\t\tpublic bool IsUnicodeClass {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); }\n\t\t}\n\n\t\tpublic bool IsAutoClass {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); }\n\t\t}\n\n\t\tpublic bool IsBeforeFieldInit {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.BeforeFieldInit); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.BeforeFieldInit, value); }\n\t\t}\n\n\t\tpublic bool IsRuntimeSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.RTSpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.RTSpecialName, value); }\n\t\t}\n\n\t\tpublic bool HasSecurity {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.HasSecurity); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.HasSecurity, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic bool IsForwarder {\n\t\t\tget { return Mixin.GetAttributes(attributes,(uint) TypeAttributes.Forwarder); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(uint) TypeAttributes.Forwarder, value); }\n\t\t}\n\n\t\tpublic string FullName {\n\t\t\tget {\n\t\t\t\tif (declaring_type != null)\n\t\t\t\t\treturn declaring_type.FullName + \"/\" + name;\n\n\t\t\t\tif (string.IsNullOrEmpty (@namespace))\n\t\t\t\t\treturn name;\n\n\t\t\t\treturn @namespace + \".\" + name;\n\t\t\t}\n\t\t}\n\n\t\tpublic ExportedType (string @namespace, string name, ModuleDefinition module, IMetadataScope scope)\n\t\t{\n\t\t\tthis.@namespace = @namespace;\n\t\t\tthis.name = name;\n\t\t\tthis.scope = scope;\n\t\t\tthis.module = module;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn FullName;\n\t\t}\n\n\t\tpublic TypeDefinition Resolve ()\n\t\t{\n\t\t\treturn module.Resolve (CreateReference ());\n\t\t}\n\n\t\tinternal TypeReference CreateReference ()\n\t\t{\n\t\t\treturn new TypeReference (@namespace, name, module, scope) {\n\t\t\t\tDeclaringType = declaring_type != null ? declaring_type.CreateReference () : null,\n\t\t\t};\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/FieldAttributes.cs",
    "content": "//\n// FieldAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum FieldAttributes : ushort {\n\t\tFieldAccessMask\t\t= 0x0007,\n\t\tCompilerControlled\t= 0x0000,\t// Member not referenceable\n\t\tPrivate\t\t\t\t= 0x0001,\t// Accessible only by the parent type\n\t\tFamANDAssem\t\t\t= 0x0002,\t// Accessible by sub-types only in this assembly\n\t\tAssembly\t\t\t= 0x0003,\t// Accessible by anyone in the Assembly\n\t\tFamily\t\t\t\t= 0x0004,\t// Accessible only by type and sub-types\n\t\tFamORAssem\t\t\t= 0x0005,\t// Accessible by sub-types anywhere, plus anyone in the assembly\n\t\tPublic\t\t\t\t= 0x0006,\t// Accessible by anyone who has visibility to this scope field contract attributes\n\n\t\tStatic\t\t\t\t= 0x0010,\t// Defined on type, else per instance\n\t\tInitOnly\t\t\t= 0x0020,\t// Field may only be initialized, not written after init\n\t\tLiteral\t\t\t\t= 0x0040,\t// Value is compile time constant\n\t\tNotSerialized\t\t= 0x0080,\t// Field does not have to be serialized when type is remoted\n\t\tSpecialName\t\t\t= 0x0200,\t// Field is special\n\n\t\t// Interop Attributes\n\t\tPInvokeImpl\t\t\t= 0x2000,\t// Implementation is forwarded through PInvoke\n\n\t\t// Additional flags\n\t\tRTSpecialName\t\t= 0x0400,\t// CLI provides 'special' behavior, depending upon the name of the field\n\t\tHasFieldMarshal\t\t= 0x1000,\t// Field has marshalling information\n\t\tHasDefault\t\t\t= 0x8000,\t// Field has default\n\t\tHasFieldRVA\t\t\t= 0x0100\t // Field has RVA\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/FieldDefinition.cs",
    "content": "//\n// FieldDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class FieldDefinition : FieldReference, IMemberDefinition, IConstantProvider, IMarshalInfoProvider {\n\n\t\tushort attributes;\n\t\tCollection<CustomAttribute> custom_attributes;\n\n\t\tint offset = Mixin.NotResolvedMarker;\n\n\t\tinternal int rva = Mixin.NotResolvedMarker;\n\t\tbyte [] initial_value;\n\n\t\tobject constant = Mixin.NotResolved;\n\n\t\tMarshalInfo marshal_info;\n\n\t\tvoid ResolveLayout ()\n\t\t{\n\t\t\tif (offset != Mixin.NotResolvedMarker)\n\t\t\t\treturn;\n\n\t\t\tif (!HasImage) {\n\t\t\t\toffset = Mixin.NoDataMarker;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\toffset = Module.Read (this, (field, reader) => reader.ReadFieldLayout (field));\n\t\t}\n\n\t\tpublic bool HasLayoutInfo {\n\t\t\tget {\n\t\t\t\tif (offset >= 0)\n\t\t\t\t\treturn true;\n\n\t\t\t\tResolveLayout ();\n\n\t\t\t\treturn offset >= 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic int Offset {\n\t\t\tget {\n\t\t\t\tif (offset >= 0)\n\t\t\t\t\treturn offset;\n\n\t\t\t\tResolveLayout ();\n\n\t\t\t\treturn offset >= 0 ? offset : -1;\n\t\t\t}\n\t\t\tset { offset = value; }\n\t\t}\n\n\t\tvoid ResolveRVA ()\n\t\t{\n\t\t\tif (rva != Mixin.NotResolvedMarker)\n\t\t\t\treturn;\n\n\t\t\tif (!HasImage)\n\t\t\t\treturn;\n\n\t\t\trva = Module.Read (this, (field, reader) => reader.ReadFieldRVA (field));\n\t\t}\n\n\t\tpublic int RVA {\n\t\t\tget {\n\t\t\t\tif (rva > 0)\n\t\t\t\t\treturn rva;\n\n\t\t\t\tResolveRVA ();\n\n\t\t\t\treturn rva > 0 ? rva : 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic byte [] InitialValue {\n\t\t\tget {\n\t\t\t\tif (initial_value != null)\n\t\t\t\t\treturn initial_value;\n\n\t\t\t\tResolveRVA ();\n\n\t\t\t\tif (initial_value == null)\n\t\t\t\t\tinitial_value = Empty<byte>.Array;\n\n\t\t\t\treturn initial_value;\n\t\t\t}\n\t\t\tset { initial_value = value; }\n\t\t}\n\n\t\tpublic FieldAttributes Attributes {\n\t\t\tget { return (FieldAttributes) attributes; }\n\t\t\tset { attributes = (ushort) value; }\n\t\t}\n\n\t\tpublic bool HasConstant {\n\t\t\tget {\n                Mixin.ResolveConstant(this, ref constant, Module);\n\n\t\t\t\treturn constant != Mixin.NoValue;\n\t\t\t}\n\t\t\tset { if (!value) constant = Mixin.NoValue; }\n\t\t}\n\n\t\tpublic object Constant {\n\t\t\tget { return HasConstant ? constant : null;\t}\n\t\t\tset { constant = value; }\n\t\t}\n\n\t\tpublic bool HasCustomAttributes {\n\t\t\tget {\n\t\t\t\tif (custom_attributes != null)\n\t\t\t\t\treturn custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttribute> CustomAttributes {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n\t\t}\n\n\t\tpublic bool HasMarshalInfo {\n\t\t\tget {\n\t\t\t\tif (marshal_info != null)\n\t\t\t\t\treturn true;\n\n                return Mixin.GetHasMarshalInfo(this, Module);\n\t\t\t}\n\t\t}\n\n\t\tpublic MarshalInfo MarshalInfo {\n            get { return marshal_info ?? (Mixin.GetMarshalInfo(this, ref marshal_info, Module)); }\n\t\t\tset { marshal_info = value; }\n\t\t}\n\n\t\t#region FieldAttributes\n\n\t\tpublic bool IsCompilerControlled {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled, value); }\n\t\t}\n\n\t\tpublic bool IsPrivate {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private, value); }\n\t\t}\n\n\t\tpublic bool IsFamilyAndAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem, value); }\n\t\t}\n\n\t\tpublic bool IsAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly, value); }\n\t\t}\n\n\t\tpublic bool IsFamily {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family, value); }\n\t\t}\n\n\t\tpublic bool IsFamilyOrAssembly {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem, value); }\n\t\t}\n\n\t\tpublic bool IsPublic {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public, value); }\n\t\t}\n\n\t\tpublic bool IsStatic {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.Static); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.Static, value); }\n\t\t}\n\n\t\tpublic bool IsInitOnly {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.InitOnly); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.InitOnly, value); }\n\t\t}\n\n\t\tpublic bool IsLiteral {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.Literal); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.Literal, value); }\n\t\t}\n\n\t\tpublic bool IsNotSerialized {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.NotSerialized); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.NotSerialized, value); }\n\t\t}\n\n\t\tpublic bool IsSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.SpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.SpecialName, value); }\n\t\t}\n\n\t\tpublic bool IsPInvokeImpl {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.PInvokeImpl); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.PInvokeImpl, value); }\n\t\t}\n\n\t\tpublic bool IsRuntimeSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.RTSpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.RTSpecialName, value); }\n\t\t}\n\n\t\tpublic bool HasDefault {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) FieldAttributes.HasDefault); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) FieldAttributes.HasDefault, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic override bool IsDefinition {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic new TypeDefinition DeclaringType {\n\t\t\tget { return (TypeDefinition) base.DeclaringType; }\n\t\t\tset { base.DeclaringType = value; }\n\t\t}\n\n\t\tpublic FieldDefinition (string name, FieldAttributes attributes, TypeReference fieldType)\n\t\t\t: base (name, fieldType)\n\t\t{\n\t\t\tthis.attributes = (ushort) attributes;\n\t\t}\n\n\t\tpublic override FieldDefinition Resolve ()\n\t\t{\n\t\t\treturn this;\n\t\t}\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic const int NotResolvedMarker = -2;\n\t\tpublic const int NoDataMarker = -1;\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/FieldReference.cs",
    "content": "//\n// FieldReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic class FieldReference : MemberReference {\n\n\t\tTypeReference field_type;\n\n\t\tpublic TypeReference FieldType {\n\t\t\tget { return field_type; }\n\t\t\tset { field_type = value; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return field_type.FullName + \" \" + MemberFullName (); }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return field_type.ContainsGenericParameter || base.ContainsGenericParameter; }\n\t\t}\n\n\t\tinternal FieldReference ()\n\t\t{\n\t\t\tthis.token = new MetadataToken (TokenType.MemberRef);\n\t\t}\n\n\t\tpublic FieldReference (string name, TypeReference fieldType)\n\t\t\t: base (name)\n\t\t{\n\t\t\tif (fieldType == null)\n\t\t\t\tthrow new ArgumentNullException (\"fieldType\");\n\n\t\t\tthis.field_type = fieldType;\n\t\t\tthis.token = new MetadataToken (TokenType.MemberRef);\n\t\t}\n\n\t\tpublic FieldReference (string name, TypeReference fieldType, TypeReference declaringType)\n\t\t\t: this (name, fieldType)\n\t\t{\n\t\t\tif (declaringType == null)\n\t\t\t\tthrow new ArgumentNullException(\"declaringType\");\n\n\t\t\tthis.DeclaringType = declaringType;\n\t\t}\n\n\t\tpublic virtual FieldDefinition Resolve ()\n\t\t{\n\t\t\tvar module = this.Module;\n\t\t\tif (module == null)\n\t\t\t\tthrow new NotSupportedException ();\n\n\t\t\treturn module.Resolve (this);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/FileAttributes.cs",
    "content": "//\n// FileAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tenum FileAttributes : uint {\n\t\tContainsMetaData\t= 0x0000,\t// This is not a resource file\n\t\tContainsNoMetaData  = 0x0001,\t// This is a resource file or other non-metadata-containing file\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/FunctionPointerType.cs",
    "content": "//\n// FunctionPointerType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\nusing Mono.Collections.Generic;\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class FunctionPointerType : TypeSpecification, IMethodSignature {\n\n\t\treadonly MethodReference function;\n\n\t\tpublic bool HasThis {\n\t\t\tget { return function.HasThis; }\n\t\t\tset { function.HasThis = value; }\n\t\t}\n\n\t\tpublic bool ExplicitThis {\n\t\t\tget { return function.ExplicitThis; }\n\t\t\tset { function.ExplicitThis = value; }\n\t\t}\n\n\t\tpublic MethodCallingConvention CallingConvention {\n\t\t\tget { return function.CallingConvention; }\n\t\t\tset { function.CallingConvention = value; }\n\t\t}\n\n\t\tpublic bool HasParameters {\n\t\t\tget { return function.HasParameters; }\n\t\t}\n\n\t\tpublic Collection<ParameterDefinition> Parameters {\n\t\t\tget { return function.Parameters; }\n\t\t}\n\n\t\tpublic TypeReference ReturnType {\n\t\t\tget { return function.MethodReturnType.ReturnType; }\n\t\t\tset { function.MethodReturnType.ReturnType = value; }\n\t\t}\n\n\t\tpublic MethodReturnType MethodReturnType {\n\t\t\tget { return function.MethodReturnType; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return function.Name; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override string Namespace {\n\t\t\tget { return string.Empty; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override ModuleDefinition Module {\n\t\t\tget { return ReturnType.Module; }\n\t\t}\n\n\t\tpublic override IMetadataScope Scope {\n\t\t\tget { return function.ReturnType.Scope; }\n\t\t}\n\n\t\tpublic override bool IsFunctionPointer {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return function.ContainsGenericParameter; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget {\n\t\t\t\tvar signature = new StringBuilder ();\n\t\t\t\tsignature.Append (function.Name);\n\t\t\t\tsignature.Append (\" \");\n\t\t\t\tsignature.Append (function.ReturnType.FullName);\n\t\t\t\tsignature.Append (\" *\");\n\t\t\t\tMixin.MethodSignatureFullName (this,signature);\n\t\t\t\treturn signature.ToString ();\n\t\t\t}\n\t\t}\n\n\t\tpublic FunctionPointerType ()\n\t\t\t: base (null)\n\t\t{\n\t\t\tthis.function = new MethodReference ();\n\t\t\tthis.function.Name = \"method\";\n\t\t\tthis.etype = MD.ElementType.FnPtr;\n\t\t}\n\n\t\tpublic override TypeDefinition Resolve ()\n\t\t{\n\t\t\treturn null;\n\t\t}\n\n\t\tpublic override TypeReference GetElementType ()\n\t\t{\n\t\t\treturn this;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/GenericInstanceMethod.cs",
    "content": "//\n// GenericInstanceMethod.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class GenericInstanceMethod : MethodSpecification, IGenericInstance, IGenericContext\n    {\n\n        Collection<TypeReference> arguments;\n\n        public bool HasGenericArguments\n        {\n            get { return !Mixin.IsNullOrEmpty(arguments); }\n        }\n\n        public Collection<TypeReference> GenericArguments\n        {\n            get { return arguments ?? (arguments = new Collection<TypeReference>()); }\n        }\n\n        public override bool IsGenericInstance\n        {\n            get { return true; }\n        }\n\n        IGenericParameterProvider IGenericContext.Method\n        {\n            get { return ElementMethod; }\n        }\n\n        IGenericParameterProvider IGenericContext.Type\n        {\n            get { return ElementMethod.DeclaringType; }\n        }\n\n        internal override bool ContainsGenericParameter\n        {\n            get { return Mixin.ContainsGenericParameter(this) || base.ContainsGenericParameter; }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                var signature = new StringBuilder();\n                var method = this.ElementMethod;\n                signature.Append(method.ReturnType.FullName)\n                    .Append(\" \")\n                    .Append(method.DeclaringType.FullName)\n                    .Append(\"::\")\n                    .Append(method.Name);\n                Mixin.GenericInstanceFullName(this, signature);\n                Mixin.MethodSignatureFullName(this, signature);\n                return signature.ToString();\n\n            }\n        }\n\n        public GenericInstanceMethod(MethodReference method)\n            : base(method)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/GenericInstanceType.cs",
    "content": "//\n// GenericInstanceType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class GenericInstanceType : TypeSpecification, IGenericInstance, IGenericContext\n    {\n\n        Collection<TypeReference> arguments;\n\n        public bool HasGenericArguments\n        {\n            get { return !Mixin.IsNullOrEmpty(arguments); }\n        }\n\n        public Collection<TypeReference> GenericArguments\n        {\n            get { return arguments ?? (arguments = new Collection<TypeReference>()); }\n        }\n\n        public override TypeReference DeclaringType\n        {\n            get { return ElementType.DeclaringType; }\n            set { throw new NotSupportedException(); }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                var name = new StringBuilder();\n                name.Append(base.FullName);\n                Mixin.GenericInstanceFullName(this, name);\n                return name.ToString();\n            }\n        }\n\n        public override bool IsGenericInstance\n        {\n            get { return true; }\n        }\n\n        internal override bool ContainsGenericParameter\n        {\n            get { return Mixin.ContainsGenericParameter(this) || base.ContainsGenericParameter; }\n        }\n\n        IGenericParameterProvider IGenericContext.Type\n        {\n            get { return ElementType; }\n        }\n\n        public GenericInstanceType(TypeReference type)\n            : base(type)\n        {\n            base.IsValueType = type.IsValueType;\n            this.etype = MD.ElementType.GenericInst;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/GenericParameter.cs",
    "content": "//\n// GenericParameter.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class GenericParameter : TypeReference, ICustomAttributeProvider {\n\n\t\tinternal int position;\n\t\tinternal GenericParameterType type;\n\t\tinternal IGenericParameterProvider owner;\n\n\t\tushort attributes;\n\t\tCollection<TypeReference> constraints;\n\t\tCollection<CustomAttribute> custom_attributes;\n\n\t\tpublic GenericParameterAttributes Attributes {\n\t\t\tget { return (GenericParameterAttributes) attributes; }\n\t\t\tset { attributes = (ushort) value; }\n\t\t}\n\n\t\tpublic int Position {\n\t\t\tget { return position; }\n\t\t}\n\n\t\tpublic GenericParameterType Type {\n\t\t\tget { return type; }\n\t\t}\n\n\t\tpublic IGenericParameterProvider Owner {\n\t\t\tget { return owner; }\n\t\t}\n\n\t\tpublic bool HasConstraints {\n\t\t\tget {\n\t\t\t\tif (constraints != null)\n\t\t\t\t\treturn constraints.Count > 0;\n\n\t\t\t\tif (HasImage)\n\t\t\t\t\treturn Module.Read (this, (generic_parameter, reader) => reader.HasGenericConstraints (generic_parameter));\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<TypeReference> Constraints {\n\t\t\tget {\n\t\t\t\tif (constraints != null)\n\t\t\t\t\treturn constraints;\n\n\t\t\t\tif (HasImage)\n\t\t\t\t\treturn Module.Read (ref constraints, this, (generic_parameter, reader) => reader.ReadGenericConstraints (generic_parameter));\n\n\t\t\t\treturn constraints = new Collection<TypeReference> ();\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasCustomAttributes {\n\t\t\tget {\n\t\t\t\tif (custom_attributes != null)\n\t\t\t\t\treturn custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttribute> CustomAttributes {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n\t\t}\n\n\t\tpublic override IMetadataScope Scope {\n\t\t\tget {\n\t\t\t\tif (owner == null)\n\t\t\t\t\treturn null;\n\n\t\t\t\treturn owner.GenericParameterType == GenericParameterType.Method\n\t\t\t\t\t? ((MethodReference) owner).DeclaringType.Scope\n\t\t\t\t\t: ((TypeReference) owner).Scope;\n\t\t\t}\n\t\t}\n\n\t\tpublic override ModuleDefinition Module {\n\t\t\tget { return module ?? owner.Module; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget {\n\t\t\t\tif (!string.IsNullOrEmpty (base.Name))\n\t\t\t\t\treturn base.Name;\n\n\t\t\t\treturn base.Name = (type == GenericParameterType.Method ? \"!!\" : \"!\") + position;\n\t\t\t}\n\t\t}\n\n\t\tpublic override string Namespace {\n\t\t\tget { return string.Empty; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return Name; }\n\t\t}\n\n\t\tpublic override bool IsGenericParameter {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic override MetadataType MetadataType {\n\t\t\tget { return (MetadataType) etype; }\n\t\t}\n\n\t\t#region GenericParameterAttributes\n\n\t\tpublic bool IsNonVariant {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.NonVariant); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.NonVariant, value); }\n\t\t}\n\n\t\tpublic bool IsCovariant {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Covariant); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Covariant, value); }\n\t\t}\n\n\t\tpublic bool IsContravariant {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Contravariant); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Contravariant, value); }\n\t\t}\n\n\t\tpublic bool HasReferenceTypeConstraint {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) GenericParameterAttributes.ReferenceTypeConstraint); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) GenericParameterAttributes.ReferenceTypeConstraint, value); }\n\t\t}\n\n\t\tpublic bool HasNotNullableValueTypeConstraint {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) GenericParameterAttributes.NotNullableValueTypeConstraint); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) GenericParameterAttributes.NotNullableValueTypeConstraint, value); }\n\t\t}\n\n\t\tpublic bool HasDefaultConstructorConstraint {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) GenericParameterAttributes.DefaultConstructorConstraint); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) GenericParameterAttributes.DefaultConstructorConstraint, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic GenericParameter (IGenericParameterProvider owner)\n\t\t\t: this (string.Empty, owner)\n\t\t{\n\t\t}\n\n\t\tpublic GenericParameter (string name, IGenericParameterProvider owner)\n\t\t\t: base (string.Empty, name)\n\t\t{\n\t\t\tif (owner == null)\n\t\t\t\tthrow new ArgumentNullException ();\n\n\t\t\tthis.position = -1;\n\t\t\tthis.owner = owner;\n\t\t\tthis.type = owner.GenericParameterType;\n\t\t\tthis.etype = ConvertGenericParameterType (this.type);\n\t\t}\n\n\t\tpublic GenericParameter (int position, GenericParameterType type, ModuleDefinition module)\n\t\t\t: base (string.Empty, string.Empty)\n\t\t{\n\t\t\tif (module == null)\n\t\t\t\tthrow new ArgumentNullException ();\n\n\t\t\tthis.position = position;\n\t\t\tthis.type = type;\n\t\t\tthis.etype = ConvertGenericParameterType (type);\n\t\t\tthis.module = module;\n\t\t}\n\n\t\tstatic ElementType ConvertGenericParameterType (GenericParameterType type)\n\t\t{\n\t\t\tswitch (type) {\n\t\t\tcase GenericParameterType.Type:\n\t\t\t\treturn ElementType.Var;\n\t\t\tcase GenericParameterType.Method:\n\t\t\t\treturn ElementType.MVar;\n\t\t\t}\n\n\t\t\tthrow new ArgumentOutOfRangeException ();\n\t\t}\n\n\t\tpublic override TypeDefinition Resolve ()\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tsealed class GenericParameterCollection : Collection<GenericParameter> {\n\n\t\treadonly IGenericParameterProvider owner;\n\n\t\tinternal GenericParameterCollection (IGenericParameterProvider owner)\n\t\t{\n\t\t\tthis.owner = owner;\n\t\t}\n\n\t\tinternal GenericParameterCollection (IGenericParameterProvider owner, int capacity)\n\t\t\t: base (capacity)\n\t\t{\n\t\t\tthis.owner = owner;\n\t\t}\n\n\t\tprotected override void OnAdd (GenericParameter item, int index)\n\t\t{\n\t\t\tUpdateGenericParameter (item, index);\n\t\t}\n\n\t\tprotected override void OnInsert (GenericParameter item, int index)\n\t\t{\n\t\t\tUpdateGenericParameter (item, index);\n\n\t\t\tfor (int i = index; i < size; i++)\n\t\t\t\titems[i].position = i + 1;\n\t\t}\n\n\t\tprotected override void OnSet (GenericParameter item, int index)\n\t\t{\n\t\t\tUpdateGenericParameter (item, index);\n\t\t}\n\n\t\tvoid UpdateGenericParameter (GenericParameter item, int index)\n\t\t{\n\t\t\titem.owner = owner;\n\t\t\titem.position = index;\n\t\t\titem.type = owner.GenericParameterType;\n\t\t}\n\n\t\tprotected override void OnRemove (GenericParameter item, int index)\n\t\t{\n\t\t\titem.owner = null;\n\t\t\titem.position = -1;\n\t\t\titem.type = GenericParameterType.Type;\n\n\t\t\tfor (int i = index + 1; i < size; i++)\n\t\t\t\titems[i].position = i - 1;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/GenericParameterAttributes.cs",
    "content": "//\n// GenericParameterAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum GenericParameterAttributes : ushort {\n\t\tVarianceMask\t= 0x0003,\n\t\tNonVariant\t\t= 0x0000,\n\t\tCovariant\t\t= 0x0001,\n\t\tContravariant\t= 0x0002,\n\n\t\tSpecialConstraintMask\t\t\t= 0x001c,\n\t\tReferenceTypeConstraint\t\t\t= 0x0004,\n\t\tNotNullableValueTypeConstraint\t= 0x0008,\n\t\tDefaultConstructorConstraint\t= 0x0010\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/IConstantProvider.cs",
    "content": "//\n// IConstantProvider.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic interface IConstantProvider : IMetadataTokenProvider {\n\n\t\tbool HasConstant { get; set; }\n\t\tobject Constant { get; set; }\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tinternal static object NoValue = new object ();\n\t\tinternal static object NotResolved = new object ();\n\n\t\tpublic static void ResolveConstant (\n\t\t\tIConstantProvider self,\n\t\t\tref object constant,\n\t\t\tModuleDefinition module)\n\t\t{\n\t\t\tlock (module.SyncRoot) {\n\t\t\t\tif (constant != Mixin.NotResolved)\n\t\t\t\t\treturn;\n\t\t\t\tif (Mixin.HasImage (module))\n\t\t\t\t\tconstant = module.Read (self, (provider, reader) => reader.ReadConstant (provider));\n\t\t\t\telse\n\t\t\t\t\tconstant = Mixin.NoValue;\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ICustomAttributeProvider.cs",
    "content": "//\n// ICustomAttributeProvider.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public interface ICustomAttributeProvider : IMetadataTokenProvider\n    {\n\n        Collection<CustomAttribute> CustomAttributes { get; }\n\n        bool HasCustomAttributes { get; }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool GetHasCustomAttributes(\n            ICustomAttributeProvider self,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module) && module.Read(self, (provider, reader) => reader.HasCustomAttributes(provider));\n        }\n\n        public static Collection<CustomAttribute> GetCustomAttributes(\n            ICustomAttributeProvider self,\n            ref Collection<CustomAttribute> variable,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module)\n                ? module.Read(ref variable, self, (provider, reader) => reader.ReadCustomAttributes(provider))\n                : variable = new Collection<CustomAttribute>();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/IGenericInstance.cs",
    "content": "//\n// IGenericInstance.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic interface IGenericInstance : IMetadataTokenProvider {\n\n\t\tbool HasGenericArguments { get; }\n\t\tCollection<TypeReference> GenericArguments { get; }\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic static bool ContainsGenericParameter (IGenericInstance self)\n\t\t{\n\t\t\tvar arguments = self.GenericArguments;\n\n\t\t\tfor (int i = 0; i < arguments.Count; i++)\n\t\t\t\tif (arguments [i].ContainsGenericParameter)\n\t\t\t\t\treturn true;\n\n\t\t\treturn false;\n\t\t}\n\n\t\tpublic static void GenericInstanceFullName (IGenericInstance self, StringBuilder builder)\n\t\t{\n\t\t\tbuilder.Append (\"<\");\n\t\t\tvar arguments = self.GenericArguments;\n\t\t\tfor (int i = 0; i < arguments.Count; i++) {\n\t\t\t\tif (i > 0)\n\t\t\t\t\tbuilder.Append (\",\");\n\t\t\t\tbuilder.Append (arguments [i].FullName);\n\t\t\t}\n\t\t\tbuilder.Append (\">\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/IGenericParameterProvider.cs",
    "content": "//\n// IGenericParameterProvider.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public interface IGenericParameterProvider : IMetadataTokenProvider\n    {\n\n        bool HasGenericParameters { get; }\n        bool IsDefinition { get; }\n        ModuleDefinition Module { get; }\n        Collection<GenericParameter> GenericParameters { get; }\n        GenericParameterType GenericParameterType { get; }\n    }\n\n    public enum GenericParameterType\n    {\n        Type,\n        Method\n    }\n\n    interface IGenericContext\n    {\n\n        bool IsDefinition { get; }\n        IGenericParameterProvider Type { get; }\n        IGenericParameterProvider Method { get; }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool GetHasGenericParameters(\n            IGenericParameterProvider self,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module) && module.Read(self, (provider, reader) => reader.HasGenericParameters(provider));\n        }\n\n        public static Collection<GenericParameter> GetGenericParameters(\n            IGenericParameterProvider self,\n            ref Collection<GenericParameter> collection,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module)\n                ? module.Read(ref collection, self, (provider, reader) => reader.ReadGenericParameters(provider))\n                : collection = new GenericParameterCollection(self);\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/IMarshalInfoProvider.cs",
    "content": "//\n// IMarshalInfoProvider.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil\n{\n\n    public interface IMarshalInfoProvider : IMetadataTokenProvider\n    {\n\n        bool HasMarshalInfo { get; }\n        MarshalInfo MarshalInfo { get; set; }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool GetHasMarshalInfo(\n            IMarshalInfoProvider self,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module) && module.Read(self, (provider, reader) => reader.HasMarshalInfo(provider));\n        }\n\n        public static MarshalInfo GetMarshalInfo(\n            IMarshalInfoProvider self,\n            ref MarshalInfo variable,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module)\n                ? module.Read(ref variable, self, (provider, reader) => reader.ReadMarshalInfo(provider))\n                : null;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/IMemberDefinition.cs",
    "content": "//\n// IMemberDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil\n{\n\n    public interface IMemberDefinition : ICustomAttributeProvider\n    {\n\n        string Name { get; set; }\n        string FullName { get; }\n\n        bool IsSpecialName { get; set; }\n        bool IsRuntimeSpecialName { get; set; }\n\n        TypeDefinition DeclaringType { get; set; }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool GetAttributes(uint self, uint attributes)\n        {\n            return (self & attributes) != 0;\n        }\n\n        public static uint SetAttributes(uint self, uint attributes, bool value)\n        {\n            if (value)\n                return self | attributes;\n\n            return self & ~attributes;\n        }\n\n        public static bool GetMaskedAttributes(uint self, uint mask, uint attributes)\n        {\n            return (self & mask) == attributes;\n        }\n\n        public static uint SetMaskedAttributes(uint self, uint mask, uint attributes, bool value)\n        {\n            if (value)\n            {\n                self &= ~mask;\n                return self | attributes;\n            }\n\n            return self & ~(mask & attributes);\n        }\n\n        public static bool GetAttributes(ushort self, ushort attributes)\n        {\n            return (self & attributes) != 0;\n        }\n\n        public static ushort SetAttributes(ushort self, ushort attributes, bool value)\n        {\n            if (value)\n                return (ushort)(self | attributes);\n\n            return (ushort)(self & ~attributes);\n        }\n\n        public static bool GetMaskedAttributes(ushort self, ushort mask, uint attributes)\n        {\n            return (self & mask) == attributes;\n        }\n\n        public static ushort SetMaskedAttributes(ushort self, ushort mask, uint attributes, bool value)\n        {\n            if (value)\n            {\n                self = (ushort)(self & ~mask);\n                return (ushort)(self | attributes);\n            }\n\n            return (ushort)(self & ~(mask & attributes));\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/IMetadataScope.cs",
    "content": "//\n// IMetadataScope.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum MetadataScopeType {\n\t\tAssemblyNameReference,\n\t\tModuleReference,\n\t\tModuleDefinition,\n\t}\n\n\tpublic interface IMetadataScope : IMetadataTokenProvider {\n\t\tMetadataScopeType MetadataScopeType { get; }\n\t\tstring Name { get; set; }\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/IMetadataTokenProvider.cs",
    "content": "//\n// IMetadataTokenProvider.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic interface IMetadataTokenProvider {\n\n\t\tMetadataToken MetadataToken { get; set; }\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/IMethodSignature.cs",
    "content": "//\n// IMethodSignature.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic interface IMethodSignature : IMetadataTokenProvider {\n\n\t\tbool HasThis { get; set; }\n\t\tbool ExplicitThis { get; set; }\n\t\tMethodCallingConvention CallingConvention { get; set; }\n\n\t\tbool HasParameters { get; }\n\t\tCollection<ParameterDefinition> Parameters { get; }\n\t\tTypeReference ReturnType { get; set; }\n\t\tMethodReturnType MethodReturnType { get; }\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic static bool HasImplicitThis (IMethodSignature self)\n\t\t{\n\t\t\treturn self.HasThis && !self.ExplicitThis;\n\t\t}\n\n\t\tpublic static void MethodSignatureFullName (IMethodSignature self, StringBuilder builder)\n\t\t{\n\t\t\tbuilder.Append (\"(\");\n\n\t\t\tif (self.HasParameters) {\n\t\t\t\tvar parameters = self.Parameters;\n\t\t\t\tfor (int i = 0; i < parameters.Count; i++) {\n\t\t\t\t\tvar parameter = parameters [i];\n\t\t\t\t\tif (i > 0)\n\t\t\t\t\t\tbuilder.Append (\",\");\n\n\t\t\t\t\tif (parameter.ParameterType.IsSentinel)\n\t\t\t\t\t\tbuilder.Append (\"...,\");\n\n\t\t\t\t\tbuilder.Append (parameter.ParameterType.FullName);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbuilder.Append (\")\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/Import.cs",
    "content": "//\n// Import.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing SR = System.Reflection;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil\n{\n\n    enum ImportGenericKind\n    {\n        Definition,\n        Open,\n    }\n\n    class MetadataImporter\n    {\n\n        readonly ModuleDefinition module;\n\n        public MetadataImporter(ModuleDefinition module)\n        {\n            this.module = module;\n        }\n\n\n        public TypeReference ImportType(TypeReference type, IGenericContext context)\n        {\n            if (Mixin.IsTypeSpecification(type))\n                return ImportTypeSpecification(type, context);\n\n            var reference = new TypeReference(\n                type.Namespace,\n                type.Name,\n                module,\n                ImportScope(type.Scope),\n                type.IsValueType);\n\n            MetadataSystem.TryProcessPrimitiveTypeReference(reference);\n\n            if (type.IsNested)\n                reference.DeclaringType = ImportType(type.DeclaringType, context);\n\n            if (type.HasGenericParameters)\n                ImportGenericParameters(reference, type);\n\n            return reference;\n        }\n\n        IMetadataScope ImportScope(IMetadataScope scope)\n        {\n            switch (scope.MetadataScopeType)\n            {\n                case MetadataScopeType.AssemblyNameReference:\n                    return ImportAssemblyName((AssemblyNameReference)scope);\n                case MetadataScopeType.ModuleDefinition:\n                    return ImportAssemblyName(((ModuleDefinition)scope).Assembly.Name);\n                case MetadataScopeType.ModuleReference:\n                    throw new NotImplementedException();\n            }\n\n            throw new NotSupportedException();\n        }\n\n        AssemblyNameReference ImportAssemblyName(AssemblyNameReference name)\n        {\n            AssemblyNameReference reference;\n            if (TryGetAssemblyNameReference(name, out reference))\n                return reference;\n\n            reference = new AssemblyNameReference(name.Name, name.Version)\n            {\n                Culture = name.Culture,\n                HashAlgorithm = name.HashAlgorithm,\n            };\n\n            var pk_token = !Mixin.IsNullOrEmpty(name.PublicKeyToken)\n                ? new byte[name.PublicKeyToken.Length]\n                : Empty<byte>.Array;\n\n            if (pk_token.Length > 0)\n                Buffer.BlockCopy(name.PublicKeyToken, 0, pk_token, 0, pk_token.Length);\n\n            reference.PublicKeyToken = pk_token;\n\n            module.AssemblyReferences.Add(reference);\n\n            return reference;\n        }\n\n        bool TryGetAssemblyNameReference(AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)\n        {\n            var references = module.AssemblyReferences;\n\n            for (int i = 0; i < references.Count; i++)\n            {\n                var reference = references[i];\n                if (name_reference.FullName != reference.FullName) // TODO compare field by field\n                    continue;\n\n                assembly_reference = reference;\n                return true;\n            }\n\n            assembly_reference = null;\n            return false;\n        }\n\n        static void ImportGenericParameters(IGenericParameterProvider imported, IGenericParameterProvider original)\n        {\n            var parameters = original.GenericParameters;\n            var imported_parameters = imported.GenericParameters;\n\n            for (int i = 0; i < parameters.Count; i++)\n                imported_parameters.Add(new GenericParameter(parameters[i].Name, imported));\n        }\n\n        TypeReference ImportTypeSpecification(TypeReference type, IGenericContext context)\n        {\n            switch (type.etype)\n            {\n                case ElementType.SzArray:\n                    var vector = (ArrayType)type;\n                    return new ArrayType(ImportType(vector.ElementType, context));\n                case ElementType.Ptr:\n                    var pointer = (PointerType)type;\n                    return new PointerType(ImportType(pointer.ElementType, context));\n                case ElementType.ByRef:\n                    var byref = (ByReferenceType)type;\n                    return new ByReferenceType(ImportType(byref.ElementType, context));\n                case ElementType.Pinned:\n                    var pinned = (PinnedType)type;\n                    return new PinnedType(ImportType(pinned.ElementType, context));\n                case ElementType.Sentinel:\n                    var sentinel = (SentinelType)type;\n                    return new SentinelType(ImportType(sentinel.ElementType, context));\n                case ElementType.CModOpt:\n                    var modopt = (OptionalModifierType)type;\n                    return new OptionalModifierType(\n                        ImportType(modopt.ModifierType, context),\n                        ImportType(modopt.ElementType, context));\n                case ElementType.CModReqD:\n                    var modreq = (RequiredModifierType)type;\n                    return new RequiredModifierType(\n                        ImportType(modreq.ModifierType, context),\n                        ImportType(modreq.ElementType, context));\n                case ElementType.Array:\n                    var array = (ArrayType)type;\n                    var imported_array = new ArrayType(ImportType(array.ElementType, context));\n                    if (array.IsVector)\n                        return imported_array;\n\n                    var dimensions = array.Dimensions;\n                    var imported_dimensions = imported_array.Dimensions;\n\n                    imported_dimensions.Clear();\n\n                    for (int i = 0; i < dimensions.Count; i++)\n                    {\n                        var dimension = dimensions[i];\n\n                        imported_dimensions.Add(new ArrayDimension(dimension.LowerBound, dimension.UpperBound));\n                    }\n\n                    return imported_array;\n                case ElementType.GenericInst:\n                    var instance = (GenericInstanceType)type;\n                    var element_type = ImportType(instance.ElementType, context);\n                    var imported_instance = new GenericInstanceType(element_type);\n\n                    var arguments = instance.GenericArguments;\n                    var imported_arguments = imported_instance.GenericArguments;\n\n                    for (int i = 0; i < arguments.Count; i++)\n                        imported_arguments.Add(ImportType(arguments[i], context));\n\n                    return imported_instance;\n                case ElementType.Var:\n                    if (context == null || context.Type == null)\n                        throw new InvalidOperationException();\n\n                    return ((TypeReference)context.Type).GetElementType().GenericParameters[((GenericParameter)type).Position];\n                case ElementType.MVar:\n                    if (context == null || context.Method == null)\n                        throw new InvalidOperationException();\n\n                    return context.Method.GenericParameters[((GenericParameter)type).Position];\n            }\n\n            throw new NotSupportedException(type.etype.ToString());\n        }\n\n        public FieldReference ImportField(FieldReference field, IGenericContext context)\n        {\n            var declaring_type = ImportType(field.DeclaringType, context);\n\n            return new FieldReference\n            {\n                Name = field.Name,\n                DeclaringType = declaring_type,\n                FieldType = ImportType(field.FieldType, context ?? declaring_type),\n            };\n        }\n\n        public MethodReference ImportMethod(MethodReference method, IGenericContext context)\n        {\n            if (method.IsGenericInstance)\n                return ImportMethodSpecification(method, context);\n\n            var declaring_type = ImportType(method.DeclaringType, context);\n\n            var reference = new MethodReference\n            {\n                Name = method.Name,\n                HasThis = method.HasThis,\n                ExplicitThis = method.ExplicitThis,\n                DeclaringType = declaring_type,\n            };\n\n            reference.CallingConvention = method.CallingConvention;\n\n            if (method.HasGenericParameters)\n                ImportGenericParameters(reference, method);\n\n            reference.ReturnType = ImportType(method.ReturnType, context ?? reference);\n\n            if (!method.HasParameters)\n                return reference;\n\n            var reference_parameters = reference.Parameters;\n\n            var parameters = method.Parameters;\n            for (int i = 0; i < parameters.Count; i++)\n                reference_parameters.Add(\n                    new ParameterDefinition(ImportType(parameters[i].ParameterType, context ?? reference)));\n\n            return reference;\n        }\n\n        MethodSpecification ImportMethodSpecification(MethodReference method, IGenericContext context)\n        {\n            if (!method.IsGenericInstance)\n                throw new NotSupportedException();\n\n            var instance = (GenericInstanceMethod)method;\n            var element_method = ImportMethod(instance.ElementMethod, context);\n            var imported_instance = new GenericInstanceMethod(element_method);\n\n            var arguments = instance.GenericArguments;\n            var imported_arguments = imported_instance.GenericArguments;\n\n            for (int i = 0; i < arguments.Count; i++)\n                imported_arguments.Add(ImportType(arguments[i], context));\n\n            return imported_instance;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/LinkedResource.cs",
    "content": "//\n// LinkedResource.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class LinkedResource : Resource {\n\n\t\tinternal byte [] hash;\n\t\tstring file;\n\n\t\tpublic byte [] Hash {\n\t\t\tget { return hash; }\n\t\t}\n\n\t\tpublic string File {\n\t\t\tget { return file; }\n\t\t\tset { file = value; }\n\t\t}\n\n\t\tpublic override ResourceType ResourceType {\n\t\t\tget { return ResourceType.Linked; }\n\t\t}\n\n\t\tpublic LinkedResource (string name, ManifestResourceAttributes flags)\n\t\t\t: base (name, flags)\n\t\t{\n\t\t}\n\n\t\tpublic LinkedResource (string name, ManifestResourceAttributes flags, string file)\n\t\t\t: base (name, flags)\n\t\t{\n\t\t\tthis.file = file;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ManifestResourceAttributes.cs",
    "content": "//\n// ManifestResourceAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum ManifestResourceAttributes : uint {\n\t\tVisibilityMask\t= 0x0007,\n\t\tPublic\t\t\t= 0x0001,\t// The resource is exported from the Assembly\n\t\tPrivate\t\t\t= 0x0002\t // The resource is private to the Assembly\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MarshalInfo.cs",
    "content": "//\n// MarshalInfo.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic class MarshalInfo {\n\n\t\tinternal NativeType native;\n\n\t\tpublic NativeType NativeType {\n\t\t\tget { return native; }\n\t\t\tset { native = value; }\n\t\t}\n\n\t\tpublic MarshalInfo (NativeType native)\n\t\t{\n\t\t\tthis.native = native;\n\t\t}\n\t}\n\n\tpublic sealed class ArrayMarshalInfo : MarshalInfo {\n\n\t\tinternal NativeType element_type;\n\t\tinternal int size_parameter_index;\n\t\tinternal int size;\n\t\tinternal int size_parameter_multiplier;\n\n\t\tpublic NativeType ElementType {\n\t\t\tget { return element_type; }\n\t\t\tset { element_type = value; }\n\t\t}\n\n\t\tpublic int SizeParameterIndex {\n\t\t\tget { return size_parameter_index; }\n\t\t\tset { size_parameter_index = value; }\n\t\t}\n\n\t\tpublic int Size {\n\t\t\tget { return size; }\n\t\t\tset { size = value; }\n\t\t}\n\n\t\tpublic int SizeParameterMultiplier {\n\t\t\tget { return size_parameter_multiplier; }\n\t\t\tset { size_parameter_multiplier = value; }\n\t\t}\n\n\t\tpublic ArrayMarshalInfo ()\n\t\t\t: base (NativeType.Array)\n\t\t{\n\t\t\telement_type = NativeType.None;\n\t\t\tsize_parameter_index = -1;\n\t\t\tsize = -1;\n\t\t\tsize_parameter_multiplier = -1;\n\t\t}\n\t}\n\n\tpublic sealed class CustomMarshalInfo : MarshalInfo {\n\n\t\tinternal Guid guid;\n\t\tinternal string unmanaged_type;\n\t\tinternal TypeReference managed_type;\n\t\tinternal string cookie;\n\n\t\tpublic Guid Guid {\n\t\t\tget { return guid; }\n\t\t\tset { guid = value; }\n\t\t}\n\n\t\tpublic string UnmanagedType {\n\t\t\tget { return unmanaged_type; }\n\t\t\tset { unmanaged_type = value; }\n\t\t}\n\n\t\tpublic TypeReference ManagedType {\n\t\t\tget { return managed_type; }\n\t\t\tset { managed_type = value; }\n\t\t}\n\n\t\tpublic string Cookie {\n\t\t\tget { return cookie; }\n\t\t\tset { cookie = value; }\n\t\t}\n\n\t\tpublic CustomMarshalInfo ()\n\t\t\t: base (NativeType.CustomMarshaler)\n\t\t{\n\t\t}\n\t}\n\n\tpublic sealed class SafeArrayMarshalInfo : MarshalInfo {\n\n\t\tinternal VariantType element_type;\n\n\t\tpublic VariantType ElementType {\n\t\t\tget { return element_type; }\n\t\t\tset { element_type = value; }\n\t\t}\n\n\t\tpublic SafeArrayMarshalInfo ()\n\t\t\t: base (NativeType.SafeArray)\n\t\t{\n\t\t\telement_type = VariantType.None;\n\t\t}\n\t}\n\n\tpublic sealed class FixedArrayMarshalInfo : MarshalInfo {\n\n\t\tinternal NativeType element_type;\n\t\tinternal int size;\n\n\t\tpublic NativeType ElementType {\n\t\t\tget { return element_type; }\n\t\t\tset { element_type = value; }\n\t\t}\n\n\t\tpublic int Size {\n\t\t\tget { return size; }\n\t\t\tset { size = value; }\n\t\t}\n\n\t\tpublic FixedArrayMarshalInfo ()\n\t\t\t: base (NativeType.FixedArray)\n\t\t{\n\t\t\telement_type = NativeType.None;\n\t\t}\n\t}\n\n\tpublic sealed class FixedSysStringMarshalInfo : MarshalInfo {\n\n\t\tinternal int size;\n\n\t\tpublic int Size {\n\t\t\tget { return size; }\n\t\t\tset { size = value; }\n\t\t}\n\n\t\tpublic FixedSysStringMarshalInfo ()\n\t\t\t: base (NativeType.FixedSysString)\n\t\t{\n\t\t\tsize = -1;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MemberDefinitionCollection.cs",
    "content": "//\n// MemberDefinitionCollection.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tclass MemberDefinitionCollection<T> : Collection<T> where T : IMemberDefinition {\n\n\t\tTypeDefinition container;\n\n\t\tinternal MemberDefinitionCollection (TypeDefinition container)\n\t\t{\n\t\t\tthis.container = container;\n\t\t}\n\n\t\tinternal MemberDefinitionCollection (TypeDefinition container, int capacity)\n\t\t\t: base (capacity)\n\t\t{\n\t\t\tthis.container = container;\n\t\t}\n\n\t\tprotected override void OnAdd (T item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected sealed override void OnSet (T item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected sealed override void OnInsert (T item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected sealed override void OnRemove (T item, int index)\n\t\t{\n\t\t\tDetach (item);\n\t\t}\n\n\t\tprotected sealed override void OnClear ()\n\t\t{\n\t\t\tforeach (var definition in this)\n\t\t\t\tDetach (definition);\n\t\t}\n\n\t\tvoid Attach (T element)\n\t\t{\n\t\t\tif (element.DeclaringType == container)\n\t\t\t\treturn;\n\n\t\t\tif (element.DeclaringType != null)\n\t\t\t\tthrow new ArgumentException (\"Member already attached\");\n\n\t\t\telement.DeclaringType = this.container;\n\t\t}\n\n\t\tstatic void Detach (T element)\n\t\t{\n\t\t\telement.DeclaringType = null;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MemberReference.cs",
    "content": "//\n// MemberReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class MemberReference : IMetadataTokenProvider {\n\n\t\tstring name;\n\t\tTypeReference declaring_type;\n\n\t\tinternal MetadataToken token;\n\n\t\tpublic virtual string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic abstract string FullName {\n\t\t\tget;\n\t\t}\n\n\t\tpublic virtual TypeReference DeclaringType {\n\t\t\tget { return declaring_type; }\n\t\t\tset { declaring_type = value; }\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return token; }\n\t\t\tset { token = value; }\n\t\t}\n\n\t\tinternal bool HasImage {\n\t\t\tget {\n\t\t\t\tvar module = Module;\n\t\t\t\tif (module == null)\n\t\t\t\t\treturn false;\n\n\t\t\t\treturn module.HasImage;\n\t\t\t}\n\t\t}\n\n\t\tpublic virtual ModuleDefinition Module {\n\t\t\tget { return declaring_type != null ? declaring_type.Module : null; }\n\t\t}\n\n\t\tpublic virtual bool IsDefinition {\n\t\t\tget { return false; }\n\t\t}\n\n\t\tinternal virtual bool ContainsGenericParameter {\n\t\t\tget { return declaring_type != null && declaring_type.ContainsGenericParameter; }\n\t\t}\n\n\t\tinternal MemberReference ()\n\t\t{\n\t\t}\n\n\t\tinternal MemberReference (string name)\n\t\t{\n\t\t\tthis.name = name ?? string.Empty;\n\t\t}\n\n\t\tinternal string MemberFullName ()\n\t\t{\n\t\t\tif (declaring_type == null)\n\t\t\t\treturn name;\n\n\t\t\treturn declaring_type.FullName + \"::\" + name;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn FullName;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MetadataResolver.cs",
    "content": "//\n// MetadataResolver.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public interface IAssemblyResolver\n    {\n        AssemblyDefinition Resolve(AssemblyNameReference name);\n        AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters);\n\n        AssemblyDefinition Resolve(string fullName);\n        AssemblyDefinition Resolve(string fullName, ReaderParameters parameters);\n        event AssemblyResolveEventHandler ResolveFailure;\n    }\n\n    public interface IMetadataResolver\n    {\n        TypeDefinition Resolve(TypeReference type);\n        FieldDefinition Resolve(FieldReference field);\n        MethodDefinition Resolve(MethodReference method);\n    }\n\n\n    public class ResolutionException : Exception\n    {\n\n        readonly MemberReference member;\n\n        public MemberReference Member\n        {\n            get { return member; }\n        }\n\n        public ResolutionException(MemberReference member)\n            : base(\"Failed to resolve \" + member.FullName)\n        {\n            this.member = member;\n        }\n\n\n    }\n\n    public class MetadataResolver : IMetadataResolver\n    {\n\n        readonly IAssemblyResolver assembly_resolver;\n\n        public IAssemblyResolver AssemblyResolver\n        {\n            get { return assembly_resolver; }\n        }\n\n        public MetadataResolver(IAssemblyResolver assemblyResolver)\n        {\n            if (assemblyResolver == null)\n                throw new ArgumentNullException(\"assemblyResolver\");\n\n            assembly_resolver = assemblyResolver;\n        }\n\n        public virtual TypeDefinition Resolve(TypeReference type)\n        {\n            if (type == null)\n                throw new ArgumentNullException(\"type\");\n\n            type = type.GetElementType();\n\n            var scope = type.Scope;\n            switch (scope.MetadataScopeType)\n            {\n                case MetadataScopeType.AssemblyNameReference:\n                    var assembly = assembly_resolver.Resolve((AssemblyNameReference)scope);\n                    if (assembly == null)\n                        return null;\n\n                    return GetType(assembly.MainModule, type);\n                case MetadataScopeType.ModuleDefinition:\n                    return GetType((ModuleDefinition)scope, type);\n                case MetadataScopeType.ModuleReference:\n                    var modules = type.Module.Assembly.Modules;\n                    var module_ref = (ModuleReference)scope;\n                    for (int i = 0; i < modules.Count; i++)\n                    {\n                        var netmodule = modules[i];\n                        if (netmodule.Name == module_ref.Name)\n                            return GetType(netmodule, type);\n                    }\n                    break;\n            }\n\n            throw new NotSupportedException();\n        }\n\n        static TypeDefinition GetType(ModuleDefinition module, TypeReference reference)\n        {\n            var type = GetTypeDefinition(module, reference);\n            if (type != null)\n                return type;\n\n            if (!module.HasExportedTypes)\n                return null;\n\n            var exported_types = module.ExportedTypes;\n\n            for (int i = 0; i < exported_types.Count; i++)\n            {\n                var exported_type = exported_types[i];\n                if (exported_type.Name != reference.Name)\n                    continue;\n\n                if (exported_type.Namespace != reference.Namespace)\n                    continue;\n\n                return exported_type.Resolve();\n            }\n\n            return null;\n        }\n\n        static TypeDefinition GetTypeDefinition(ModuleDefinition module, TypeReference type)\n        {\n            if (!type.IsNested)\n                return module.GetType(type.Namespace, type.Name);\n\n            var declaring_type = type.DeclaringType.Resolve();\n            if (declaring_type == null)\n                return null;\n\n            return Mixin.GetNestedType(declaring_type, type.Name);\n        }\n\n        public virtual FieldDefinition Resolve(FieldReference field)\n        {\n            if (field == null)\n                throw new ArgumentNullException(\"field\");\n\n            var type = Resolve(field.DeclaringType);\n            if (type == null)\n                return null;\n\n            if (!type.HasFields)\n                return null;\n\n            return GetField(type, field);\n        }\n\n        FieldDefinition GetField(TypeDefinition type, FieldReference reference)\n        {\n            while (type != null)\n            {\n                var field = GetField(type.Fields, reference);\n                if (field != null)\n                    return field;\n\n                if (type.BaseType == null)\n                    return null;\n\n                type = Resolve(type.BaseType);\n            }\n\n            return null;\n        }\n\n        static FieldDefinition GetField(Collection<FieldDefinition> fields, FieldReference reference)\n        {\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var field = fields[i];\n\n                if (field.Name != reference.Name)\n                    continue;\n\n                if (!AreSame(field.FieldType, reference.FieldType))\n                    continue;\n\n                return field;\n            }\n\n            return null;\n        }\n\n        public virtual MethodDefinition Resolve(MethodReference method)\n        {\n            if (method == null)\n                throw new ArgumentNullException(\"method\");\n\n            var type = Resolve(method.DeclaringType);\n            if (type == null)\n                return null;\n\n            method = method.GetElementMethod();\n\n            if (!type.HasMethods)\n                return null;\n\n            return GetMethod(type, method);\n        }\n\n        MethodDefinition GetMethod(TypeDefinition type, MethodReference reference)\n        {\n            while (type != null)\n            {\n                var method = GetMethod(type.Methods, reference);\n                if (method != null)\n                    return method;\n\n                if (type.BaseType == null)\n                    return null;\n\n                type = Resolve(type.BaseType);\n            }\n\n            return null;\n        }\n\n        public static MethodDefinition GetMethod(Collection<MethodDefinition> methods, MethodReference reference)\n        {\n            for (int i = 0; i < methods.Count; i++)\n            {\n                var method = methods[i];\n\n                if (method.Name != reference.Name)\n                    continue;\n\n                if (method.HasGenericParameters != reference.HasGenericParameters)\n                    continue;\n\n                if (method.HasGenericParameters && method.GenericParameters.Count != reference.GenericParameters.Count)\n                    continue;\n\n                if (!AreSame(method.ReturnType, reference.ReturnType))\n                    continue;\n\n                if (method.HasParameters != reference.HasParameters)\n                    continue;\n\n                if (!method.HasParameters && !reference.HasParameters)\n                    return method;\n\n                if (!AreSame(method.Parameters, reference.Parameters))\n                    continue;\n\n                return method;\n            }\n\n            return null;\n        }\n\n        static bool AreSame(Collection<ParameterDefinition> a, Collection<ParameterDefinition> b)\n        {\n            var count = a.Count;\n\n            if (count != b.Count)\n                return false;\n\n            if (count == 0)\n                return true;\n\n            for (int i = 0; i < count; i++)\n                if (!AreSame(a[i].ParameterType, b[i].ParameterType))\n                    return false;\n\n            return true;\n        }\n\n        static bool AreSame(TypeSpecification a, TypeSpecification b)\n        {\n            if (!AreSame(a.ElementType, b.ElementType))\n                return false;\n\n            if (a.IsGenericInstance)\n                return AreSame((GenericInstanceType)a, (GenericInstanceType)b);\n\n            if (a.IsRequiredModifier || a.IsOptionalModifier)\n                return AreSame((IModifierType)a, (IModifierType)b);\n\n            if (a.IsArray)\n                return AreSame((ArrayType)a, (ArrayType)b);\n\n            return true;\n        }\n\n        static bool AreSame(ArrayType a, ArrayType b)\n        {\n            if (a.Rank != b.Rank)\n                return false;\n\n            // TODO: dimensions\n\n            return true;\n        }\n\n        static bool AreSame(IModifierType a, IModifierType b)\n        {\n            return AreSame(a.ModifierType, b.ModifierType);\n        }\n\n        static bool AreSame(GenericInstanceType a, GenericInstanceType b)\n        {\n            if (a.GenericArguments.Count != b.GenericArguments.Count)\n                return false;\n\n            for (int i = 0; i < a.GenericArguments.Count; i++)\n                if (!AreSame(a.GenericArguments[i], b.GenericArguments[i]))\n                    return false;\n\n            return true;\n        }\n\n        static bool AreSame(GenericParameter a, GenericParameter b)\n        {\n            return a.Position == b.Position;\n        }\n\n        static bool AreSame(TypeReference a, TypeReference b)\n        {\n            if (ReferenceEquals(a, b))\n                return true;\n\n            if (a == null || b == null)\n                return false;\n\n            if (a.etype != b.etype)\n                return false;\n\n            if (a.IsGenericParameter)\n                return AreSame((GenericParameter)a, (GenericParameter)b);\n\n            if (Mixin.IsTypeSpecification(a))\n                return AreSame((TypeSpecification)a, (TypeSpecification)b);\n\n            if (a.Name != b.Name || a.Namespace != b.Namespace)\n                return false;\n\n            //TODO: check scope\n\n            return AreSame(a.DeclaringType, b.DeclaringType);\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MetadataSystem.cs",
    "content": "//\n// MetadataSystem.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tstruct Range {\n\t\tpublic uint Start;\n\t\tpublic uint Length;\n\n\t\tpublic Range (uint index, uint length)\n\t\t{\n\t\t\tthis.Start = index;\n\t\t\tthis.Length = length;\n\t\t}\n\t}\n\n\tsealed class MetadataSystem {\n\n\t\tinternal AssemblyNameReference [] AssemblyReferences;\n\t\tinternal ModuleReference [] ModuleReferences;\n\n\t\tinternal TypeDefinition [] Types;\n\t\tinternal TypeReference [] TypeReferences;\n\n\t\tinternal FieldDefinition [] Fields;\n\t\tinternal MethodDefinition [] Methods;\n\t\tinternal MemberReference [] MemberReferences;\n\n\t\tinternal Dictionary<uint, uint []> NestedTypes;\n\t\tinternal Dictionary<uint, uint> ReverseNestedTypes;\n\t\tinternal Dictionary<uint, MetadataToken []> Interfaces;\n\t\tinternal Dictionary<uint, Row<ushort, uint>> ClassLayouts;\n\t\tinternal Dictionary<uint, uint> FieldLayouts;\n\t\tinternal Dictionary<uint, uint> FieldRVAs;\n\t\tinternal Dictionary<MetadataToken, uint> FieldMarshals;\n\t\tinternal Dictionary<MetadataToken, Row<ElementType, uint>> Constants;\n\t\tinternal Dictionary<uint, MetadataToken []> Overrides;\n\t\tinternal Dictionary<MetadataToken, Range> CustomAttributes;\n\t\tinternal Dictionary<MetadataToken, Range> SecurityDeclarations;\n\t\tinternal Dictionary<uint, Range> Events;\n\t\tinternal Dictionary<uint, Range> Properties;\n\t\tinternal Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>> Semantics;\n\t\tinternal Dictionary<uint, Row<PInvokeAttributes, uint, uint>> PInvokes;\n\t\tinternal Dictionary<MetadataToken, Range> GenericParameters;\n\t\tinternal Dictionary<uint, MetadataToken []> GenericConstraints;\n\n\t\tstatic Dictionary<string, Row<ElementType, bool>> primitive_value_types;\n\n\t\tstatic void InitializePrimitives ()\n\t\t{\n\t\t\tprimitive_value_types = new Dictionary<string, Row<ElementType, bool>> (18, StringComparer.Ordinal) {\n\t\t\t\t{ \"Void\", new Row<ElementType, bool> (ElementType.Void, false) },\n\t\t\t\t{ \"Boolean\", new Row<ElementType, bool> (ElementType.Boolean, true) },\n\t\t\t\t{ \"Char\", new Row<ElementType, bool> (ElementType.Char, true) },\n\t\t\t\t{ \"SByte\", new Row<ElementType, bool> (ElementType.I1, true) },\n\t\t\t\t{ \"Byte\", new Row<ElementType, bool> (ElementType.U1, true) },\n\t\t\t\t{ \"Int16\", new Row<ElementType, bool> (ElementType.I2, true) },\n\t\t\t\t{ \"UInt16\", new Row<ElementType, bool> (ElementType.U2, true) },\n\t\t\t\t{ \"Int32\", new Row<ElementType, bool> (ElementType.I4, true) },\n\t\t\t\t{ \"UInt32\", new Row<ElementType, bool> (ElementType.U4, true) },\n\t\t\t\t{ \"Int64\", new Row<ElementType, bool> (ElementType.I8, true) },\n\t\t\t\t{ \"UInt64\", new Row<ElementType, bool> (ElementType.U8, true) },\n\t\t\t\t{ \"Single\", new Row<ElementType, bool> (ElementType.R4, true) },\n\t\t\t\t{ \"Double\", new Row<ElementType, bool> (ElementType.R8, true) },\n\t\t\t\t{ \"String\", new Row<ElementType, bool> (ElementType.String, false) },\n\t\t\t\t{ \"TypedReference\", new Row<ElementType, bool> (ElementType.TypedByRef, false) },\n\t\t\t\t{ \"IntPtr\", new Row<ElementType, bool> (ElementType.I, true) },\n\t\t\t\t{ \"UIntPtr\", new Row<ElementType, bool> (ElementType.U, true) },\n\t\t\t\t{ \"Object\", new Row<ElementType, bool> (ElementType.Object, false) },\n\t\t\t};\n\t\t}\n\n\t\tpublic static void TryProcessPrimitiveTypeReference (TypeReference type)\n\t\t{\n\t\t\tif (type.Namespace != \"System\")\n\t\t\t\treturn;\n\n\t\t\tvar scope = type.scope;\n\t\t\tif (scope == null || scope.MetadataScopeType != MetadataScopeType.AssemblyNameReference)\n\t\t\t\treturn;\n\n\t\t\tRow<ElementType, bool> primitive_data;\n\t\t\tif (!TryGetPrimitiveData (type, out primitive_data))\n\t\t\t\treturn;\n\n\t\t\ttype.etype = primitive_data.Col1;\n\t\t\ttype.IsValueType = primitive_data.Col2;\n\t\t}\n\n\t\tpublic static bool TryGetPrimitiveElementType (TypeDefinition type, out ElementType etype)\n\t\t{\n\t\t\tetype = ElementType.None;\n\n\t\t\tif (type.Namespace != \"System\")\n\t\t\t\treturn false;\n\n\t\t\tRow<ElementType, bool> primitive_data;\n\t\t\tif (TryGetPrimitiveData (type, out primitive_data) &&Mixin .IsPrimitive (primitive_data.Col1)) {\n\t\t\t\tetype = primitive_data.Col1;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tstatic bool TryGetPrimitiveData (TypeReference type, out Row<ElementType, bool> primitive_data)\n\t\t{\n\t\t\tif (primitive_value_types == null)\n\t\t\t\tInitializePrimitives ();\n\n\t\t\treturn primitive_value_types.TryGetValue (type.Name, out primitive_data);\n\t\t}\n\n\t\tpublic void Clear ()\n\t\t{\n\t\t\tif (NestedTypes != null) NestedTypes.Clear ();\n\t\t\tif (ReverseNestedTypes != null) ReverseNestedTypes.Clear ();\n\t\t\tif (Interfaces != null) Interfaces.Clear ();\n\t\t\tif (ClassLayouts != null) ClassLayouts.Clear ();\n\t\t\tif (FieldLayouts != null) FieldLayouts.Clear ();\n\t\t\tif (FieldRVAs != null) FieldRVAs.Clear ();\n\t\t\tif (FieldMarshals != null) FieldMarshals.Clear ();\n\t\t\tif (Constants != null) Constants.Clear ();\n\t\t\tif (Overrides != null) Overrides.Clear ();\n\t\t\tif (CustomAttributes != null) CustomAttributes.Clear ();\n\t\t\tif (SecurityDeclarations != null) SecurityDeclarations.Clear ();\n\t\t\tif (Events != null) Events.Clear ();\n\t\t\tif (Properties != null) Properties.Clear ();\n\t\t\tif (Semantics != null) Semantics.Clear ();\n\t\t\tif (PInvokes != null) PInvokes.Clear ();\n\t\t\tif (GenericParameters != null) GenericParameters.Clear ();\n\t\t\tif (GenericConstraints != null) GenericConstraints.Clear ();\n\t\t}\n\n\t\tpublic TypeDefinition GetTypeDefinition (uint rid)\n\t\t{\n\t\t\tif (rid < 1 || rid > Types.Length)\n\t\t\t\treturn null;\n\n\t\t\treturn Types [rid - 1];\n\t\t}\n\n\t\tpublic void AddTypeDefinition (TypeDefinition type)\n\t\t{\n\t\t\tTypes [type.token.RID - 1] = type;\n\t\t}\n\n\t\tpublic TypeReference GetTypeReference (uint rid)\n\t\t{\n\t\t\tif (rid < 1 || rid > TypeReferences.Length)\n\t\t\t\treturn null;\n\n\t\t\treturn TypeReferences [rid - 1];\n\t\t}\n\n\t\tpublic void AddTypeReference (TypeReference type)\n\t\t{\n\t\t\tTypeReferences [type.token.RID - 1] = type;\n\t\t}\n\n\t\tpublic FieldDefinition GetFieldDefinition (uint rid)\n\t\t{\n\t\t\tif (rid < 1 || rid > Fields.Length)\n\t\t\t\treturn null;\n\n\t\t\treturn Fields [rid - 1];\n\t\t}\n\n\t\tpublic void AddFieldDefinition (FieldDefinition field)\n\t\t{\n\t\t\tFields [field.token.RID - 1] = field;\n\t\t}\n\n\t\tpublic MethodDefinition GetMethodDefinition (uint rid)\n\t\t{\n\t\t\tif (rid < 1 || rid > Methods.Length)\n\t\t\t\treturn null;\n\n\t\t\treturn Methods [rid - 1];\n\t\t}\n\n\t\tpublic void AddMethodDefinition (MethodDefinition method)\n\t\t{\n\t\t\tMethods [method.token.RID - 1] = method;\n\t\t}\n\n\t\tpublic MemberReference GetMemberReference (uint rid)\n\t\t{\n\t\t\tif (rid < 1 || rid > MemberReferences.Length)\n\t\t\t\treturn null;\n\n\t\t\treturn MemberReferences [rid - 1];\n\t\t}\n\n\t\tpublic void AddMemberReference (MemberReference member)\n\t\t{\n\t\t\tMemberReferences [member.token.RID - 1] = member;\n\t\t}\n\n\t\tpublic bool TryGetNestedTypeMapping (TypeDefinition type, out uint [] mapping)\n\t\t{\n\t\t\treturn NestedTypes.TryGetValue (type.token.RID, out mapping);\n\t\t}\n\n\t\tpublic void SetNestedTypeMapping (uint type_rid, uint [] mapping)\n\t\t{\n\t\t\tNestedTypes [type_rid] = mapping;\n\t\t}\n\n\t\tpublic void RemoveNestedTypeMapping (TypeDefinition type)\n\t\t{\n\t\t\tNestedTypes.Remove (type.token.RID);\n\t\t}\n\n\t\tpublic bool TryGetReverseNestedTypeMapping (TypeDefinition type, out uint declaring)\n\t\t{\n\t\t\treturn ReverseNestedTypes.TryGetValue (type.token.RID, out declaring);\n\t\t}\n\n\t\tpublic void SetReverseNestedTypeMapping (uint nested, uint declaring)\n\t\t{\n\t\t\tReverseNestedTypes.Add (nested, declaring);\n\t\t}\n\n\t\tpublic void RemoveReverseNestedTypeMapping (TypeDefinition type)\n\t\t{\n\t\t\tReverseNestedTypes.Remove (type.token.RID);\n\t\t}\n\n\t\tpublic bool TryGetInterfaceMapping (TypeDefinition type, out MetadataToken [] mapping)\n\t\t{\n\t\t\treturn Interfaces.TryGetValue (type.token.RID, out mapping);\n\t\t}\n\n\t\tpublic void SetInterfaceMapping (uint type_rid, MetadataToken [] mapping)\n\t\t{\n\t\t\tInterfaces [type_rid] = mapping;\n\t\t}\n\n\t\tpublic void RemoveInterfaceMapping (TypeDefinition type)\n\t\t{\n\t\t\tInterfaces.Remove (type.token.RID);\n\t\t}\n\n\t\tpublic void AddPropertiesRange (uint type_rid, Range range)\n\t\t{\n\t\t\tProperties.Add (type_rid, range);\n\t\t}\n\n\t\tpublic bool TryGetPropertiesRange (TypeDefinition type, out Range range)\n\t\t{\n\t\t\treturn Properties.TryGetValue (type.token.RID, out range);\n\t\t}\n\n\t\tpublic void RemovePropertiesRange (TypeDefinition type)\n\t\t{\n\t\t\tProperties.Remove (type.token.RID);\n\t\t}\n\n\t\tpublic void AddEventsRange (uint type_rid, Range range)\n\t\t{\n\t\t\tEvents.Add (type_rid, range);\n\t\t}\n\n\t\tpublic bool TryGetEventsRange (TypeDefinition type, out Range range)\n\t\t{\n\t\t\treturn Events.TryGetValue (type.token.RID, out range);\n\t\t}\n\n\t\tpublic void RemoveEventsRange (TypeDefinition type)\n\t\t{\n\t\t\tEvents.Remove (type.token.RID);\n\t\t}\n\n\t\tpublic bool TryGetGenericParameterRange (IGenericParameterProvider owner, out Range range)\n\t\t{\n\t\t\treturn GenericParameters.TryGetValue (owner.MetadataToken, out range);\n\t\t}\n\n\t\tpublic void RemoveGenericParameterRange (IGenericParameterProvider owner)\n\t\t{\n\t\t\tGenericParameters.Remove (owner.MetadataToken);\n\t\t}\n\n\t\tpublic bool TryGetCustomAttributeRange (ICustomAttributeProvider owner, out Range range)\n\t\t{\n\t\t\treturn CustomAttributes.TryGetValue (owner.MetadataToken, out range);\n\t\t}\n\n\t\tpublic void RemoveCustomAttributeRange (ICustomAttributeProvider owner)\n\t\t{\n\t\t\tCustomAttributes.Remove (owner.MetadataToken);\n\t\t}\n\n\t\tpublic bool TryGetSecurityDeclarationRange (ISecurityDeclarationProvider owner, out Range range)\n\t\t{\n\t\t\treturn SecurityDeclarations.TryGetValue (owner.MetadataToken, out range);\n\t\t}\n\n\t\tpublic void RemoveSecurityDeclarationRange (ISecurityDeclarationProvider owner)\n\t\t{\n\t\t\tSecurityDeclarations.Remove (owner.MetadataToken);\n\t\t}\n\n\t\tpublic bool TryGetGenericConstraintMapping (GenericParameter generic_parameter, out MetadataToken [] mapping)\n\t\t{\n\t\t\treturn GenericConstraints.TryGetValue (generic_parameter.token.RID, out mapping);\n\t\t}\n\n\t\tpublic void SetGenericConstraintMapping (uint gp_rid, MetadataToken [] mapping)\n\t\t{\n\t\t\tGenericConstraints [gp_rid] = mapping;\n\t\t}\n\n\t\tpublic void RemoveGenericConstraintMapping (GenericParameter generic_parameter)\n\t\t{\n\t\t\tGenericConstraints.Remove (generic_parameter.token.RID);\n\t\t}\n\n\t\tpublic bool TryGetOverrideMapping (MethodDefinition method, out MetadataToken [] mapping)\n\t\t{\n\t\t\treturn Overrides.TryGetValue (method.token.RID, out mapping);\n\t\t}\n\n\t\tpublic void SetOverrideMapping (uint rid, MetadataToken [] mapping)\n\t\t{\n\t\t\tOverrides [rid] = mapping;\n\t\t}\n\n\t\tpublic void RemoveOverrideMapping (MethodDefinition method)\n\t\t{\n\t\t\tOverrides.Remove (method.token.RID);\n\t\t}\n\n\t\tpublic TypeDefinition GetFieldDeclaringType (uint field_rid)\n\t\t{\n\t\t\treturn BinaryRangeSearch (Types, field_rid, true);\n\t\t}\n\n\t\tpublic TypeDefinition GetMethodDeclaringType (uint method_rid)\n\t\t{\n\t\t\treturn BinaryRangeSearch (Types, method_rid, false);\n\t\t}\n\n\t\tstatic TypeDefinition BinaryRangeSearch (TypeDefinition [] types, uint rid, bool field)\n\t\t{\n\t\t\tint min = 0;\n\t\t\tint max = types.Length - 1;\n\t\t\twhile (min <= max) {\n\t\t\t\tint mid = min + ((max - min) / 2);\n\t\t\t\tvar type = types [mid];\n\t\t\t\tvar range = field ? type.fields_range : type.methods_range;\n\n\t\t\t\tif (rid < range.Start)\n\t\t\t\t\tmax = mid - 1;\n\t\t\t\telse if (rid >= range.Start + range.Length)\n\t\t\t\t\tmin = mid + 1;\n\t\t\t\telse\n\t\t\t\t\treturn type;\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodAttributes.cs",
    "content": "//\n// MethodAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum MethodAttributes : ushort {\n\t\tMemberAccessMask\t= 0x0007,\n\t\tCompilerControlled\t= 0x0000,\t// Member not referenceable\n\t\tPrivate\t\t\t\t= 0x0001,\t// Accessible only by the parent type\n\t\tFamANDAssem\t\t\t= 0x0002,\t// Accessible by sub-types only in this Assembly\n\t\tAssembly\t\t\t= 0x0003,\t// Accessibly by anyone in the Assembly\n\t\tFamily\t\t\t\t= 0x0004,\t// Accessible only by type and sub-types\n\t\tFamORAssem\t\t\t= 0x0005,\t// Accessibly by sub-types anywhere, plus anyone in assembly\n\t\tPublic\t\t\t\t= 0x0006,\t// Accessibly by anyone who has visibility to this scope\n\n\t\tStatic\t\t\t\t= 0x0010,\t// Defined on type, else per instance\n\t\tFinal\t\t\t\t= 0x0020,\t// Method may not be overridden\n\t\tVirtual\t\t\t\t= 0x0040,\t// Method is virtual\n\t\tHideBySig\t\t\t= 0x0080,\t// Method hides by name+sig, else just by name\n\n\t\tVtableLayoutMask\t= 0x0100,\t// Use this mask to retrieve vtable attributes\n\t\tReuseSlot\t\t\t= 0x0000,\t// Method reuses existing slot in vtable\n\t\tNewSlot\t\t\t\t= 0x0100,\t// Method always gets a new slot in the vtable\n\n\t\tCheckAccessOnOverride = 0x0200,   // Method can only be overriden if also accessible\n\t\tAbstract\t\t\t= 0x0400,\t// Method does not provide an implementation\n\t\tSpecialName\t\t\t= 0x0800,\t// Method is special\n\n\t\t// Interop Attributes\n\t\tPInvokeImpl\t\t\t= 0x2000,\t// Implementation is forwarded through PInvoke\n\t\tUnmanagedExport\t\t= 0x0008,\t// Reserved: shall be zero for conforming implementations\n\n\t\t// Additional flags\n\t\tRTSpecialName\t\t= 0x1000,\t// CLI provides 'special' behavior, depending upon the name of the method\n\t\tHasSecurity\t\t\t= 0x4000,\t// Method has security associate with it\n\t\tRequireSecObject\t= 0x8000\t // Method calls another method containing security code\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodCallingConvention.cs",
    "content": "//\n// MethodCallingConvention.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum MethodCallingConvention : byte {\n\t\tDefault\t\t= 0x0,\n\t\tC\t\t\t= 0x1,\n\t\tStdCall\t\t= 0x2,\n\t\tThisCall\t= 0x3,\n\t\tFastCall\t= 0x4,\n\t\tVarArg\t\t= 0x5,\n\t\tGeneric\t\t= 0x10,\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodDefinition.cs",
    "content": "//\n// MethodDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Cecil.Cil;\nusing Mono.Collections.Generic;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class MethodDefinition : MethodReference, IMemberDefinition, ISecurityDeclarationProvider\n    {\n\n        ushort attributes;\n        ushort impl_attributes;\n        internal volatile bool sem_attrs_ready;\n        internal MethodSemanticsAttributes sem_attrs;\n        Collection<CustomAttribute> custom_attributes;\n        Collection<SecurityDeclaration> security_declarations;\n\n        internal RVA rva;\n        internal PInvokeInfo pinvoke;\n        Collection<MethodReference> overrides;\n\n        internal MethodBody body;\n\n        public MethodAttributes Attributes\n        {\n            get { return (MethodAttributes)attributes; }\n            set { attributes = (ushort)value; }\n        }\n\n        public MethodImplAttributes ImplAttributes\n        {\n            get { return (MethodImplAttributes)impl_attributes; }\n            set { impl_attributes = (ushort)value; }\n        }\n\n        public MethodSemanticsAttributes SemanticsAttributes\n        {\n            get\n            {\n                if (sem_attrs_ready)\n                    return sem_attrs;\n\n                if (HasImage)\n                {\n                    ReadSemantics();\n                    return sem_attrs;\n                }\n\n                sem_attrs = MethodSemanticsAttributes.None;\n                sem_attrs_ready = true;\n                return sem_attrs;\n            }\n            set { sem_attrs = value; }\n        }\n\n        internal void ReadSemantics()\n        {\n            if (sem_attrs_ready)\n                return;\n\n            var module = this.Module;\n            if (module == null)\n                return;\n\n            if (!module.HasImage)\n                return;\n\n            module.Read(this, (method, reader) => reader.ReadAllSemantics(method));\n        }\n\n        public bool HasSecurityDeclarations\n        {\n            get\n            {\n                if (security_declarations != null)\n                    return security_declarations.Count > 0;\n\n                return Mixin.GetHasSecurityDeclarations(this, Module);\n            }\n        }\n\n        public Collection<SecurityDeclaration> SecurityDeclarations\n        {\n            get { return security_declarations ?? (Mixin.GetSecurityDeclarations(this, ref security_declarations, Module)); }\n        }\n\n        public bool HasCustomAttributes\n        {\n            get\n            {\n                if (custom_attributes != null)\n                    return custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n            }\n        }\n\n        public Collection<CustomAttribute> CustomAttributes\n        {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n        }\n\n        public int RVA\n        {\n            get { return (int)rva; }\n        }\n\n        public bool HasBody\n        {\n            get\n            {\n                return (attributes & (ushort)MethodAttributes.Abstract) == 0 &&\n                    (attributes & (ushort)MethodAttributes.PInvokeImpl) == 0 &&\n                    (impl_attributes & (ushort)MethodImplAttributes.InternalCall) == 0 &&\n                    (impl_attributes & (ushort)MethodImplAttributes.Native) == 0 &&\n                    (impl_attributes & (ushort)MethodImplAttributes.Unmanaged) == 0 &&\n                    (impl_attributes & (ushort)MethodImplAttributes.Runtime) == 0;\n            }\n        }\n\n        public MethodBody Body\n        {\n            get\n            {\n                MethodBody localBody = this.body;\n                if (localBody != null)\n                    return localBody;\n\n                if (!HasBody)\n                    return null;\n\n                if (HasImage && rva != 0)\n                    return Module.Read(ref body, this, (method, reader) => reader.ReadMethodBody(method));\n\n                return body = new MethodBody(this);\n            }\n            set\n            {\n                // we reset Body to null in ILSpy to save memory; so we need that operation to be thread-safe\n                lock (Module.SyncRoot)\n                {\n                    body = value;\n                }\n            }\n        }\n\n        public bool HasPInvokeInfo\n        {\n            get\n            {\n                if (pinvoke != null)\n                    return true;\n\n                return IsPInvokeImpl;\n            }\n        }\n\n        public PInvokeInfo PInvokeInfo\n        {\n            get\n            {\n                if (pinvoke != null)\n                    return pinvoke;\n\n                if (HasImage && IsPInvokeImpl)\n                    return Module.Read(ref pinvoke, this, (method, reader) => reader.ReadPInvokeInfo(method));\n\n                return null;\n            }\n            set\n            {\n                IsPInvokeImpl = true;\n                pinvoke = value;\n            }\n        }\n\n        public bool HasOverrides\n        {\n            get\n            {\n                if (overrides != null)\n                    return overrides.Count > 0;\n\n                if (HasImage)\n                    return Module.Read(this, (method, reader) => reader.HasOverrides(method));\n\n                return false;\n            }\n        }\n\n        public Collection<MethodReference> Overrides\n        {\n            get\n            {\n                if (overrides != null)\n                    return overrides;\n\n                if (HasImage)\n                    return Module.Read(ref overrides, this, (method, reader) => reader.ReadOverrides(method));\n\n                return overrides = new Collection<MethodReference>();\n            }\n        }\n\n        public override bool HasGenericParameters\n        {\n            get\n            {\n                if (generic_parameters != null)\n                    return generic_parameters.Count > 0;\n\n                return Mixin.GetHasGenericParameters(this, Module);\n            }\n        }\n\n        public override Collection<GenericParameter> GenericParameters\n        {\n            get { return generic_parameters ?? (Mixin.GetGenericParameters(this, ref generic_parameters, Module)); }\n        }\n\n        #region MethodAttributes\n\n        public bool IsCompilerControlled\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.CompilerControlled); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.CompilerControlled, value); }\n        }\n\n        public bool IsPrivate\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Private); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Private, value); }\n        }\n\n        public bool IsFamilyAndAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamANDAssem); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamANDAssem, value); }\n        }\n\n        public bool IsAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Assembly); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Assembly, value); }\n        }\n\n        public bool IsFamily\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Family); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Family, value); }\n        }\n\n        public bool IsFamilyOrAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamORAssem); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamORAssem, value); }\n        }\n\n        public bool IsPublic\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Public); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Public, value); }\n        }\n\n        public bool IsStatic\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Static); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Static, value); }\n        }\n\n        public bool IsFinal\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Final); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Final, value); }\n        }\n\n        public bool IsVirtual\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Virtual); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Virtual, value); }\n        }\n\n        public bool IsHideBySig\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.HideBySig); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.HideBySig, value); }\n        }\n\n        public bool IsReuseSlot\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.ReuseSlot); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.ReuseSlot, value); }\n        }\n\n        public bool IsNewSlot\n        {\n            get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.NewSlot); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.NewSlot, value); }\n        }\n\n        public bool IsCheckAccessOnOverride\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.CheckAccessOnOverride); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.CheckAccessOnOverride, value); }\n        }\n\n        public bool IsAbstract\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Abstract); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Abstract, value); }\n        }\n\n        public bool IsSpecialName\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.SpecialName); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.SpecialName, value); }\n        }\n\n        public bool IsPInvokeImpl\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.PInvokeImpl); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.PInvokeImpl, value); }\n        }\n\n        public bool IsUnmanagedExport\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.UnmanagedExport); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.UnmanagedExport, value); }\n        }\n\n        public bool IsRuntimeSpecialName\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.RTSpecialName); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.RTSpecialName, value); }\n        }\n\n        public bool HasSecurity\n        {\n            get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.HasSecurity); }\n            set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.HasSecurity, value); }\n        }\n\n        #endregion\n\n        #region MethodImplAttributes\n\n        public bool IsIL\n        {\n            get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.IL); }\n            set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.IL, value); }\n        }\n\n        public bool IsNative\n        {\n            get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Native); }\n            set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Native, value); }\n        }\n\n        public bool IsRuntime\n        {\n            get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Runtime); }\n            set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Runtime, value); }\n        }\n\n        public bool IsUnmanaged\n        {\n            get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Unmanaged); }\n            set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Unmanaged, value); }\n        }\n\n        public bool IsManaged\n        {\n            get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Managed); }\n            set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Managed, value); }\n        }\n\n        public bool IsForwardRef\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.ForwardRef); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.ForwardRef, value); }\n        }\n\n        public bool IsPreserveSig\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.PreserveSig); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.PreserveSig, value); }\n        }\n\n        public bool IsInternalCall\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.InternalCall); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.InternalCall, value); }\n        }\n\n        public bool IsSynchronized\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.Synchronized); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.Synchronized, value); }\n        }\n\n        public bool NoInlining\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.NoInlining); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.NoInlining, value); }\n        }\n\n        public bool NoOptimization\n        {\n            get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.NoOptimization); }\n            set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.NoOptimization, value); }\n        }\n\n        #endregion\n\n        #region MethodSemanticsAttributes\n\n        public bool IsSetter\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Setter); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Setter, value); }\n        }\n\n        public bool IsGetter\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Getter); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Getter, value); }\n        }\n\n        public bool IsOther\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Other); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Other, value); }\n        }\n\n        public bool IsAddOn\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.AddOn); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.AddOn, value); }\n        }\n\n        public bool IsRemoveOn\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.RemoveOn); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.RemoveOn, value); }\n        }\n\n        public bool IsFire\n        {\n            get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Fire); }\n            set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Fire, value); }\n        }\n\n        #endregion\n\n        public new TypeDefinition DeclaringType\n        {\n            get { return (TypeDefinition)base.DeclaringType; }\n            set { base.DeclaringType = value; }\n        }\n\n        public bool IsConstructor\n        {\n            get\n            {\n                return this.IsRuntimeSpecialName\n                    && this.IsSpecialName\n                    && (this.Name == \".cctor\" || this.Name == \".ctor\");\n            }\n        }\n\n        public override bool IsDefinition\n        {\n            get { return true; }\n        }\n\n        internal MethodDefinition()\n        {\n            this.token = new MetadataToken(TokenType.Method);\n        }\n\n        public MethodDefinition(string name, MethodAttributes attributes, TypeReference returnType)\n            : base(name, returnType)\n        {\n            this.attributes = (ushort)attributes;\n            this.HasThis = !this.IsStatic;\n            this.token = new MetadataToken(TokenType.Method);\n        }\n\n        public override MethodDefinition Resolve()\n        {\n            return this;\n        }\n    }\n\n    static partial class Mixin\n    {\n\n        public static ParameterDefinition GetParameter(MethodBody self, int index)\n        {\n            var method = self.method;\n\n            if (method.HasThis)\n            {\n                if (index == 0)\n                    return self.ThisParameter;\n\n                index--;\n            }\n\n            var parameters = method.Parameters;\n\n            if (index < 0 || index >= parameters.size)\n                return null;\n\n            return parameters[index];\n        }\n\n        public static VariableDefinition GetVariable(MethodBody self, int index)\n        {\n            var variables = self.Variables;\n\n            if (index < 0 || index >= variables.size)\n                return null;\n\n            return variables[index];\n        }\n\n        public static bool GetSemantics(MethodDefinition self, MethodSemanticsAttributes semantics)\n        {\n            return (self.SemanticsAttributes & semantics) != 0;\n        }\n\n        public static void SetSemantics(MethodDefinition self, MethodSemanticsAttributes semantics, bool value)\n        {\n            if (value)\n                self.SemanticsAttributes |= semantics;\n            else\n                self.SemanticsAttributes &= ~semantics;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodImplAttributes.cs",
    "content": "//\n// MethodImplAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum MethodImplAttributes : ushort {\n\t\tCodeTypeMask\t\t= 0x0003,\n\t\tIL\t\t\t\t\t= 0x0000,\t// Method impl is CIL\n\t\tNative\t\t\t\t= 0x0001,\t// Method impl is native\n\t\tOPTIL\t\t\t\t= 0x0002,\t// Reserved: shall be zero in conforming implementations\n\t\tRuntime\t\t\t\t= 0x0003,\t// Method impl is provided by the runtime\n\n\t\tManagedMask\t\t\t= 0x0004,\t// Flags specifying whether the code is managed or unmanaged\n\t\tUnmanaged\t\t\t= 0x0004,\t// Method impl is unmanaged, otherwise managed\n\t\tManaged\t\t\t\t= 0x0000,\t// Method impl is managed\n\n\t\t// Implementation info and interop\n\t\tForwardRef\t\t\t= 0x0010,\t// Indicates method is defined; used primarily in merge scenarios\n\t\tPreserveSig\t\t\t= 0x0080,\t// Reserved: conforming implementations may ignore\n\t\tInternalCall\t\t= 0x1000,\t// Reserved: shall be zero in conforming implementations\n\t\tSynchronized\t\t= 0x0020,\t// Method is single threaded through the body\n\t\tNoOptimization\t\t= 0x0040,\t// Method is not optimized by the JIT.\n\t\tNoInlining\t\t\t= 0x0008,\t// Method may not be inlined\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodReference.cs",
    "content": "//\n// MethodReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public class MethodReference : MemberReference, IMethodSignature, IGenericParameterProvider, IGenericContext\n    {\n        int hashCode = -1;\n        static int instance_id;\n        internal ParameterDefinitionCollection parameters;\n        MethodReturnType return_type;\n\n        bool has_this;\n        bool explicit_this;\n        MethodCallingConvention calling_convention;\n        internal Collection<GenericParameter> generic_parameters;\n\n        public virtual bool HasThis\n        {\n            get { return has_this; }\n            set { has_this = value; }\n        }\n\n        public virtual bool ExplicitThis\n        {\n            get { return explicit_this; }\n            set { explicit_this = value; }\n        }\n\n        public virtual MethodCallingConvention CallingConvention\n        {\n            get { return calling_convention; }\n            set { calling_convention = value; }\n        }\n\n        public virtual bool HasParameters\n        {\n            get { return !Mixin.IsNullOrEmpty(parameters); }\n        }\n\n        public virtual Collection<ParameterDefinition> Parameters\n        {\n            get\n            {\n                if (parameters == null)\n                    parameters = new ParameterDefinitionCollection(this);\n\n                return parameters;\n            }\n        }\n\n        IGenericParameterProvider IGenericContext.Type\n        {\n            get\n            {\n                var declaring_type = this.DeclaringType;\n                var instance = declaring_type as GenericInstanceType;\n                if (instance != null)\n                    return instance.ElementType;\n\n                return declaring_type;\n            }\n        }\n\n        IGenericParameterProvider IGenericContext.Method\n        {\n            get { return this; }\n        }\n\n        GenericParameterType IGenericParameterProvider.GenericParameterType\n        {\n            get { return GenericParameterType.Method; }\n        }\n\n        public virtual bool HasGenericParameters\n        {\n            get { return !Mixin.IsNullOrEmpty(generic_parameters); }\n        }\n\n        public virtual Collection<GenericParameter> GenericParameters\n        {\n            get\n            {\n                if (generic_parameters != null)\n                    return generic_parameters;\n\n                return generic_parameters = new GenericParameterCollection(this);\n            }\n        }\n\n        public TypeReference ReturnType\n        {\n            get\n            {\n                var return_type = MethodReturnType;\n                return return_type != null ? return_type.ReturnType : null;\n            }\n            set\n            {\n                var return_type = MethodReturnType;\n                if (return_type != null)\n                    return_type.ReturnType = value;\n            }\n        }\n\n        public virtual MethodReturnType MethodReturnType\n        {\n            get { return return_type; }\n            set { return_type = value; }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                var builder = new StringBuilder();\n                builder.Append(ReturnType.FullName)\n                    .Append(\" \")\n                    .Append(MemberFullName());\n                Mixin.MethodSignatureFullName(this, builder);\n                return builder.ToString();\n            }\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n\n        public virtual bool IsGenericInstance\n        {\n            get { return false; }\n        }\n\n        internal override bool ContainsGenericParameter\n        {\n            get\n            {\n                if (this.ReturnType.ContainsGenericParameter || base.ContainsGenericParameter)\n                    return true;\n\n                var parameters = this.Parameters;\n\n                for (int i = 0; i < parameters.Count; i++)\n                    if (parameters[i].ParameterType.ContainsGenericParameter)\n                        return true;\n\n                return false;\n            }\n        }\n\n        internal MethodReference()\n        {\n            this.return_type = new MethodReturnType(this);\n            this.token = new MetadataToken(TokenType.MemberRef);\n        }\n\n        public MethodReference(string name, TypeReference returnType)\n            : base(name)\n        {\n            if (returnType == null)\n                throw new ArgumentNullException(\"returnType\");\n\n            this.return_type = new MethodReturnType(this);\n            this.return_type.ReturnType = returnType;\n            this.token = new MetadataToken(TokenType.MemberRef);\n        }\n\n        public MethodReference(string name, TypeReference returnType, TypeReference declaringType)\n            : this(name, returnType)\n        {\n            if (declaringType == null)\n                throw new ArgumentNullException(\"declaringType\");\n\n            this.DeclaringType = declaringType;\n        }\n\n        public virtual MethodReference GetElementMethod()\n        {\n            return this;\n        }\n\n        public virtual MethodDefinition Resolve()\n        {\n            var module = this.Module;\n            if (module == null)\n                throw new NotSupportedException();\n\n            return module.Resolve(this);\n        }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool IsVarArg(IMethodSignature self)\n        {\n            return (self.CallingConvention & MethodCallingConvention.VarArg) != 0;\n        }\n\n        public static int GetSentinelPosition(IMethodSignature self)\n        {\n            if (!self.HasParameters)\n                return -1;\n\n            var parameters = self.Parameters;\n            for (int i = 0; i < parameters.Count; i++)\n                if (parameters[i].ParameterType.IsSentinel)\n                    return i;\n\n            return -1;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodReturnType.cs",
    "content": "//\n// MethodReturnType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.Threading;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class MethodReturnType : IConstantProvider, ICustomAttributeProvider, IMarshalInfoProvider {\n\n\t\tinternal IMethodSignature method;\n\t\tinternal ParameterDefinition parameter;\n\t\tTypeReference return_type;\n\n\t\tpublic IMethodSignature Method {\n\t\t\tget { return method; }\n\t\t}\n\n\t\tpublic TypeReference ReturnType {\n\t\t\tget { return return_type; }\n\t\t\tset { return_type = value; }\n\t\t}\n\n\t\tinternal ParameterDefinition Parameter {\n\t\t\tget {\n\t\t\t\tif (parameter == null)\n                    parameter=new ParameterDefinition (return_type, method);\n\n\t\t\t\treturn parameter;\n\t\t\t}\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return Parameter.MetadataToken; }\n\t\t\tset { Parameter.MetadataToken = value; }\n\t\t}\n\n\t\tpublic ParameterAttributes Attributes {\n\t\t\tget { return Parameter.Attributes; }\n\t\t\tset { Parameter.Attributes = value; }\n\t\t}\n\n\t\tpublic bool HasCustomAttributes {\n\t\t\tget { return parameter != null && parameter.HasCustomAttributes; }\n\t\t}\n\n\t\tpublic Collection<CustomAttribute> CustomAttributes {\n\t\t\tget { return Parameter.CustomAttributes; }\n\t\t}\n\n\t\tpublic bool HasDefault {\n\t\t\tget { return parameter != null && parameter.HasDefault; }\n\t\t\tset { Parameter.HasDefault = value; }\n\t\t}\n\n\t\tpublic bool HasConstant {\n\t\t\tget { return parameter != null && parameter.HasConstant; }\n\t\t\tset { Parameter.HasConstant = value; }\n\t\t}\n\n\t\tpublic object Constant {\n\t\t\tget { return Parameter.Constant; }\n\t\t\tset { Parameter.Constant = value; }\n\t\t}\n\n\t\tpublic bool HasFieldMarshal {\n\t\t\tget { return parameter != null && parameter.HasFieldMarshal; }\n\t\t\tset { Parameter.HasFieldMarshal = value; }\n\t\t}\n\n\t\tpublic bool HasMarshalInfo {\n\t\t\tget { return parameter != null && parameter.HasMarshalInfo; }\n\t\t}\n\n\t\tpublic MarshalInfo MarshalInfo {\n\t\t\tget { return Parameter.MarshalInfo; }\n\t\t\tset { Parameter.MarshalInfo = value; }\n\t\t}\n\n\t\tpublic MethodReturnType (IMethodSignature method)\n\t\t{\n\t\t\tthis.method = method;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodSemanticsAttributes.cs",
    "content": "//\n// MethodSemanticsattributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum MethodSemanticsAttributes : ushort {\n\t\tNone\t\t= 0x0000,\n\t\tSetter\t\t= 0x0001,\t// Setter for property\n\t\tGetter\t\t= 0x0002,\t// Getter for property\n\t\tOther\t\t= 0x0004,\t// Other method for property or event\n\t\tAddOn\t\t= 0x0008,\t// AddOn method for event\n\t\tRemoveOn\t= 0x0010,\t// RemoveOn method for event\n\t\tFire\t\t= 0x0020\t // Fire method for event\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/MethodSpecification.cs",
    "content": "//\n// MethodSpecification.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class MethodSpecification : MethodReference {\n\n\t\treadonly MethodReference method;\n\n\t\tpublic MethodReference ElementMethod {\n\t\t\tget { return method; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return method.Name; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override MethodCallingConvention CallingConvention {\n\t\t\tget { return method.CallingConvention; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool HasThis {\n\t\t\tget { return method.HasThis; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool ExplicitThis {\n\t\t\tget { return method.ExplicitThis; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override MethodReturnType MethodReturnType {\n\t\t\tget { return method.MethodReturnType; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override TypeReference DeclaringType {\n\t\t\tget { return method.DeclaringType; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override ModuleDefinition Module {\n\t\t\tget { return method.Module; }\n\t\t}\n\n\t\tpublic override bool HasParameters {\n\t\t\tget { return method.HasParameters; }\n\t\t}\n\n\t\tpublic override Collection<ParameterDefinition> Parameters {\n\t\t\tget { return method.Parameters; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return method.ContainsGenericParameter; }\n\t\t}\n\n\t\tinternal MethodSpecification (MethodReference method)\n\t\t{\n\t\t\tif (method == null)\n\t\t\t\tthrow new ArgumentNullException (\"method\");\n\n\t\t\tthis.method = method;\n\t\t\tthis.token = new MetadataToken (TokenType.MethodSpec);\n\t\t}\n\n\t\tpublic sealed override MethodReference GetElementMethod ()\n\t\t{\n\t\t\treturn method.GetElementMethod ();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/Modifiers.cs",
    "content": "//\n// Modifiers.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic interface IModifierType {\n\t\tTypeReference ModifierType { get; }\n\t\tTypeReference ElementType { get; }\n\t}\n\n\tpublic sealed class OptionalModifierType : TypeSpecification, IModifierType {\n\n\t\tTypeReference modifier_type;\n\n\t\tpublic TypeReference ModifierType {\n\t\t\tget { return modifier_type; }\n\t\t\tset { modifier_type = value; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return base.Name + Suffix; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return base.FullName + Suffix; }\n\t\t}\n\n\t\tstring Suffix {\n\t\t\tget { return \" modopt(\" + modifier_type + \")\"; }\n\t\t}\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsOptionalModifier {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return modifier_type.ContainsGenericParameter || base.ContainsGenericParameter; }\n\t\t}\n\n\t\tpublic OptionalModifierType (TypeReference modifierType, TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckModifier (modifierType, type);\n\t\t\tthis.modifier_type = modifierType;\n\t\t\tthis.etype = MD.ElementType.CModOpt;\n\t\t}\n\t}\n\n\tpublic sealed class RequiredModifierType : TypeSpecification, IModifierType {\n\n\t\tTypeReference modifier_type;\n\n\t\tpublic TypeReference ModifierType {\n\t\t\tget { return modifier_type; }\n\t\t\tset { modifier_type = value; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return base.Name + Suffix; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return base.FullName + Suffix; }\n\t\t}\n\n\t\tstring Suffix {\n\t\t\tget { return \" modreq(\" + modifier_type + \")\"; }\n\t\t}\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsRequiredModifier {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return modifier_type.ContainsGenericParameter || base.ContainsGenericParameter; }\n\t\t}\n\n\t\tpublic RequiredModifierType (TypeReference modifierType, TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckModifier (modifierType, type);\n\t\t\tthis.modifier_type = modifierType;\n\t\t\tthis.etype = MD.ElementType.CModReqD;\n\t\t}\n\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic static void CheckModifier (TypeReference modifierType, TypeReference type)\n\t\t{\n\t\t\tif (modifierType == null)\n\t\t\t\tthrow new ArgumentNullException (\"modifierType\");\n\t\t\tif (type == null)\n\t\t\t\tthrow new ArgumentNullException (\"type\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ModuleDefinition.cs",
    "content": "//\n// ModuleDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading;\nusing SR = System.Reflection;\nusing Mono.Cecil.Cil;\nusing Mono.Cecil.Metadata;\nusing Mono.Cecil.PE;\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public enum ReadingMode\n    {\n        Immediate = 1,\n        Deferred = 2,\n    }\n\n    public sealed class ReaderParameters\n    {\n\n        ReadingMode reading_mode;\n        IAssemblyResolver assembly_resolver;\n        IMetadataResolver metadata_resolver;\n        Stream symbol_stream;\n        ISymbolReaderProvider symbol_reader_provider;\n        bool read_symbols;\n\n        public ReadingMode ReadingMode\n        {\n            get { return reading_mode; }\n            set { reading_mode = value; }\n        }\n\n        public IAssemblyResolver AssemblyResolver\n        {\n            get { return assembly_resolver; }\n            set { assembly_resolver = value; }\n        }\n\n        public IMetadataResolver MetadataResolver\n        {\n            get { return metadata_resolver; }\n            set { metadata_resolver = value; }\n        }\n\n        public Stream SymbolStream\n        {\n            get { return symbol_stream; }\n            set { symbol_stream = value; }\n        }\n\n        public ISymbolReaderProvider SymbolReaderProvider\n        {\n            get { return symbol_reader_provider; }\n            set { symbol_reader_provider = value; }\n        }\n\n        public bool ReadSymbols\n        {\n            get { return read_symbols; }\n            set { read_symbols = value; }\n        }\n\n        public ReaderParameters()\n            : this(ReadingMode.Deferred)\n        {\n        }\n\n        public ReaderParameters(ReadingMode readingMode)\n        {\n            this.reading_mode = readingMode;\n        }\n    }\n\n\n    public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider\n    {\n\n        internal Image Image;\n        internal MetadataSystem MetadataSystem;\n        internal ReadingMode ReadingMode;\n        internal ISymbolReaderProvider SymbolReaderProvider;\n\n        internal ISymbolReader symbol_reader;\n        internal IAssemblyResolver assembly_resolver;\n        internal IMetadataResolver metadata_resolver;\n        internal TypeSystem type_system;\n\n        readonly MetadataReader reader;\n        readonly string fq_name;\n\n        internal ModuleKind kind;\n        TargetRuntime runtime;\n        TargetArchitecture architecture;\n        ModuleAttributes attributes;\n        ModuleCharacteristics characteristics;\n        Guid mvid;\n\n        internal AssemblyDefinition assembly;\n        MethodDefinition entry_point;\n\n        Collection<CustomAttribute> custom_attributes;\n        Collection<AssemblyNameReference> references;\n        Collection<ModuleReference> modules;\n        Collection<Resource> resources;\n        Collection<ExportedType> exported_types;\n        TypeDefinitionCollection types;\n\n        public bool IsMain\n        {\n            get { return kind != ModuleKind.NetModule; }\n        }\n\n        public ModuleKind Kind\n        {\n            get { return kind; }\n            set { kind = value; }\n        }\n\n        public TargetRuntime Runtime\n        {\n            get { return runtime; }\n            set { runtime = value; }\n        }\n\n        public TargetArchitecture Architecture\n        {\n            get { return architecture; }\n            set { architecture = value; }\n        }\n\n        public ModuleAttributes Attributes\n        {\n            get { return attributes; }\n            set { attributes = value; }\n        }\n\n        public ModuleCharacteristics Characteristics\n        {\n            get { return characteristics; }\n            set { characteristics = value; }\n        }\n\n        public string FullyQualifiedName\n        {\n            get { return fq_name; }\n        }\n\n        public Guid Mvid\n        {\n            get { return mvid; }\n            set { mvid = value; }\n        }\n\n        internal bool HasImage\n        {\n            get { return Image != null; }\n        }\n\n        public bool HasSymbols\n        {\n            get { return symbol_reader != null; }\n        }\n\n        public ISymbolReader SymbolReader\n        {\n            get { return symbol_reader; }\n        }\n\n        public override MetadataScopeType MetadataScopeType\n        {\n            get { return MetadataScopeType.ModuleDefinition; }\n        }\n\n        public AssemblyDefinition Assembly\n        {\n            get { return assembly; }\n        }\n\n\n        public IAssemblyResolver AssemblyResolver\n        {\n            get { return assembly_resolver ?? (assembly_resolver = new DefaultAssemblyResolver()); }\n        }\n\n        public IMetadataResolver MetadataResolver\n        {\n            get\n            {\n                if (metadata_resolver == null)\n                    metadata_resolver=new MetadataResolver(this.AssemblyResolver);\n\n                return metadata_resolver;\n            }\n        }\n\n        public TypeSystem TypeSystem\n        {\n            get\n            {\n                if (type_system == null)\n                    type_system = TypeSystem.CreateTypeSystem(this);\n                return type_system;\n            }\n        }\n\n        public bool HasAssemblyReferences\n        {\n            get\n            {\n                if (references != null)\n                    return references.Count > 0;\n\n                return HasImage && Image.HasTable(Table.AssemblyRef);\n            }\n        }\n\n        public Collection<AssemblyNameReference> AssemblyReferences\n        {\n            get\n            {\n                if (references != null)\n                    return references;\n\n                if (HasImage)\n                    return Read(ref references, this, (_, reader) => reader.ReadAssemblyReferences());\n\n                return references = new Collection<AssemblyNameReference>();\n            }\n        }\n\n        public bool HasModuleReferences\n        {\n            get\n            {\n                if (modules != null)\n                    return modules.Count > 0;\n\n                return HasImage && Image.HasTable(Table.ModuleRef);\n            }\n        }\n\n        public Collection<ModuleReference> ModuleReferences\n        {\n            get\n            {\n                if (modules != null)\n                    return modules;\n\n                if (HasImage)\n                    return Read(ref modules, this, (_, reader) => reader.ReadModuleReferences());\n\n                return modules = new Collection<ModuleReference>();\n            }\n        }\n\n        public bool HasResources\n        {\n            get\n            {\n                if (resources != null)\n                    return resources.Count > 0;\n\n                if (HasImage)\n                    return Image.HasTable(Table.ManifestResource) || Read(this, (_, reader) => reader.HasFileResource());\n\n                return false;\n            }\n        }\n\n        public Collection<Resource> Resources\n        {\n            get\n            {\n                if (resources != null)\n                    return resources;\n\n                if (HasImage)\n                    return Read(ref resources, this, (_, reader) => reader.ReadResources());\n\n                return resources = new Collection<Resource>();\n            }\n        }\n\n        public bool HasCustomAttributes\n        {\n            get\n            {\n                if (custom_attributes != null)\n                    return custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, this);\n            }\n        }\n\n        public Collection<CustomAttribute> CustomAttributes\n        {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, this)); }\n        }\n\n        public bool HasTypes\n        {\n            get\n            {\n                if (types != null)\n                    return types.Count > 0;\n\n                return HasImage && Image.HasTable(Table.TypeDef);\n            }\n        }\n\n        public Collection<TypeDefinition> Types\n        {\n            get\n            {\n                if (types != null)\n                    return types;\n\n                if (HasImage)\n                    return Read(ref types, this, (_, reader) => reader.ReadTypes());\n\n                return types = new TypeDefinitionCollection(this);\n            }\n        }\n\n        public bool HasExportedTypes\n        {\n            get\n            {\n                if (exported_types != null)\n                    return exported_types.Count > 0;\n\n                return HasImage && Image.HasTable(Table.ExportedType);\n            }\n        }\n\n        public Collection<ExportedType> ExportedTypes\n        {\n            get\n            {\n                if (exported_types != null)\n                    return exported_types;\n\n                if (HasImage)\n                    return Read(ref exported_types, this, (_, reader) => reader.ReadExportedTypes());\n\n                return exported_types = new Collection<ExportedType>();\n            }\n        }\n\n        public MethodDefinition EntryPoint\n        {\n            get\n            {\n                if (entry_point != null)\n                    return entry_point;\n\n                if (HasImage)\n                    return Read(ref entry_point, this, (_, reader) => reader.ReadEntryPoint());\n\n                return entry_point = null;\n            }\n            set { entry_point = value; }\n        }\n\n        internal ModuleDefinition()\n        {\n            this.MetadataSystem = new MetadataSystem();\n            this.token = new MetadataToken(TokenType.Module, 1);\n        }\n\n        internal ModuleDefinition(Image image)\n            : this()\n        {\n            this.Image = image;\n            this.kind = image.Kind;\n            this.runtime = image.Runtime;\n            this.architecture = image.Architecture;\n            this.attributes = image.Attributes;\n            this.characteristics = image.Characteristics;\n            this.fq_name = image.FileName;\n\n            this.reader = new MetadataReader(this);\n        }\n\n        public bool HasTypeReference(string fullName)\n        {\n            return HasTypeReference(string.Empty, fullName);\n        }\n\n        public bool HasTypeReference(string scope, string fullName)\n        {\n            CheckFullName(fullName);\n\n            if (!HasImage)\n                return false;\n\n            return GetTypeReference(scope, fullName) != null;\n        }\n\n        public bool TryGetTypeReference(string fullName, out TypeReference type)\n        {\n            return TryGetTypeReference(string.Empty, fullName, out type);\n        }\n\n        public bool TryGetTypeReference(string scope, string fullName, out TypeReference type)\n        {\n            CheckFullName(fullName);\n\n            if (!HasImage)\n            {\n                type = null;\n                return false;\n            }\n\n            return (type = GetTypeReference(scope, fullName)) != null;\n        }\n\n        TypeReference GetTypeReference(string scope, string fullname)\n        {\n            return Read(new Row<string, string>(scope, fullname), (row, reader) => reader.GetTypeReference(row.Col1, row.Col2));\n        }\n\n        public IEnumerable<TypeReference> GetTypeReferences()\n        {\n            if (!HasImage)\n                return Empty<TypeReference>.Array;\n\n            return Read(this, (_, reader) => reader.GetTypeReferences());\n        }\n\n        public IEnumerable<MemberReference> GetMemberReferences()\n        {\n            if (!HasImage)\n                return Empty<MemberReference>.Array;\n\n            return Read(this, (_, reader) => reader.GetMemberReferences());\n        }\n\n        public TypeReference GetType(string fullName, bool runtimeName)\n        {\n            return runtimeName\n                ? TypeParser.ParseType(this, fullName)\n                : GetType(fullName);\n        }\n\n        public TypeDefinition GetType(string fullName)\n        {\n            CheckFullName(fullName);\n\n            var position = fullName.IndexOf('/');\n            if (position > 0)\n                return GetNestedType(fullName);\n\n            return ((TypeDefinitionCollection)this.Types).GetType(fullName);\n        }\n\n        public TypeDefinition GetType(string @namespace, string name)\n        {\n            Mixin.CheckName(name);\n\n            return ((TypeDefinitionCollection)this.Types).GetType(@namespace ?? string.Empty, name);\n        }\n\n        public IEnumerable<TypeDefinition> GetTypes()\n        {\n            return GetTypes(Types);\n        }\n\n        static IEnumerable<TypeDefinition> GetTypes(Collection<TypeDefinition> types)\n        {\n            for (int i = 0; i < types.Count; i++)\n            {\n                var type = types[i];\n\n                yield return type;\n\n                if (!type.HasNestedTypes)\n                    continue;\n\n                foreach (var nested in GetTypes(type.NestedTypes))\n                    yield return nested;\n            }\n        }\n\n        static void CheckFullName(string fullName)\n        {\n            if (fullName == null)\n                throw new ArgumentNullException(\"fullName\");\n            if (fullName.Length == 0)\n                throw new ArgumentException();\n        }\n\n        TypeDefinition GetNestedType(string fullname)\n        {\n            var names = fullname.Split('/');\n            var type = GetType(names[0]);\n\n            if (type == null)\n                return null;\n\n            for (int i = 1; i < names.Length; i++)\n            {\n                var nested_type = Mixin.GetNestedType(type, names[i]);\n                if (nested_type == null)\n                    return null;\n\n                type = nested_type;\n            }\n\n            return type;\n        }\n\n        internal FieldDefinition Resolve(FieldReference field)\n        {\n            return MetadataResolver.Resolve(field);\n        }\n\n        internal MethodDefinition Resolve(MethodReference method)\n        {\n            return MetadataResolver.Resolve(method);\n        }\n\n        internal TypeDefinition Resolve(TypeReference type)\n        {\n            return MetadataResolver.Resolve(type);\n        }\n\n\n        public IMetadataTokenProvider LookupToken(int token)\n        {\n            return LookupToken(new MetadataToken((uint)token));\n        }\n\n        public IMetadataTokenProvider LookupToken(MetadataToken token)\n        {\n            return Read(token, (t, reader) => reader.LookupToken(t));\n        }\n\n        readonly object module_lock = new object();\n\n        internal object SyncRoot\n        {\n            get { return module_lock; }\n        }\n\n        internal TRet Read<TItem, TRet>(TItem item, Func<TItem, MetadataReader, TRet> read)\n        {\n            lock (module_lock)\n            {\n                var position = reader.position;\n                var context = reader.context;\n\n                var ret = read(item, reader);\n\n                reader.position = position;\n                reader.context = context;\n\n                return ret;\n            }\n        }\n\n        internal TRet Read<TItem, TRet>(ref TRet variable, TItem item, Func<TItem, MetadataReader, TRet> read) where TRet : class\n        {\n            lock (module_lock)\n            {\n                if (variable != null)\n                    return variable;\n\n                var position = reader.position;\n                var context = reader.context;\n\n                var ret = read(item, reader);\n\n                reader.position = position;\n                reader.context = context;\n\n                return variable = ret;\n            }\n        }\n\n        public bool HasDebugHeader\n        {\n            get { return Image != null && !Image.Debug.IsZero; }\n        }\n\n        public ImageDebugDirectory GetDebugHeader(out byte[] header)\n        {\n            if (!HasDebugHeader)\n                throw new InvalidOperationException();\n\n            return Image.GetDebugHeader(out header);\n        }\n\n        void ProcessDebugHeader()\n        {\n            if (!HasDebugHeader)\n                return;\n\n            byte[] header;\n            var directory = GetDebugHeader(out header);\n\n            if (!symbol_reader.ProcessDebugHeader(directory, header))\n                throw new InvalidOperationException();\n        }\n\n\n\n        public void ReadSymbols()\n        {\n            if (string.IsNullOrEmpty(fq_name))\n                throw new InvalidOperationException();\n\n            var provider = SymbolProvider.GetPlatformReaderProvider();\n            if (provider == null)\n                throw new InvalidOperationException();\n\n            ReadSymbols(provider.GetSymbolReader(this, fq_name));\n        }\n\n        public void ReadSymbols(ISymbolReader reader)\n        {\n            if (reader == null)\n                throw new ArgumentNullException(\"reader\");\n\n            symbol_reader = reader;\n\n            ProcessDebugHeader();\n        }\n\n        public static ModuleDefinition ReadModule(string fileName)\n        {\n            return ReadModule(fileName, new ReaderParameters(ReadingMode.Deferred));\n        }\n\n        public static ModuleDefinition ReadModule(Stream stream)\n        {\n            return ReadModule(stream, new ReaderParameters(ReadingMode.Deferred));\n        }\n\n        public static ModuleDefinition ReadModule(string fileName, ReaderParameters parameters)\n        {\n            using (var stream = GetFileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))\n            {\n                return ReadModule(stream, parameters);\n            }\n        }\n\n        static void CheckStream(object stream)\n        {\n            if (stream == null)\n                throw new ArgumentNullException(\"stream\");\n        }\n\n        public static ModuleDefinition ReadModule(Stream stream, ReaderParameters parameters)\n        {\n            CheckStream(stream);\n            if (!stream.CanRead || !stream.CanSeek)\n                throw new ArgumentException();\n            Mixin.CheckParameters(parameters);\n\n            return ModuleReader.CreateModuleFrom(\n                ImageReader.ReadImageFrom(stream),\n                parameters);\n        }\n\n        static Stream GetFileStream(string fileName, FileMode mode, FileAccess access, FileShare share)\n        {\n            if (fileName == null)\n                throw new ArgumentNullException(\"fileName\");\n            if (fileName.Length == 0)\n                throw new ArgumentException();\n\n            return new FileStream(fileName, mode, access, share);\n        }\n\n\n\n    }\n\n    static partial class Mixin\n    {\n\n        public static void CheckParameters(object parameters)\n        {\n            if (parameters == null)\n                throw new ArgumentNullException(\"parameters\");\n        }\n\n        public static bool HasImage(ModuleDefinition self)\n        {\n            return self != null && self.HasImage;\n        }\n\n        public static bool IsCorlib(ModuleDefinition module)\n        {\n            if (module.Assembly == null)\n                return false;\n\n            return module.Assembly.Name.Name == \"mscorlib\";\n        }\n\n        public static string GetFullyQualifiedName(Stream self)\n        {\n\n            return string.Empty;\n        }\n\n        public static TargetRuntime ParseRuntime(string self)\n        {\n            switch (self[1])\n            {\n                case '1':\n                    return self[3] == '0'\n                        ? TargetRuntime.Net_1_0\n                        : TargetRuntime.Net_1_1;\n                case '2':\n                    return TargetRuntime.Net_2_0;\n                case '4':\n                default:\n                    return TargetRuntime.Net_4_0;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ModuleKind.cs",
    "content": "//\n// ModuleKind.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic enum ModuleKind {\n\t\tDll,\n\t\tConsole,\n\t\tWindows,\n\t\tNetModule,\n\t}\n\n\tpublic enum TargetArchitecture {\n\t\tI386,\n\t\tAMD64,\n\t\tIA64,\n\t\tARMv7,\n\t}\n\n\t[Flags]\n\tpublic enum ModuleAttributes {\n\t\tILOnly = 1,\n\t\tRequired32Bit = 2,\n\t\tStrongNameSigned = 8,\n\t\tPreferred32Bit = 0x00020000,\n\t}\n\n\t[Flags]\n\tpublic enum ModuleCharacteristics {\n\t\tHighEntropyVA = 0x0020,\n\t\tDynamicBase = 0x0040,\n\t\tNoSEH = 0x0400,\n\t\tNXCompat = 0x0100,\n\t\tAppContainer = 0x1000,\n\t\tTerminalServerAware = 0x8000,\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ModuleReference.cs",
    "content": "//\n// ModuleReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic class ModuleReference : IMetadataScope {\n\n\t\tstring name;\n\n\t\tinternal MetadataToken token;\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic virtual MetadataScopeType MetadataScopeType {\n\t\t\tget { return MetadataScopeType.ModuleReference; }\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return token; }\n\t\t\tset { token = value; }\n\t\t}\n\n\t\tinternal ModuleReference ()\n\t\t{\n\t\t\tthis.token = new MetadataToken (TokenType.ModuleRef);\n\t\t}\n\n\t\tpublic ModuleReference (string name)\n\t\t\t: this ()\n\t\t{\n\t\t\tthis.name = name;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn name;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/NativeType.cs",
    "content": "//\n// NativeType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum NativeType {\n\t\tNone = 0x66,\n\n\t\tBoolean = 0x02,\n\t\tI1 = 0x03,\n\t\tU1 = 0x04,\n\t\tI2 = 0x05,\n\t\tU2 = 0x06,\n\t\tI4 = 0x07,\n\t\tU4 = 0x08,\n\t\tI8 = 0x09,\n\t\tU8 = 0x0a,\n\t\tR4 = 0x0b,\n\t\tR8 = 0x0c,\n\t\tLPStr = 0x14,\n\t\tInt = 0x1f,\n\t\tUInt = 0x20,\n\t\tFunc = 0x26,\n\t\tArray = 0x2a,\n\n\t\t// Msft specific\n\t\tCurrency = 0x0f,\n\t\tBStr = 0x13,\n\t\tLPWStr = 0x15,\n\t\tLPTStr = 0x16,\n\t\tFixedSysString = 0x17,\n\t\tIUnknown = 0x19,\n\t\tIDispatch = 0x1a,\n\t\tStruct = 0x1b,\n\t\tIntF = 0x1c,\n\t\tSafeArray = 0x1d,\n\t\tFixedArray = 0x1e,\n\t\tByValStr = 0x22,\n\t\tANSIBStr = 0x23,\n\t\tTBStr = 0x24,\n\t\tVariantBool = 0x25,\n\t\tASAny = 0x28,\n\t\tLPStruct = 0x2b,\n\t\tCustomMarshaler = 0x2c,\n\t\tError = 0x2d,\n\t\tMax = 0x50\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/PInvokeAttributes.cs",
    "content": "//\n// PInvokeAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum PInvokeAttributes : ushort {\n\t\tNoMangle\t\t\t= 0x0001,\t// PInvoke is to use the member name as specified\n\n\t\t// Character set\n\t\tCharSetMask\t\t\t= 0x0006,\n\t\tCharSetNotSpec\t\t= 0x0000,\n\t\tCharSetAnsi\t\t\t= 0x0002,\n\t\tCharSetUnicode\t\t= 0x0004,\n\t\tCharSetAuto\t\t\t= 0x0006,\n\n\t\tSupportsLastError\t= 0x0040,\t// Information about target function. Not relevant for fields\n\n\t\t// Calling convetion\n\t\tCallConvMask\t\t= 0x0700,\n\t\tCallConvWinapi\t\t= 0x0100,\n\t\tCallConvCdecl\t\t= 0x0200,\n\t\tCallConvStdCall\t\t= 0x0300,\n\t\tCallConvThiscall\t= 0x0400,\n\t\tCallConvFastcall\t= 0x0500,\n\n\t\tBestFitMask\t\t\t= 0x0030,\n\t\tBestFitEnabled\t\t= 0x0010,\n\t\tBestFitDisabled\t\t= 0x0020,\n\n\t\tThrowOnUnmappableCharMask = 0x3000,\n\t\tThrowOnUnmappableCharEnabled = 0x1000,\n\t\tThrowOnUnmappableCharDisabled = 0x2000,\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/PInvokeInfo.cs",
    "content": "//\n// PInvokeInfo.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class PInvokeInfo {\n\n\t\tushort attributes;\n\t\tstring entry_point;\n\t\tModuleReference module;\n\n\t\tpublic PInvokeAttributes Attributes {\n\t\t\tget { return (PInvokeAttributes) attributes; }\n\t\t\tset { attributes = (ushort) value; }\n\t\t}\n\n\t\tpublic string EntryPoint {\n\t\t\tget { return entry_point; }\n\t\t\tset { entry_point = value; }\n\t\t}\n\n\t\tpublic ModuleReference Module {\n\t\t\tget { return module; }\n\t\t\tset { module = value; }\n\t\t}\n\n\t\t#region PInvokeAttributes\n\n\t\tpublic bool IsNoMangle {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) PInvokeAttributes.NoMangle); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) PInvokeAttributes.NoMangle, value); }\n\t\t}\n\n\t\tpublic bool IsCharSetNotSpec {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetNotSpec); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetNotSpec, value); }\n\t\t}\n\n\t\tpublic bool IsCharSetAnsi {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAnsi); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAnsi, value); }\n\t\t}\n\n\t\tpublic bool IsCharSetUnicode {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetUnicode); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetUnicode, value); }\n\t\t}\n\n\t\tpublic bool IsCharSetAuto {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAuto); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAuto, value); }\n\t\t}\n\n\t\tpublic bool SupportsLastError {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) PInvokeAttributes.SupportsLastError); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) PInvokeAttributes.SupportsLastError, value); }\n\t\t}\n\n\t\tpublic bool IsCallConvWinapi {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvWinapi); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvWinapi, value); }\n\t\t}\n\n\t\tpublic bool IsCallConvCdecl {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvCdecl); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvCdecl, value); }\n\t\t}\n\n\t\tpublic bool IsCallConvStdCall {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvStdCall); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvStdCall, value); }\n\t\t}\n\n\t\tpublic bool IsCallConvThiscall {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvThiscall); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvThiscall, value); }\n\t\t}\n\n\t\tpublic bool IsCallConvFastcall {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvFastcall); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvFastcall, value); }\n\t\t}\n\n\t\tpublic bool IsBestFitEnabled {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitEnabled); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitEnabled, value); }\n\t\t}\n\n\t\tpublic bool IsBestFitDisabled {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitDisabled); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitDisabled, value); }\n\t\t}\n\n\t\tpublic bool IsThrowOnUnmappableCharEnabled {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharEnabled); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharEnabled, value); }\n\t\t}\n\n\t\tpublic bool IsThrowOnUnmappableCharDisabled {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharDisabled); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharDisabled, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic PInvokeInfo (PInvokeAttributes attributes, string entryPoint, ModuleReference module)\n\t\t{\n\t\t\tthis.attributes = (ushort) attributes;\n\t\t\tthis.entry_point = entryPoint;\n\t\t\tthis.module = module;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ParameterAttributes.cs",
    "content": "//\n// ParameterAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum ParameterAttributes : ushort {\n\t\tNone\t\t\t\t= 0x0000,\n\t\tIn\t\t\t\t\t= 0x0001,\t// Param is [In]\n\t\tOut\t\t\t\t\t= 0x0002,\t// Param is [Out]\n\t\tLcid\t\t\t\t= 0x0004,\n\t\tRetval\t\t\t\t= 0x0008,\n\t\tOptional\t\t\t= 0x0010,\t// Param is optional\n\t\tHasDefault\t\t\t= 0x1000,\t// Param has default value\n\t\tHasFieldMarshal\t\t= 0x2000,\t// Param has field marshal\n\t\tUnused\t\t\t\t= 0xcfe0\t // Reserved: shall be zero in a conforming implementation\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ParameterDefinition.cs",
    "content": "//\n// ParameterDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class ParameterDefinition : ParameterReference, ICustomAttributeProvider, IConstantProvider, IMarshalInfoProvider\n    {\n\n        ushort attributes;\n\n        internal IMethodSignature method;\n\n        object constant = Mixin.NotResolved;\n        Collection<CustomAttribute> custom_attributes;\n        MarshalInfo marshal_info;\n\n        public ParameterAttributes Attributes\n        {\n            get { return (ParameterAttributes)attributes; }\n            set { attributes = (ushort)value; }\n        }\n\n        public IMethodSignature Method\n        {\n            get { return method; }\n        }\n\n        public int Sequence\n        {\n            get\n            {\n                if (method == null)\n                    return -1;\n\n                return Mixin.HasImplicitThis(method) ? index + 1 : index;\n            }\n        }\n\n        public bool HasConstant\n        {\n            get\n            {\n                Mixin.ResolveConstant(this, ref constant, parameter_type.Module);\n\n                return constant != Mixin.NoValue;\n            }\n            set { if (!value) constant = Mixin.NoValue; }\n        }\n\n        public object Constant\n        {\n            get { return HasConstant ? constant : null; }\n            set { constant = value; }\n        }\n\n        public bool HasCustomAttributes\n        {\n            get\n            {\n                if (custom_attributes != null)\n                    return custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, parameter_type.Module);\n            }\n        }\n\n        public Collection<CustomAttribute> CustomAttributes\n        {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, parameter_type.Module)); }\n        }\n\n        public bool HasMarshalInfo\n        {\n            get\n            {\n                if (marshal_info != null)\n                    return true;\n\n                return Mixin.GetHasMarshalInfo(this, parameter_type.Module);\n            }\n        }\n\n        public MarshalInfo MarshalInfo\n        {\n            get { return marshal_info ?? (Mixin.GetMarshalInfo(this, ref marshal_info, parameter_type.Module)); }\n            set { marshal_info = value; }\n        }\n\n        #region ParameterAttributes\n\n        public bool IsIn\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.In); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.In, value); }\n        }\n\n        public bool IsOut\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.Out); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.Out, value); }\n        }\n\n        public bool IsLcid\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.Lcid); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.Lcid, value); }\n        }\n\n        public bool IsReturnValue\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.Retval); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.Retval, value); }\n        }\n\n        public bool IsOptional\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.Optional); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.Optional, value); }\n        }\n\n        public bool HasDefault\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.HasDefault); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.HasDefault, value); }\n        }\n\n        public bool HasFieldMarshal\n        {\n            get { return Mixin.GetAttributes(attributes, (ushort)ParameterAttributes.HasFieldMarshal); }\n            set { attributes = Mixin.SetAttributes(attributes, (ushort)ParameterAttributes.HasFieldMarshal, value); }\n        }\n\n        #endregion\n\n        internal ParameterDefinition(TypeReference parameterType, IMethodSignature method)\n            : this(string.Empty, ParameterAttributes.None, parameterType)\n        {\n            this.method = method;\n        }\n\n        public ParameterDefinition(TypeReference parameterType)\n            : this(string.Empty, ParameterAttributes.None, parameterType)\n        {\n        }\n\n        public ParameterDefinition(string name, ParameterAttributes attributes, TypeReference parameterType)\n            : base(name, parameterType)\n        {\n            this.attributes = (ushort)attributes;\n            this.token = new MetadataToken(TokenType.Param);\n        }\n\n        public override ParameterDefinition Resolve()\n        {\n            return this;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ParameterDefinitionCollection.cs",
    "content": "//\n// ParameterDefinitionCollection.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tsealed class ParameterDefinitionCollection : Collection<ParameterDefinition> {\n\n\t\treadonly IMethodSignature method;\n\n\t\tinternal ParameterDefinitionCollection (IMethodSignature method)\n\t\t{\n\t\t\tthis.method = method;\n\t\t}\n\n\t\tinternal ParameterDefinitionCollection (IMethodSignature method, int capacity)\n\t\t\t: base (capacity)\n\t\t{\n\t\t\tthis.method = method;\n\t\t}\n\n\t\tprotected override void OnAdd (ParameterDefinition item, int index)\n\t\t{\n\t\t\titem.method = method;\n\t\t\titem.index = index;\n\t\t}\n\n\t\tprotected override void OnInsert (ParameterDefinition item, int index)\n\t\t{\n\t\t\titem.method = method;\n\t\t\titem.index = index;\n\n\t\t\tfor (int i = index; i < size; i++)\n\t\t\t\titems [i].index = i + 1;\n\t\t}\n\n\t\tprotected override void OnSet (ParameterDefinition item, int index)\n\t\t{\n\t\t\titem.method = method;\n\t\t\titem.index = index;\n\t\t}\n\n\t\tprotected override void OnRemove (ParameterDefinition item, int index)\n\t\t{\n\t\t\titem.method = null;\n\t\t\titem.index = -1;\n\n\t\t\tfor (int i = index + 1; i < size; i++)\n\t\t\t\titems [i].index = i - 1;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ParameterReference.cs",
    "content": "//\n// ParameterReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class ParameterReference : IMetadataTokenProvider {\n\n\t\tstring name;\n\t\tinternal int index = -1;\n\t\tprotected TypeReference parameter_type;\n\t\tinternal MetadataToken token;\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic int Index {\n\t\t\tget { return index; }\n\t\t}\n\n\t\tpublic TypeReference ParameterType {\n\t\t\tget { return parameter_type; }\n\t\t\tset { parameter_type = value; }\n\t\t}\n\n\t\tpublic MetadataToken MetadataToken {\n\t\t\tget { return token; }\n\t\t\tset { token = value; }\n\t\t}\n\n\t\tinternal ParameterReference (string name, TypeReference parameterType)\n\t\t{\n\t\t\tif (parameterType == null)\n\t\t\t\tthrow new ArgumentNullException (\"parameterType\");\n\n\t\t\tthis.name = name ?? string.Empty;\n\t\t\tthis.parameter_type = parameterType;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn name;\n\t\t}\n\n\t\tpublic abstract ParameterDefinition Resolve ();\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/PinnedType.cs",
    "content": "//\n// PinnedType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class PinnedType : TypeSpecification {\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsPinned {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic PinnedType (TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.etype = MD.ElementType.Pinned;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/PointerType.cs",
    "content": "//\n// PointerType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class PointerType : TypeSpecification {\n\n\t\tpublic override string Name {\n\t\t\tget { return base.Name + \"*\"; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return base.FullName + \"*\"; }\n\t\t}\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsPointer {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic PointerType (TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.etype = MD.ElementType.Ptr;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/PropertyAttributes.cs",
    "content": "//\n// PropertyAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum PropertyAttributes : ushort {\n\t\tNone\t\t\t= 0x0000,\n\t\tSpecialName\t\t= 0x0200,\t// Property is special\n\t\tRTSpecialName\t= 0x0400,\t// Runtime(metadata internal APIs) should check name encoding\n\t\tHasDefault\t\t= 0x1000,\t// Property has default\n\t\tUnused\t\t\t= 0xe9ff\t // Reserved: shall be zero in a conforming implementation\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/PropertyDefinition.cs",
    "content": "//\n// PropertyDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.Text;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class PropertyDefinition : PropertyReference, IMemberDefinition, IConstantProvider {\n\n\t\tbool? has_this;\n\t\tushort attributes;\n\n\t\tCollection<CustomAttribute> custom_attributes;\n\n\t\tinternal MethodDefinition get_method;\n\t\tinternal MethodDefinition set_method;\n\t\tinternal Collection<MethodDefinition> other_methods;\n\n\t\tobject constant = Mixin.NotResolved;\n\n\t\tpublic PropertyAttributes Attributes {\n\t\t\tget { return (PropertyAttributes) attributes; }\n\t\t\tset { attributes = (ushort) value; }\n\t\t}\n\n\t\tpublic bool HasThis {\n\t\t\tget {\n\t\t\t\tif (has_this.HasValue)\n\t\t\t\t\treturn has_this.Value;\n\n\t\t\t\tif (GetMethod != null)\n\t\t\t\t\treturn get_method.HasThis;\n\n\t\t\t\tif (SetMethod != null)\n\t\t\t\t\treturn set_method.HasThis;\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tset { has_this = value; }\n\t\t}\n\n\t\tpublic bool HasCustomAttributes {\n\t\t\tget {\n\t\t\t\tif (custom_attributes != null)\n\t\t\t\t\treturn custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<CustomAttribute> CustomAttributes {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n\t\t}\n\n\t\tpublic MethodDefinition GetMethod {\n\t\t\tget {\n\t\t\t\tif (get_method != null)\n\t\t\t\t\treturn get_method;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn get_method;\n\t\t\t}\n\t\t\tset { get_method = value; }\n\t\t}\n\n\t\tpublic MethodDefinition SetMethod {\n\t\t\tget {\n\t\t\t\tif (set_method != null)\n\t\t\t\t\treturn set_method;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn set_method;\n\t\t\t}\n\t\t\tset { set_method = value; }\n\t\t}\n\n\t\tpublic bool HasOtherMethods {\n\t\t\tget {\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods.Count > 0;\n\n\t\t\t\tInitializeMethods ();\n\t\t\t\treturn !Mixin.IsNullOrEmpty (other_methods);\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<MethodDefinition> OtherMethods {\n\t\t\tget {\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods;\n\n\t\t\t\tInitializeMethods ();\n\n\t\t\t\tif (other_methods != null)\n\t\t\t\t\treturn other_methods;\n\n\t\t\t\treturn other_methods = new Collection<MethodDefinition> ();\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasParameters {\n\t\t\tget {\n\t\t\t\tInitializeMethods ();\n\n\t\t\t\tif (get_method != null)\n\t\t\t\t\treturn get_method.HasParameters;\n\n\t\t\t\tif (set_method != null)\n\t\t\t\t\treturn set_method.HasParameters && set_method.Parameters.Count > 1;\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tpublic override Collection<ParameterDefinition> Parameters {\n\t\t\tget {\n\t\t\t\tInitializeMethods ();\n\n\t\t\t\tif (get_method != null)\n\t\t\t\t\treturn MirrorParameters (get_method, 0);\n\n\t\t\t\tif (set_method != null)\n\t\t\t\t\treturn MirrorParameters (set_method, 1);\n\n\t\t\t\treturn new Collection<ParameterDefinition> ();\n\t\t\t}\n\t\t}\n\n\t\tstatic Collection<ParameterDefinition> MirrorParameters (MethodDefinition method, int bound)\n\t\t{\n\t\t\tvar parameters = new Collection<ParameterDefinition> ();\n\t\t\tif (!method.HasParameters)\n\t\t\t\treturn parameters;\n\n\t\t\tvar original_parameters = method.Parameters;\n\t\t\tvar end = original_parameters.Count - bound;\n\n\t\t\tfor (int i = 0; i < end; i++)\n\t\t\t\tparameters.Add (original_parameters [i]);\n\n\t\t\treturn parameters;\n\t\t}\n\n\t\tpublic bool HasConstant {\n\t\t\tget {\n                Mixin.ResolveConstant(this, ref constant, Module);\n\n\t\t\t\treturn constant != Mixin.NoValue;\n\t\t\t}\n\t\t\tset { if (!value) constant = Mixin.NoValue; }\n\t\t}\n\n\t\tpublic object Constant {\n\t\t\tget { return HasConstant ? constant : null;\t}\n\t\t\tset { constant = value; }\n\t\t}\n\n\t\t#region PropertyAttributes\n\n\t\tpublic bool IsSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) PropertyAttributes.SpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) PropertyAttributes.SpecialName, value); }\n\t\t}\n\n\t\tpublic bool IsRuntimeSpecialName {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) PropertyAttributes.RTSpecialName); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) PropertyAttributes.RTSpecialName, value); }\n\t\t}\n\n\t\tpublic bool HasDefault {\n\t\t\tget { return Mixin.GetAttributes(attributes,(ushort) PropertyAttributes.HasDefault); }\n\t\t\tset { attributes =Mixin.SetAttributes(attributes,(ushort) PropertyAttributes.HasDefault, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tpublic new TypeDefinition DeclaringType {\n\t\t\tget { return (TypeDefinition) base.DeclaringType; }\n\t\t\tset { base.DeclaringType = value; }\n\t\t}\n\n\t\tpublic override bool IsDefinition {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget {\n\t\t\t\tvar builder = new StringBuilder ();\n\t\t\t\tbuilder.Append (PropertyType.ToString ());\n\t\t\t\tbuilder.Append (' ');\n\t\t\t\tbuilder.Append (MemberFullName ());\n\t\t\t\tbuilder.Append ('(');\n\t\t\t\tif (HasParameters) {\n\t\t\t\t\tvar parameters = Parameters;\n\t\t\t\t\tfor (int i = 0; i < parameters.Count; i++) {\n\t\t\t\t\t\tif (i > 0)\n\t\t\t\t\t\t\tbuilder.Append (',');\n\t\t\t\t\t\tbuilder.Append (parameters [i].ParameterType.FullName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbuilder.Append (')');\n\t\t\t\treturn builder.ToString ();\n\t\t\t}\n\t\t}\n\n\t\tpublic PropertyDefinition (string name, PropertyAttributes attributes, TypeReference propertyType)\n\t\t\t: base (name, propertyType)\n\t\t{\n\t\t\tthis.attributes = (ushort) attributes;\n\t\t\tthis.token = new MetadataToken (TokenType.Property);\n\t\t}\n\n\t\tvoid InitializeMethods ()\n\t\t{\n\t\t\tvar module = this.Module;\n\t\t\tlock (module.SyncRoot) {\n\t\t\t\tif (get_method != null || set_method != null)\n\t\t\t\t\treturn;\n\n                if (!Mixin.HasImage(module))\n\t\t\t\t\treturn;\n\n\t\t\t\tmodule.Read (this, (property, reader) => reader.ReadMethods (property));\n\t\t\t}\n\t\t}\n\n\t\tpublic override PropertyDefinition Resolve ()\n\t\t{\n\t\t\treturn this;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/PropertyReference.cs",
    "content": "//\n// PropertyReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class PropertyReference : MemberReference {\n\n\t\tTypeReference property_type;\n\n\t\tpublic TypeReference PropertyType {\n\t\t\tget { return property_type; }\n\t\t\tset { property_type = value; }\n\t\t}\n\n\t\tpublic abstract Collection<ParameterDefinition> Parameters {\n\t\t\tget;\n\t\t}\n\n\t\tinternal PropertyReference (string name, TypeReference propertyType)\n\t\t\t: base (name)\n\t\t{\n\t\t\tif (propertyType == null)\n\t\t\t\tthrow new ArgumentNullException (\"propertyType\");\n\n\t\t\tproperty_type = propertyType;\n\t\t}\n\n\t\tpublic abstract PropertyDefinition Resolve ();\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/ReferenceType.cs",
    "content": "//\n// ByReferenceType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class ByReferenceType : TypeSpecification {\n\n\t\tpublic override string Name {\n\t\t\tget { return base.Name + \"&\"; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return base.FullName + \"&\"; }\n\t\t}\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsByReference {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic ByReferenceType (TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.etype = MD.ElementType.ByRef;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/Resource.cs",
    "content": "//\n// ResourceType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum ResourceType {\n\t\tLinked,\n\t\tEmbedded,\n\t\tAssemblyLinked,\n\t}\n\n\tpublic abstract class Resource {\n\n\t\tstring name;\n\t\tuint attributes;\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic ManifestResourceAttributes Attributes {\n\t\t\tget { return (ManifestResourceAttributes) attributes; }\n\t\t\tset { attributes = (uint) value; }\n\t\t}\n\n\t\tpublic abstract ResourceType ResourceType {\n\t\t\tget;\n\t\t}\n\n\t\t#region ManifestResourceAttributes\n\n\t\tpublic bool IsPublic {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Public); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Public, value); }\n\t\t}\n\n\t\tpublic bool IsPrivate {\n\t\t\tget { return Mixin.GetMaskedAttributes(attributes,(uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Private); }\n\t\t\tset { attributes = Mixin.SetMaskedAttributes(attributes,(uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Private, value); }\n\t\t}\n\n\t\t#endregion\n\n\t\tinternal Resource (string name, ManifestResourceAttributes attributes)\n\t\t{\n\t\t\tthis.name = name;\n\t\t\tthis.attributes = (uint) attributes;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/SecurityDeclaration.cs",
    "content": "//\n// SecurityDeclaration.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Threading;\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public enum SecurityAction : ushort\n    {\n        Request = 1,\n        Demand = 2,\n        Assert = 3,\n        Deny = 4,\n        PermitOnly = 5,\n        LinkDemand = 6,\n        InheritDemand = 7,\n        RequestMinimum = 8,\n        RequestOptional = 9,\n        RequestRefuse = 10,\n        PreJitGrant = 11,\n        PreJitDeny = 12,\n        NonCasDemand = 13,\n        NonCasLinkDemand = 14,\n        NonCasInheritance = 15\n    }\n\n    public interface ISecurityDeclarationProvider : IMetadataTokenProvider\n    {\n\n        bool HasSecurityDeclarations { get; }\n        Collection<SecurityDeclaration> SecurityDeclarations { get; }\n    }\n\n    public sealed class SecurityAttribute : ICustomAttribute\n    {\n\n        TypeReference attribute_type;\n\n        internal Collection<CustomAttributeNamedArgument> fields;\n        internal Collection<CustomAttributeNamedArgument> properties;\n\n        public TypeReference AttributeType\n        {\n            get { return attribute_type; }\n            set { attribute_type = value; }\n        }\n\n        public bool HasFields\n        {\n            get { return !Mixin.IsNullOrEmpty(fields); }\n        }\n\n        public Collection<CustomAttributeNamedArgument> Fields\n        {\n            get { return fields ?? (fields = new Collection<CustomAttributeNamedArgument>()); }\n        }\n\n        public bool HasProperties\n        {\n            get { return !Mixin.IsNullOrEmpty(properties); }\n        }\n\n        public Collection<CustomAttributeNamedArgument> Properties\n        {\n            get { return properties ?? (properties = new Collection<CustomAttributeNamedArgument>()); }\n        }\n\n        public SecurityAttribute(TypeReference attributeType)\n        {\n            this.attribute_type = attributeType;\n        }\n    }\n\n    public sealed class SecurityDeclaration\n    {\n\n        readonly internal uint signature;\n        byte[] blob;\n        readonly ModuleDefinition module;\n\n        internal bool resolved;\n        SecurityAction action;\n        internal Collection<SecurityAttribute> security_attributes;\n\n        public SecurityAction Action\n        {\n            get { return action; }\n            set { action = value; }\n        }\n\n        public bool HasSecurityAttributes\n        {\n            get\n            {\n                Resolve();\n\n                return !Mixin.IsNullOrEmpty(security_attributes);\n            }\n        }\n\n        public Collection<SecurityAttribute> SecurityAttributes\n        {\n            get\n            {\n                Resolve();\n\n                return security_attributes ?? (security_attributes = new Collection<SecurityAttribute>());\n            }\n        }\n\n        internal bool HasImage\n        {\n            get { return module != null && module.HasImage; }\n        }\n\n        internal SecurityDeclaration(SecurityAction action, uint signature, ModuleDefinition module)\n        {\n            this.action = action;\n            this.signature = signature;\n            this.module = module;\n        }\n\n        public SecurityDeclaration(SecurityAction action)\n        {\n            this.action = action;\n            this.resolved = true;\n        }\n\n        public SecurityDeclaration(SecurityAction action, byte[] blob)\n        {\n            this.action = action;\n            this.resolved = false;\n            this.blob = blob;\n        }\n\n        public byte[] GetBlob()\n        {\n            if (blob != null)\n                return blob;\n\n            if (!HasImage || signature == 0)\n                throw new NotSupportedException();\n\n            return blob = module.Read(this, (declaration, reader) => reader.ReadSecurityDeclarationBlob(declaration.signature));\n        }\n\n        void Resolve()\n        {\n            if (resolved || !HasImage)\n                return;\n\n            module.Read(this, (declaration, reader) =>\n            {\n                reader.ReadSecurityDeclarationSignature(declaration);\n                return this;\n            });\n\n            resolved = true;\n        }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool GetHasSecurityDeclarations(\n            ISecurityDeclarationProvider self,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module) && module.Read(self, (provider, reader) => reader.HasSecurityDeclarations(provider));\n        }\n\n        public static Collection<SecurityDeclaration> GetSecurityDeclarations(\n            ISecurityDeclarationProvider self,\n            ref Collection<SecurityDeclaration> variable,\n            ModuleDefinition module)\n        {\n            return Mixin.HasImage(module)\n                ? module.Read(ref variable, self, (provider, reader) => reader.ReadSecurityDeclarations(provider))\n                : variable = new Collection<SecurityDeclaration>();\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/SentinelType.cs",
    "content": "//\n// SentinelType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing MD = Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic sealed class SentinelType : TypeSpecification {\n\n\t\tpublic override bool IsValueType {\n\t\t\tget { return false; }\n\t\t\tset { throw new InvalidOperationException (); }\n\t\t}\n\n\t\tpublic override bool IsSentinel {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tpublic SentinelType (TypeReference type)\n\t\t\t: base (type)\n\t\t{\n\t\t\tMixin.CheckType (type);\n\t\t\tthis.etype = MD.ElementType.Sentinel;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/TargetRuntime.cs",
    "content": "//\n// TargetRuntime.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum TargetRuntime {\n\t\tNet_1_0,\n\t\tNet_1_1,\n\t\tNet_2_0,\n\t\tNet_4_0,\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeAttributes.cs",
    "content": "//\n// TypeAttributes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil {\n\n\t[Flags]\n\tpublic enum TypeAttributes : uint {\n\t\t// Visibility attributes\n\t\tVisibilityMask\t\t= 0x00000007,\t// Use this mask to retrieve visibility information\n\t\tNotPublic\t\t\t= 0x00000000,\t// Class has no public scope\n\t\tPublic\t\t\t\t= 0x00000001,\t// Class has public scope\n\t\tNestedPublic\t\t= 0x00000002,\t// Class is nested with public visibility\n\t\tNestedPrivate\t\t= 0x00000003,\t// Class is nested with private visibility\n\t\tNestedFamily\t\t= 0x00000004,\t// Class is nested with family visibility\n\t\tNestedAssembly\t\t= 0x00000005,\t// Class is nested with assembly visibility\n\t\tNestedFamANDAssem\t= 0x00000006,\t// Class is nested with family and assembly visibility\n\t\tNestedFamORAssem\t= 0x00000007,\t// Class is nested with family or assembly visibility\n\n\t\t// Class layout attributes\n\t\tLayoutMask\t\t\t= 0x00000018,\t// Use this mask to retrieve class layout information\n\t\tAutoLayout\t\t\t= 0x00000000,\t// Class fields are auto-laid out\n\t\tSequentialLayout\t= 0x00000008,\t// Class fields are laid out sequentially\n\t\tExplicitLayout\t\t= 0x00000010,\t// Layout is supplied explicitly\n\n\t\t// Class semantics attributes\n\t\tClassSemanticMask\t= 0x00000020,\t// Use this mask to retrieve class semantics information\n\t\tClass\t\t\t\t= 0x00000000,\t// Type is a class\n\t\tInterface\t\t\t= 0x00000020,\t// Type is an interface\n\n\t\t// Special semantics in addition to class semantics\n\t\tAbstract\t\t\t= 0x00000080,\t// Class is abstract\n\t\tSealed\t\t\t\t= 0x00000100,\t// Class cannot be extended\n\t\tSpecialName\t\t\t= 0x00000400,\t// Class name is special\n\n\t\t// Implementation attributes\n\t\tImport\t\t\t\t= 0x00001000,\t// Class/Interface is imported\n\t\tSerializable\t\t= 0x00002000,\t// Class is serializable\n\t\tWindowsRuntime\t\t= 0x00004000,\t// Windows Runtime type\n\n\t\t// String formatting attributes\n\t\tStringFormatMask\t= 0x00030000,\t// Use this mask to retrieve string information for native interop\n\t\tAnsiClass\t\t\t= 0x00000000,\t// LPSTR is interpreted as ANSI\n\t\tUnicodeClass\t\t= 0x00010000,\t// LPSTR is interpreted as Unicode\n\t\tAutoClass\t\t\t= 0x00020000,\t// LPSTR is interpreted automatically\n\n\t\t// Class initialization attributes\n\t\tBeforeFieldInit\t\t= 0x00100000,\t// Initialize the class before first static field access\n\n\t\t// Additional flags\n\t\tRTSpecialName\t\t= 0x00000800,\t// CLI provides 'special' behavior, depending upon the name of the Type\n\t\tHasSecurity\t\t\t= 0x00040000,\t// Type has security associate with it\n\t\tForwarder\t\t\t= 0x00200000,   // Exported type is a type forwarder\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeDefinition.cs",
    "content": "//\n// TypeDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.Metadata;\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public sealed class TypeDefinition : TypeReference, IMemberDefinition, ISecurityDeclarationProvider\n    {\n\n        uint attributes;\n        TypeReference base_type;\n        internal Range fields_range;\n        internal Range methods_range;\n\n        short packing_size = Mixin.NotResolvedMarker;\n        int class_size = Mixin.NotResolvedMarker;\n\n        Collection<TypeReference> interfaces;\n        Collection<TypeDefinition> nested_types;\n        Collection<MethodDefinition> methods;\n        Collection<FieldDefinition> fields;\n        Collection<EventDefinition> events;\n        Collection<PropertyDefinition> properties;\n        Collection<CustomAttribute> custom_attributes;\n        Collection<SecurityDeclaration> security_declarations;\n\n        public TypeAttributes Attributes\n        {\n            get { return (TypeAttributes)attributes; }\n            set { attributes = (uint)value; }\n        }\n\n        public TypeReference BaseType\n        {\n            get { return base_type; }\n            set { base_type = value; }\n        }\n\n        void ResolveLayout()\n        {\n            if (packing_size != Mixin.NotResolvedMarker || class_size != Mixin.NotResolvedMarker)\n                return;\n\n            if (!HasImage)\n            {\n                packing_size = Mixin.NoDataMarker;\n                class_size = Mixin.NoDataMarker;\n                return;\n            }\n\n            var row = Module.Read(this, (type, reader) => reader.ReadTypeLayout(type));\n\n            packing_size = row.Col1;\n            class_size = row.Col2;\n        }\n\n        public bool HasLayoutInfo\n        {\n            get\n            {\n                if (packing_size >= 0 || class_size >= 0)\n                    return true;\n\n                ResolveLayout();\n\n                return packing_size >= 0 || class_size >= 0;\n            }\n        }\n\n        public short PackingSize\n        {\n            get\n            {\n                if (packing_size >= 0)\n                    return packing_size;\n\n                ResolveLayout();\n\n                return packing_size >= 0 ? packing_size : (short)-1;\n            }\n            set { packing_size = value; }\n        }\n\n        public int ClassSize\n        {\n            get\n            {\n                if (class_size >= 0)\n                    return class_size;\n\n                ResolveLayout();\n\n                return class_size >= 0 ? class_size : -1;\n            }\n            set { class_size = value; }\n        }\n\n        public bool HasInterfaces\n        {\n            get\n            {\n                if (interfaces != null)\n                    return interfaces.Count > 0;\n\n                if (HasImage)\n                    return Module.Read(this, (type, reader) => reader.HasInterfaces(type));\n\n                return false;\n            }\n        }\n\n        public Collection<TypeReference> Interfaces\n        {\n            get\n            {\n                if (interfaces != null)\n                    return interfaces;\n\n                if (HasImage)\n                    return Module.Read(ref interfaces, this, (type, reader) => reader.ReadInterfaces(type));\n\n                return interfaces = new Collection<TypeReference>();\n            }\n        }\n\n        public bool HasNestedTypes\n        {\n            get\n            {\n                if (nested_types != null)\n                    return nested_types.Count > 0;\n\n                if (HasImage)\n                    return Module.Read(this, (type, reader) => reader.HasNestedTypes(type));\n\n                return false;\n            }\n        }\n\n        public Collection<TypeDefinition> NestedTypes\n        {\n            get\n            {\n                if (nested_types != null)\n                    return nested_types;\n\n                if (HasImage)\n                    return Module.Read(ref nested_types, this, (type, reader) => reader.ReadNestedTypes(type));\n\n                return nested_types = new MemberDefinitionCollection<TypeDefinition>(this);\n            }\n        }\n\n        public bool HasMethods\n        {\n            get\n            {\n                if (methods != null)\n                    return methods.Count > 0;\n\n                if (HasImage)\n                    return methods_range.Length > 0;\n\n                return false;\n            }\n        }\n\n        public Collection<MethodDefinition> Methods\n        {\n            get\n            {\n                if (methods != null)\n                    return methods;\n\n                if (HasImage)\n                    return Module.Read(ref methods, this, (type, reader) => reader.ReadMethods(type));\n\n                return methods = new MemberDefinitionCollection<MethodDefinition>(this);\n            }\n        }\n\n        public bool HasFields\n        {\n            get\n            {\n                if (fields != null)\n                    return fields.Count > 0;\n\n                if (HasImage)\n                    return fields_range.Length > 0;\n\n                return false;\n            }\n        }\n\n        public Collection<FieldDefinition> Fields\n        {\n            get\n            {\n                if (fields != null)\n                    return fields;\n\n                if (HasImage)\n                    return Module.Read(ref fields, this, (type, reader) => reader.ReadFields(type));\n\n                return fields = new MemberDefinitionCollection<FieldDefinition>(this);\n            }\n        }\n\n        public bool HasEvents\n        {\n            get\n            {\n                if (events != null)\n                    return events.Count > 0;\n\n                if (HasImage)\n                    return Module.Read(this, (type, reader) => reader.HasEvents(type));\n\n                return false;\n            }\n        }\n\n        public Collection<EventDefinition> Events\n        {\n            get\n            {\n                if (events != null)\n                    return events;\n\n                if (HasImage)\n                    return Module.Read(ref events, this, (type, reader) => reader.ReadEvents(type));\n\n                return events = new MemberDefinitionCollection<EventDefinition>(this);\n            }\n        }\n\n        public bool HasProperties\n        {\n            get\n            {\n                if (properties != null)\n                    return properties.Count > 0;\n\n                if (HasImage)\n                    return Module.Read(this, (type, reader) => reader.HasProperties(type));\n\n                return false;\n            }\n        }\n\n        public Collection<PropertyDefinition> Properties\n        {\n            get\n            {\n                if (properties != null)\n                    return properties;\n\n                if (HasImage)\n                    return Module.Read(ref properties, this, (type, reader) => reader.ReadProperties(type));\n\n                return properties = new MemberDefinitionCollection<PropertyDefinition>(this);\n            }\n        }\n\n        public bool HasSecurityDeclarations\n        {\n            get\n            {\n                if (security_declarations != null)\n                    return security_declarations.Count > 0;\n\n                return Mixin.GetHasSecurityDeclarations(this, Module);\n            }\n        }\n\n        public Collection<SecurityDeclaration> SecurityDeclarations\n        {\n            get { return security_declarations ?? (Mixin.GetSecurityDeclarations(this, ref security_declarations, Module)); }\n        }\n\n        public bool HasCustomAttributes\n        {\n            get\n            {\n                if (custom_attributes != null)\n                    return custom_attributes.Count > 0;\n\n                return Mixin.GetHasCustomAttributes(this, Module);\n            }\n        }\n\n        public Collection<CustomAttribute> CustomAttributes\n        {\n            get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }\n        }\n\n        public override bool HasGenericParameters\n        {\n            get\n            {\n                if (generic_parameters != null)\n                    return generic_parameters.Count > 0;\n\n                return Mixin.GetHasGenericParameters(this, Module);\n            }\n        }\n\n        public override Collection<GenericParameter> GenericParameters\n        {\n            get { return generic_parameters ?? (Mixin.GetGenericParameters(this,ref generic_parameters, Module)); }\n        }\n\n        #region TypeAttributes\n\n        public bool IsNotPublic\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NotPublic); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NotPublic, value); }\n        }\n\n        public bool IsPublic\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.Public); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.Public, value); }\n        }\n\n        public bool IsNestedPublic\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedPublic); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedPublic, value); }\n        }\n\n        public bool IsNestedPrivate\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedPrivate); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedPrivate, value); }\n        }\n\n        public bool IsNestedFamily\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamily); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamily, value); }\n        }\n\n        public bool IsNestedAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedAssembly); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedAssembly, value); }\n        }\n\n        public bool IsNestedFamilyAndAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamANDAssem); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamANDAssem, value); }\n        }\n\n        public bool IsNestedFamilyOrAssembly\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamORAssem); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.VisibilityMask, (uint)TypeAttributes.NestedFamORAssem, value); }\n        }\n\n        public bool IsAutoLayout\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.AutoLayout); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.AutoLayout, value); }\n        }\n\n        public bool IsSequentialLayout\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.SequentialLayout); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.SequentialLayout, value); }\n        }\n\n        public bool IsExplicitLayout\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.ExplicitLayout); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.LayoutMask, (uint)TypeAttributes.ExplicitLayout, value); }\n        }\n\n        public bool IsClass\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.ClassSemanticMask, (uint)TypeAttributes.Class); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.ClassSemanticMask, (uint)TypeAttributes.Class, value); }\n        }\n\n        public bool IsInterface\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.ClassSemanticMask, (uint)TypeAttributes.Interface); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.ClassSemanticMask, (uint)TypeAttributes.Interface, value); }\n        }\n\n        public bool IsAbstract\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.Abstract); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.Abstract, value); }\n        }\n\n        public bool IsSealed\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.Sealed); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.Sealed, value); }\n        }\n\n        public bool IsSpecialName\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.SpecialName); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.SpecialName, value); }\n        }\n\n        public bool IsImport\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.Import); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.Import, value); }\n        }\n\n        public bool IsSerializable\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.Serializable); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.Serializable, value); }\n        }\n\n        public bool IsWindowsRuntime\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.WindowsRuntime); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.WindowsRuntime, value); }\n        }\n\n        public bool IsAnsiClass\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.AnsiClass); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.AnsiClass, value); }\n        }\n\n        public bool IsUnicodeClass\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.UnicodeClass); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.UnicodeClass, value); }\n        }\n\n        public bool IsAutoClass\n        {\n            get { return Mixin.GetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.AutoClass); }\n            set { attributes = Mixin.SetMaskedAttributes(attributes, (uint)TypeAttributes.StringFormatMask, (uint)TypeAttributes.AutoClass, value); }\n        }\n\n        public bool IsBeforeFieldInit\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.BeforeFieldInit); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.BeforeFieldInit, value); }\n        }\n\n        public bool IsRuntimeSpecialName\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.RTSpecialName); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.RTSpecialName, value); }\n        }\n\n        public bool HasSecurity\n        {\n            get { return Mixin.GetAttributes(attributes, (uint)TypeAttributes.HasSecurity); }\n            set { attributes = Mixin.SetAttributes(attributes, (uint)TypeAttributes.HasSecurity, value); }\n        }\n\n        #endregion\n\n        public bool IsEnum\n        {\n            get { return base_type != null && Mixin.IsTypeOf(base_type, \"System\", \"Enum\"); }\n        }\n\n        public override bool IsValueType\n        {\n            get\n            {\n                if (base_type == null)\n                    return false;\n\n                return Mixin.IsTypeOf(base_type, \"System\", \"Enum\") || (Mixin.IsTypeOf(base_type, \"System\", \"ValueType\") && !Mixin.IsTypeOf(this, \"System\", \"Enum\"));\n            }\n        }\n\n        public override bool IsPrimitive\n        {\n            get\n            {\n                ElementType primitive_etype;\n                return MetadataSystem.TryGetPrimitiveElementType(this, out primitive_etype);\n            }\n        }\n\n        public override MetadataType MetadataType\n        {\n            get\n            {\n                ElementType primitive_etype;\n                if (MetadataSystem.TryGetPrimitiveElementType(this, out primitive_etype))\n                    return (MetadataType)primitive_etype;\n\n                return base.MetadataType;\n            }\n        }\n\n        public override bool IsDefinition\n        {\n            get { return true; }\n        }\n\n        public new TypeDefinition DeclaringType\n        {\n            get { return (TypeDefinition)base.DeclaringType; }\n            set { base.DeclaringType = value; }\n        }\n\n        public TypeDefinition(string @namespace, string name, TypeAttributes attributes)\n            : base(@namespace, name)\n        {\n            this.attributes = (uint)attributes;\n            this.token = new MetadataToken(TokenType.TypeDef);\n        }\n\n        public TypeDefinition(string @namespace, string name, TypeAttributes attributes, TypeReference baseType) :\n            this(@namespace, name, attributes)\n        {\n            this.BaseType = baseType;\n        }\n\n        public override TypeDefinition Resolve()\n        {\n            return this;\n        }\n    }\n\n    static partial class Mixin\n    {\n\n        public static TypeReference GetEnumUnderlyingType(TypeDefinition self)\n        {\n            var fields = self.Fields;\n\n            for (int i = 0; i < fields.Count; i++)\n            {\n                var field = fields[i];\n                if (!field.IsStatic)\n                    return field.FieldType;\n            }\n\n            throw new ArgumentException();\n        }\n\n        public static TypeDefinition GetNestedType(TypeDefinition self, string name)\n        {\n            if (!self.HasNestedTypes)\n                return null;\n\n            var nested_types = self.NestedTypes;\n\n            for (int i = 0; i < nested_types.Count; i++)\n            {\n                var nested_type = nested_types[i];\n                if (nested_type.Name == name)\n                    return nested_type;\n            }\n\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeDefinitionCollection.cs",
    "content": "//\n// TypeDefinitionCollection.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\n\nusing Mono.Cecil.Metadata;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil {\n\n\tusing Slot = Row<string, string>;\n\n\tsealed class TypeDefinitionCollection : Collection<TypeDefinition> {\n\n\t\treadonly ModuleDefinition container;\n\t\treadonly Dictionary<Slot, TypeDefinition> name_cache;\n\n\t\tinternal TypeDefinitionCollection (ModuleDefinition container)\n\t\t{\n\t\t\tthis.container = container;\n\t\t\tthis.name_cache = new Dictionary<Slot, TypeDefinition> (new RowEqualityComparer ());\n\t\t}\n\n\t\tinternal TypeDefinitionCollection (ModuleDefinition container, int capacity)\n\t\t\t: base (capacity)\n\t\t{\n\t\t\tthis.container = container;\n\t\t\tthis.name_cache = new Dictionary<Slot, TypeDefinition> (capacity, new RowEqualityComparer ());\n\t\t}\n\n\t\tprotected override void OnAdd (TypeDefinition item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected override void OnSet (TypeDefinition item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected override void OnInsert (TypeDefinition item, int index)\n\t\t{\n\t\t\tAttach (item);\n\t\t}\n\n\t\tprotected override void OnRemove (TypeDefinition item, int index)\n\t\t{\n\t\t\tDetach (item);\n\t\t}\n\n\t\tprotected override void OnClear ()\n\t\t{\n\t\t\tforeach (var type in this)\n\t\t\t\tDetach (type);\n\t\t}\n\n\t\tvoid Attach (TypeDefinition type)\n\t\t{\n\t\t\tif (type.Module != null && type.Module != container)\n\t\t\t\tthrow new ArgumentException (\"Type already attached\");\n\n\t\t\ttype.module = container;\n\t\t\ttype.scope = container;\n\t\t\tname_cache [new Slot (type.Namespace, type.Name)] = type;\n\t\t}\n\n\t\tvoid Detach (TypeDefinition type)\n\t\t{\n\t\t\ttype.module = null;\n\t\t\ttype.scope = null;\n\t\t\tname_cache.Remove (new Slot (type.Namespace, type.Name));\n\t\t}\n\n\t\tpublic TypeDefinition GetType (string fullname)\n\t\t{\n\t\t\tstring @namespace, name;\n\t\t\tTypeParser.SplitFullName (fullname, out @namespace, out name);\n\n\t\t\treturn GetType (@namespace, name);\n\t\t}\n\n\t\tpublic TypeDefinition GetType (string @namespace, string name)\n\t\t{\n\t\t\tTypeDefinition type;\n\t\t\tif (name_cache.TryGetValue (new Slot (@namespace, name), out type))\n\t\t\t\treturn type;\n\n\t\t\treturn null;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeParser.cs",
    "content": "//\n// TypeParser.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil\n{\n\n    class TypeParser\n    {\n\n        class Type\n        {\n            public const int Ptr = -1;\n            public const int ByRef = -2;\n            public const int SzArray = -3;\n\n            public string type_fullname;\n            public string[] nested_names;\n            public int arity;\n            public int[] specs;\n            public Type[] generic_arguments;\n            public string assembly;\n        }\n\n        readonly string fullname;\n        readonly int length;\n\n        int position;\n\n        TypeParser(string fullname)\n        {\n            this.fullname = fullname;\n            this.length = fullname.Length;\n        }\n\n        Type ParseType(bool fq_name)\n        {\n            var type = new Type();\n            type.type_fullname = ParsePart();\n\n            type.nested_names = ParseNestedNames();\n\n            if (TryGetArity(type))\n                type.generic_arguments = ParseGenericArguments(type.arity);\n\n            type.specs = ParseSpecs();\n\n            if (fq_name)\n                type.assembly = ParseAssemblyName();\n\n            return type;\n        }\n\n        static bool TryGetArity(Type type)\n        {\n            int arity = 0;\n\n            TryAddArity(type.type_fullname, ref arity);\n\n            var nested_names = type.nested_names;\n            if (!Mixin.IsNullOrEmpty(nested_names))\n            {\n                for (int i = 0; i < nested_names.Length; i++)\n                    TryAddArity(nested_names[i], ref arity);\n            }\n\n            type.arity = arity;\n            return arity > 0;\n        }\n\n        static bool TryGetArity(string name, out int arity)\n        {\n            arity = 0;\n            var index = name.LastIndexOf('`');\n            if (index == -1)\n                return false;\n\n            return ParseInt32(name.Substring(index + 1), out arity);\n        }\n\n        static bool ParseInt32(string value, out int result)\n        {\n#if CF\n\t\t\ttry {\n\t\t\t\tresult = int.Parse (value);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\tresult = 0;\n\t\t\t\treturn false;\n\t\t\t}\n#else\n            return int.TryParse(value, out result);\n#endif\n        }\n\n        static void TryAddArity(string name, ref int arity)\n        {\n            int type_arity;\n            if (!TryGetArity(name, out type_arity))\n                return;\n\n            arity += type_arity;\n        }\n\n        string ParsePart()\n        {\n            int start = position;\n            while (position < length && !IsDelimiter(fullname[position]))\n                position++;\n\n            return fullname.Substring(start, position - start);\n        }\n\n        static bool IsDelimiter(char chr)\n        {\n            return \"+,[]*&\".IndexOf(chr) != -1;\n        }\n\n        void TryParseWhiteSpace()\n        {\n            while (position < length && Char.IsWhiteSpace(fullname[position]))\n                position++;\n        }\n\n        string[] ParseNestedNames()\n        {\n            string[] nested_names = null;\n            while (TryParse('+'))\n                Add(ref nested_names, ParsePart());\n\n            return nested_names;\n        }\n\n        bool TryParse(char chr)\n        {\n            if (position < length && fullname[position] == chr)\n            {\n                position++;\n                return true;\n            }\n\n            return false;\n        }\n\n        static void Add<T>(ref T[] array, T item)\n        {\n            if (array == null)\n            {\n                array = new[] { item };\n                return;\n            }\n\n#if !CF\n            Array.Resize(ref array, array.Length + 1);\n#else\n\t\t\tvar copy = new T [array.Length + 1];\n\t\t\tArray.Copy (array, copy, array.Length);\n\t\t\tarray = copy;\n#endif\n            array[array.Length - 1] = item;\n        }\n\n        int[] ParseSpecs()\n        {\n            int[] specs = null;\n\n            while (position < length)\n            {\n                switch (fullname[position])\n                {\n                    case '*':\n                        position++;\n                        Add(ref specs, Type.Ptr);\n                        break;\n                    case '&':\n                        position++;\n                        Add(ref specs, Type.ByRef);\n                        break;\n                    case '[':\n                        position++;\n                        switch (fullname[position])\n                        {\n                            case ']':\n                                position++;\n                                Add(ref specs, Type.SzArray);\n                                break;\n                            case '*':\n                                position++;\n                                Add(ref specs, 1);\n                                break;\n                            default:\n                                var rank = 1;\n                                while (TryParse(','))\n                                    rank++;\n\n                                Add(ref specs, rank);\n\n                                TryParse(']');\n                                break;\n                        }\n                        break;\n                    default:\n                        return specs;\n                }\n            }\n\n            return specs;\n        }\n\n        Type[] ParseGenericArguments(int arity)\n        {\n            Type[] generic_arguments = null;\n\n            if (position == length || fullname[position] != '[')\n                return generic_arguments;\n\n            TryParse('[');\n\n            for (int i = 0; i < arity; i++)\n            {\n                var fq_argument = TryParse('[');\n                Add(ref generic_arguments, ParseType(fq_argument));\n                if (fq_argument)\n                    TryParse(']');\n\n                TryParse(',');\n                TryParseWhiteSpace();\n            }\n\n            TryParse(']');\n\n            return generic_arguments;\n        }\n\n        string ParseAssemblyName()\n        {\n            if (!TryParse(','))\n                return string.Empty;\n\n            TryParseWhiteSpace();\n\n            var start = position;\n            while (position < length)\n            {\n                var chr = fullname[position];\n                if (chr == '[' || chr == ']')\n                    break;\n\n                position++;\n            }\n\n            return fullname.Substring(start, position - start);\n        }\n\n        public static TypeReference ParseType(ModuleDefinition module, string fullname)\n        {\n            if (string.IsNullOrEmpty(fullname))\n                return null;\n\n            var parser = new TypeParser(fullname);\n            return GetTypeReference(module, parser.ParseType(true));\n        }\n\n        static TypeReference GetTypeReference(ModuleDefinition module, Type type_info)\n        {\n            TypeReference type;\n            if (!TryGetDefinition(module, type_info, out type))\n                type = CreateReference(type_info, module, GetMetadataScope(module, type_info));\n\n            return CreateSpecs(type, type_info);\n        }\n\n        static TypeReference CreateSpecs(TypeReference type, Type type_info)\n        {\n            type = TryCreateGenericInstanceType(type, type_info);\n\n            var specs = type_info.specs;\n            if (Mixin.IsNullOrEmpty(specs))\n                return type;\n\n            for (int i = 0; i < specs.Length; i++)\n            {\n                switch (specs[i])\n                {\n                    case Type.Ptr:\n                        type = new PointerType(type);\n                        break;\n                    case Type.ByRef:\n                        type = new ByReferenceType(type);\n                        break;\n                    case Type.SzArray:\n                        type = new ArrayType(type);\n                        break;\n                    default:\n                        var array = new ArrayType(type);\n                        array.Dimensions.Clear();\n\n                        for (int j = 0; j < specs[i]; j++)\n                            array.Dimensions.Add(new ArrayDimension());\n\n                        type = array;\n                        break;\n                }\n            }\n\n            return type;\n        }\n\n        static TypeReference TryCreateGenericInstanceType(TypeReference type, Type type_info)\n        {\n            var generic_arguments = type_info.generic_arguments;\n            if (Mixin.IsNullOrEmpty(generic_arguments))\n                return type;\n\n            var instance = new GenericInstanceType(type);\n            var instance_arguments = instance.GenericArguments;\n\n            for (int i = 0; i < generic_arguments.Length; i++)\n                instance_arguments.Add(GetTypeReference(type.Module, generic_arguments[i]));\n\n            return instance;\n        }\n\n        public static void SplitFullName(string fullname, out string @namespace, out string name)\n        {\n            var last_dot = fullname.LastIndexOf('.');\n\n            if (last_dot == -1)\n            {\n                @namespace = string.Empty;\n                name = fullname;\n            }\n            else\n            {\n                @namespace = fullname.Substring(0, last_dot);\n                name = fullname.Substring(last_dot + 1);\n            }\n        }\n\n        static TypeReference CreateReference(Type type_info, ModuleDefinition module, IMetadataScope scope)\n        {\n            string @namespace, name;\n            SplitFullName(type_info.type_fullname, out @namespace, out name);\n\n            var type = new TypeReference(@namespace, name, module, scope);\n            MetadataSystem.TryProcessPrimitiveTypeReference(type);\n\n            AdjustGenericParameters(type);\n\n            var nested_names = type_info.nested_names;\n            if (Mixin.IsNullOrEmpty(nested_names))\n                return type;\n\n            for (int i = 0; i < nested_names.Length; i++)\n            {\n                type = new TypeReference(string.Empty, nested_names[i], module, null)\n                {\n                    DeclaringType = type,\n                };\n\n                AdjustGenericParameters(type);\n            }\n\n            return type;\n        }\n\n        static void AdjustGenericParameters(TypeReference type)\n        {\n            int arity;\n            if (!TryGetArity(type.Name, out arity))\n                return;\n\n            for (int i = 0; i < arity; i++)\n                type.GenericParameters.Add(new GenericParameter(type));\n        }\n\n        static IMetadataScope GetMetadataScope(ModuleDefinition module, Type type_info)\n        {\n            if (string.IsNullOrEmpty(type_info.assembly))\n                return module.TypeSystem.Corlib;\n\n            return MatchReference(module, AssemblyNameReference.Parse(type_info.assembly));\n        }\n\n        static AssemblyNameReference MatchReference(ModuleDefinition module, AssemblyNameReference pattern)\n        {\n            var references = module.AssemblyReferences;\n\n            for (int i = 0; i < references.Count; i++)\n            {\n                var reference = references[i];\n                if (reference.FullName == pattern.FullName)\n                    return reference;\n            }\n\n            return pattern;\n        }\n\n        static bool TryGetDefinition(ModuleDefinition module, Type type_info, out TypeReference type)\n        {\n            type = null;\n            if (!TryCurrentModule(module, type_info))\n                return false;\n\n            var typedef = module.GetType(type_info.type_fullname);\n            if (typedef == null)\n                return false;\n\n            var nested_names = type_info.nested_names;\n            if (!Mixin.IsNullOrEmpty(nested_names))\n            {\n                for (int i = 0; i < nested_names.Length; i++)\n                    typedef = Mixin.GetNestedType(typedef, nested_names[i]);\n            }\n\n            type = typedef;\n            return true;\n        }\n\n        static bool TryCurrentModule(ModuleDefinition module, Type type_info)\n        {\n            if (string.IsNullOrEmpty(type_info.assembly))\n                return true;\n\n            if (module.assembly != null && module.assembly.Name.FullName == type_info.assembly)\n                return true;\n\n            return false;\n        }\n\n        public static string ToParseable(TypeReference type)\n        {\n            if (type == null)\n                return null;\n\n            var name = new StringBuilder();\n            AppendType(type, name, true, true);\n            return name.ToString();\n        }\n\n        static void AppendType(TypeReference type, StringBuilder name, bool fq_name, bool top_level)\n        {\n            var declaring_type = type.DeclaringType;\n            if (declaring_type != null)\n            {\n                AppendType(declaring_type, name, false, top_level);\n                name.Append('+');\n            }\n\n            var @namespace = type.Namespace;\n            if (!string.IsNullOrEmpty(@namespace))\n            {\n                name.Append(@namespace);\n                name.Append('.');\n            }\n\n            name.Append(type.GetElementType().Name);\n\n            if (!fq_name)\n                return;\n\n            if (Mixin.IsTypeSpecification(type))\n                AppendTypeSpecification((TypeSpecification)type, name);\n\n            if (RequiresFullyQualifiedName(type, top_level))\n            {\n                name.Append(\", \");\n                name.Append(GetScopeFullName(type));\n            }\n        }\n\n        static string GetScopeFullName(TypeReference type)\n        {\n            var scope = type.Scope;\n            switch (scope.MetadataScopeType)\n            {\n                case MetadataScopeType.AssemblyNameReference:\n                    return ((AssemblyNameReference)scope).FullName;\n                case MetadataScopeType.ModuleDefinition:\n                    return ((ModuleDefinition)scope).Assembly.Name.FullName;\n            }\n\n            throw new ArgumentException();\n        }\n\n        static void AppendTypeSpecification(TypeSpecification type, StringBuilder name)\n        {\n            if (Mixin.IsTypeSpecification(type.ElementType))\n                AppendTypeSpecification((TypeSpecification)type.ElementType, name);\n\n            switch (type.etype)\n            {\n                case ElementType.Ptr:\n                    name.Append('*');\n                    break;\n                case ElementType.ByRef:\n                    name.Append('&');\n                    break;\n                case ElementType.SzArray:\n                case ElementType.Array:\n                    var array = (ArrayType)type;\n                    if (array.IsVector)\n                    {\n                        name.Append(\"[]\");\n                    }\n                    else\n                    {\n                        name.Append('[');\n                        for (int i = 1; i < array.Rank; i++)\n                            name.Append(',');\n                        name.Append(']');\n                    }\n                    break;\n                case ElementType.GenericInst:\n                    var instance = (GenericInstanceType)type;\n                    var arguments = instance.GenericArguments;\n\n                    name.Append('[');\n\n                    for (int i = 0; i < arguments.Count; i++)\n                    {\n                        if (i > 0)\n                            name.Append(',');\n\n                        var argument = arguments[i];\n                        var requires_fqname = argument.Scope != argument.Module;\n\n                        if (requires_fqname)\n                            name.Append('[');\n\n                        AppendType(argument, name, true, false);\n\n                        if (requires_fqname)\n                            name.Append(']');\n                    }\n\n                    name.Append(']');\n                    break;\n                default:\n                    return;\n            }\n        }\n\n        static bool RequiresFullyQualifiedName(TypeReference type, bool top_level)\n        {\n            if (type.Scope == type.Module)\n                return false;\n\n            if (type.Scope.Name == \"mscorlib\" && top_level)\n                return false;\n\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeReference.cs",
    "content": "//\n// TypeReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.Metadata;\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil\n{\n\n    public enum MetadataType : byte\n    {\n        Void = ElementType.Void,\n        Boolean = ElementType.Boolean,\n        Char = ElementType.Char,\n        SByte = ElementType.I1,\n        Byte = ElementType.U1,\n        Int16 = ElementType.I2,\n        UInt16 = ElementType.U2,\n        Int32 = ElementType.I4,\n        UInt32 = ElementType.U4,\n        Int64 = ElementType.I8,\n        UInt64 = ElementType.U8,\n        Single = ElementType.R4,\n        Double = ElementType.R8,\n        String = ElementType.String,\n        Pointer = ElementType.Ptr,\n        ByReference = ElementType.ByRef,\n        ValueType = ElementType.ValueType,\n        Class = ElementType.Class,\n        Var = ElementType.Var,\n        Array = ElementType.Array,\n        GenericInstance = ElementType.GenericInst,\n        TypedByReference = ElementType.TypedByRef,\n        IntPtr = ElementType.I,\n        UIntPtr = ElementType.U,\n        FunctionPointer = ElementType.FnPtr,\n        Object = ElementType.Object,\n        MVar = ElementType.MVar,\n        RequiredModifier = ElementType.CModReqD,\n        OptionalModifier = ElementType.CModOpt,\n        Sentinel = ElementType.Sentinel,\n        Pinned = ElementType.Pinned,\n    }\n\n    public class TypeReference : MemberReference, IGenericParameterProvider, IGenericContext\n    {\n\n        string @namespace;\n        bool value_type;\n        int hashCode = -1;\n        static int instance_id;\n        internal IMetadataScope scope;\n        internal ModuleDefinition module;\n\n        internal ElementType etype = ElementType.None;\n\n        string fullname;\n\n        protected Collection<GenericParameter> generic_parameters;\n\n        public override string Name\n        {\n            get { return base.Name; }\n            set\n            {\n                base.Name = value;\n                fullname = null;\n            }\n        }\n\n        public virtual string Namespace\n        {\n            get { return @namespace; }\n            set\n            {\n                @namespace = value;\n                fullname = null;\n            }\n        }\n\n        public virtual bool IsValueType\n        {\n            get { return value_type; }\n            set { value_type = value; }\n        }\n\n        public override ModuleDefinition Module\n        {\n            get\n            {\n                if (module != null)\n                    return module;\n\n                var declaring_type = this.DeclaringType;\n                if (declaring_type != null)\n                    return declaring_type.Module;\n\n                return null;\n            }\n        }\n\n        IGenericParameterProvider IGenericContext.Type\n        {\n            get { return this; }\n        }\n\n        IGenericParameterProvider IGenericContext.Method\n        {\n            get { return null; }\n        }\n\n        GenericParameterType IGenericParameterProvider.GenericParameterType\n        {\n            get { return GenericParameterType.Type; }\n        }\n\n        public virtual bool HasGenericParameters\n        {\n            get { return !Mixin.IsNullOrEmpty(generic_parameters); }\n        }\n\n        public virtual Collection<GenericParameter> GenericParameters\n        {\n            get\n            {\n                if (generic_parameters != null)\n                    return generic_parameters;\n\n                return generic_parameters = new GenericParameterCollection(this);\n            }\n        }\n\n        public virtual IMetadataScope Scope\n        {\n            get\n            {\n                var declaring_type = this.DeclaringType;\n                if (declaring_type != null)\n                    return declaring_type.Scope;\n\n                return scope;\n            }\n        }\n\n        public bool IsNested\n        {\n            get { return this.DeclaringType != null; }\n        }\n\n        public override TypeReference DeclaringType\n        {\n            get { return base.DeclaringType; }\n            set\n            {\n                base.DeclaringType = value;\n                fullname = null;\n            }\n        }\n\n        public override string FullName\n        {\n            get\n            {\n                if (fullname != null)\n                    return fullname;\n\n                if (IsNested)\n                    return fullname = DeclaringType.FullName + \"/\" + Name;\n\n                if (string.IsNullOrEmpty(@namespace))\n                    return fullname = Name;\n\n                return fullname = @namespace + \".\" + Name;\n            }\n        }\n\n        public virtual bool IsByReference\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsPointer\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsSentinel\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsArray\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsGenericParameter\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsGenericInstance\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsRequiredModifier\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsOptionalModifier\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsPinned\n        {\n            get { return false; }\n        }\n\n        public virtual bool IsFunctionPointer\n        {\n            get { return false; }\n        }\n\n        public override int GetHashCode()\n        {\n            if (hashCode == -1)\n                hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);\n            return hashCode;\n        }\n        public virtual bool IsPrimitive\n        {\n            get { return Mixin.IsPrimitive(etype); }\n        }\n\n        public virtual MetadataType MetadataType\n        {\n            get\n            {\n                switch (etype)\n                {\n                    case ElementType.None:\n                        return IsValueType ? MetadataType.ValueType : MetadataType.Class;\n                    default:\n                        return (MetadataType)etype;\n                }\n            }\n        }\n\n        protected TypeReference(string @namespace, string name)\n            : base(name)\n        {\n            this.@namespace = @namespace ?? string.Empty;\n            this.token = new MetadataToken(TokenType.TypeRef, 0);\n        }\n\n        public TypeReference(string @namespace, string name, ModuleDefinition module, IMetadataScope scope)\n            : this(@namespace, name)\n        {\n            this.module = module;\n            this.scope = scope;\n        }\n\n        public TypeReference(string @namespace, string name, ModuleDefinition module, IMetadataScope scope, bool valueType) :\n            this(@namespace, name, module, scope)\n        {\n            value_type = valueType;\n        }\n\n        public virtual TypeReference GetElementType()\n        {\n            return this;\n        }\n\n        public virtual TypeDefinition Resolve()\n        {\n            var module = this.Module;\n            if (module == null)\n                throw new NotSupportedException();\n\n            return module.Resolve(this);\n        }\n    }\n\n    static partial class Mixin\n    {\n\n        public static bool IsPrimitive(ElementType self)\n        {\n            switch (self)\n            {\n                case ElementType.Boolean:\n                case ElementType.Char:\n                case ElementType.I:\n                case ElementType.U:\n                case ElementType.I1:\n                case ElementType.U1:\n                case ElementType.I2:\n                case ElementType.U2:\n                case ElementType.I4:\n                case ElementType.U4:\n                case ElementType.I8:\n                case ElementType.U8:\n                case ElementType.R4:\n                case ElementType.R8:\n                    return true;\n                default:\n                    return false;\n            }\n        }\n\n        public static bool IsTypeOf(TypeReference self, string @namespace, string name)\n        {\n            return self.Name == name\n                && self.Namespace == @namespace;\n        }\n\n        public static bool IsTypeSpecification(TypeReference type)\n        {\n            switch (type.etype)\n            {\n                case ElementType.Array:\n                case ElementType.ByRef:\n                case ElementType.CModOpt:\n                case ElementType.CModReqD:\n                case ElementType.FnPtr:\n                case ElementType.GenericInst:\n                case ElementType.MVar:\n                case ElementType.Pinned:\n                case ElementType.Ptr:\n                case ElementType.SzArray:\n                case ElementType.Sentinel:\n                case ElementType.Var:\n                    return true;\n            }\n\n            return false;\n        }\n\n        public static TypeDefinition CheckedResolve(TypeReference self)\n        {\n            var type = self.Resolve();\n            if (type == null)\n                throw new ResolutionException(self);\n\n            return type;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeSpecification.cs",
    "content": "//\n// TypeSpecification.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil {\n\n\tpublic abstract class TypeSpecification : TypeReference {\n\n\t\treadonly TypeReference element_type;\n\n\t\tpublic TypeReference ElementType {\n\t\t\tget { return element_type; }\n\t\t}\n\n\t\tpublic override string Name {\n\t\t\tget { return element_type.Name; }\n\t\t\tset { throw new NotSupportedException (); }\n\t\t}\n\n\t\tpublic override string Namespace {\n\t\t\tget { return element_type.Namespace; }\n\t\t\tset { throw new NotSupportedException (); }\n\t\t}\n\n\t\tpublic override IMetadataScope Scope {\n\t\t\tget { return element_type.Scope; }\n\t\t}\n\n\t\tpublic override ModuleDefinition Module {\n\t\t\tget { return element_type.Module; }\n\t\t}\n\n\t\tpublic override string FullName {\n\t\t\tget { return element_type.FullName; }\n\t\t}\n\n\t\tinternal override bool ContainsGenericParameter {\n\t\t\tget { return element_type.ContainsGenericParameter; }\n\t\t}\n\n\t\tpublic override MetadataType MetadataType {\n\t\t\tget { return (MetadataType) etype; }\n\t\t}\n\n\t\tinternal TypeSpecification (TypeReference type)\n\t\t\t: base (null, null)\n\t\t{\n\t\t\tthis.element_type = type;\n\t\t\tthis.token = new MetadataToken (TokenType.TypeSpec);\n\t\t}\n\n\t\tpublic override TypeReference GetElementType ()\n\t\t{\n\t\t\treturn element_type;\n\t\t}\n\t}\n\n\tstatic partial class Mixin {\n\n\t\tpublic static void CheckType (TypeReference type)\n\t\t{\n\t\t\tif (type == null)\n\t\t\t\tthrow new ArgumentNullException (\"type\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/TypeSystem.cs",
    "content": "//\n// TypeSystem.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil\n{\n\n    public abstract class TypeSystem\n    {\n\n        sealed class CoreTypeSystem : TypeSystem\n        {\n\n            public CoreTypeSystem(ModuleDefinition module)\n                : base(module)\n            {\n            }\n\n            internal override TypeReference LookupType(string @namespace, string name)\n            {\n                var type = LookupTypeDefinition(@namespace, name) ?? LookupTypeForwarded(@namespace, name);\n                if (type != null)\n                    return type;\n\n                throw new NotSupportedException();\n            }\n\n            TypeReference LookupTypeDefinition(string @namespace, string name)\n            {\n                var metadata = module.MetadataSystem;\n                if (metadata.Types == null)\n                    Initialize(module.Types);\n\n                return module.Read(new Row<string, string>(@namespace, name), (row, reader) =>\n                {\n                    var types = reader.metadata.Types;\n\n                    for (int i = 0; i < types.Length; i++)\n                    {\n                        if (types[i] == null)\n                            types[i] = reader.GetTypeDefinition((uint)i + 1);\n\n                        var type = types[i];\n\n                        if (type.Name == row.Col2 && type.Namespace == row.Col1)\n                            return type;\n                    }\n\n                    return null;\n                });\n            }\n\n            TypeReference LookupTypeForwarded(string @namespace, string name)\n            {\n                if (!module.HasExportedTypes)\n                    return null;\n\n                var exported_types = module.ExportedTypes;\n                for (int i = 0; i < exported_types.Count; i++)\n                {\n                    var exported_type = exported_types[i];\n\n                    if (exported_type.Name == name && exported_type.Namespace == @namespace)\n                        return exported_type.CreateReference();\n                }\n\n                return null;\n            }\n\n            static void Initialize(object obj)\n            {\n            }\n        }\n\n        sealed class CommonTypeSystem : TypeSystem\n        {\n\n            AssemblyNameReference corlib;\n\n            public CommonTypeSystem(ModuleDefinition module)\n                : base(module)\n            {\n            }\n\n            internal override TypeReference LookupType(string @namespace, string name)\n            {\n                return CreateTypeReference(@namespace, name);\n            }\n\n            public AssemblyNameReference GetCorlibReference()\n            {\n                if (corlib != null)\n                    return corlib;\n\n                const string mscorlib = \"mscorlib\";\n                const string systemruntime = \"System.Runtime\";\n\n                var references = module.AssemblyReferences;\n\n                for (int i = 0; i < references.Count; i++)\n                {\n                    var reference = references[i];\n                    if (reference.Name == mscorlib || reference.Name == systemruntime)\n                        return corlib = reference;\n                }\n\n                corlib = new AssemblyNameReference\n                {\n                    Name = mscorlib,\n                    Version = GetCorlibVersion(),\n                    PublicKeyToken = new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 },\n                };\n\n                references.Add(corlib);\n\n                return corlib;\n            }\n\n            Version GetCorlibVersion()\n            {\n                switch (module.Runtime)\n                {\n                    case TargetRuntime.Net_1_0:\n                    case TargetRuntime.Net_1_1:\n                        return new Version(1, 0, 0, 0);\n                    case TargetRuntime.Net_2_0:\n                        return new Version(2, 0, 0, 0);\n                    case TargetRuntime.Net_4_0:\n                        return new Version(4, 0, 0, 0);\n                    default:\n                        throw new NotSupportedException();\n                }\n            }\n\n            TypeReference CreateTypeReference(string @namespace, string name)\n            {\n                return new TypeReference(@namespace, name, module, GetCorlibReference());\n            }\n        }\n\n        readonly ModuleDefinition module;\n\n        TypeReference type_object;\n        TypeReference type_void;\n        TypeReference type_bool;\n        TypeReference type_char;\n        TypeReference type_sbyte;\n        TypeReference type_byte;\n        TypeReference type_int16;\n        TypeReference type_uint16;\n        TypeReference type_int32;\n        TypeReference type_uint32;\n        TypeReference type_int64;\n        TypeReference type_uint64;\n        TypeReference type_single;\n        TypeReference type_double;\n        TypeReference type_intptr;\n        TypeReference type_uintptr;\n        TypeReference type_string;\n        TypeReference type_typedref;\n\n        TypeSystem(ModuleDefinition module)\n        {\n            this.module = module;\n        }\n\n        internal static TypeSystem CreateTypeSystem(ModuleDefinition module)\n        {\n            if (Mixin.IsCorlib(module))\n                return new CoreTypeSystem(module);\n\n            return new CommonTypeSystem(module);\n        }\n\n        internal abstract TypeReference LookupType(string @namespace, string name);\n\n        TypeReference LookupSystemType(ref TypeReference typeRef, string name, ElementType element_type)\n        {\n            lock (module.SyncRoot)\n            {\n                if (typeRef != null)\n                    return typeRef;\n                var type = LookupType(\"System\", name);\n                type.etype = element_type;\n                return typeRef = type;\n            }\n        }\n\n        TypeReference LookupSystemValueType(ref TypeReference typeRef, string name, ElementType element_type)\n        {\n            lock (module.SyncRoot)\n            {\n                if (typeRef != null)\n                    return typeRef;\n                var type = LookupType(\"System\", name);\n                type.etype = element_type;\n                type.IsValueType = true;\n                return typeRef = type;\n            }\n        }\n\n        public IMetadataScope Corlib\n        {\n            get\n            {\n                var common = this as CommonTypeSystem;\n                if (common == null)\n                    return module;\n\n                return common.GetCorlibReference();\n            }\n        }\n\n        public TypeReference Object\n        {\n            get { return type_object ?? (LookupSystemType(ref type_object, \"Object\", ElementType.Object)); }\n        }\n\n        public TypeReference Void\n        {\n            get { return type_void ?? (LookupSystemType(ref type_void, \"Void\", ElementType.Void)); }\n        }\n\n        public TypeReference Boolean\n        {\n            get { return type_bool ?? (LookupSystemValueType(ref type_bool, \"Boolean\", ElementType.Boolean)); }\n        }\n\n        public TypeReference Char\n        {\n            get { return type_char ?? (LookupSystemValueType(ref type_char, \"Char\", ElementType.Char)); }\n        }\n\n        public TypeReference SByte\n        {\n            get { return type_sbyte ?? (LookupSystemValueType(ref type_sbyte, \"SByte\", ElementType.I1)); }\n        }\n\n        public TypeReference Byte\n        {\n            get { return type_byte ?? (LookupSystemValueType(ref type_byte, \"Byte\", ElementType.U1)); }\n        }\n\n        public TypeReference Int16\n        {\n            get { return type_int16 ?? (LookupSystemValueType(ref type_int16, \"Int16\", ElementType.I2)); }\n        }\n\n        public TypeReference UInt16\n        {\n            get { return type_uint16 ?? (LookupSystemValueType(ref type_uint16, \"UInt16\", ElementType.U2)); }\n        }\n\n        public TypeReference Int32\n        {\n            get { return type_int32 ?? (LookupSystemValueType(ref type_int32, \"Int32\", ElementType.I4)); }\n        }\n\n        public TypeReference UInt32\n        {\n            get { return type_uint32 ?? (LookupSystemValueType(ref type_uint32, \"UInt32\", ElementType.U4)); }\n        }\n\n        public TypeReference Int64\n        {\n            get { return type_int64 ?? (LookupSystemValueType(ref type_int64, \"Int64\", ElementType.I8)); }\n        }\n\n        public TypeReference UInt64\n        {\n            get { return type_uint64 ?? (LookupSystemValueType(ref type_uint64, \"UInt64\", ElementType.U8)); }\n        }\n\n        public TypeReference Single\n        {\n            get { return type_single ?? (LookupSystemValueType(ref type_single, \"Single\", ElementType.R4)); }\n        }\n\n        public TypeReference Double\n        {\n            get { return type_double ?? (LookupSystemValueType(ref type_double, \"Double\", ElementType.R8)); }\n        }\n\n        public TypeReference IntPtr\n        {\n            get { return type_intptr ?? (LookupSystemValueType(ref type_intptr, \"IntPtr\", ElementType.I)); }\n        }\n\n        public TypeReference UIntPtr\n        {\n            get { return type_uintptr ?? (LookupSystemValueType(ref type_uintptr, \"UIntPtr\", ElementType.U)); }\n        }\n\n        public TypeReference String\n        {\n            get { return type_string ?? (LookupSystemType(ref type_string, \"String\", ElementType.String)); }\n        }\n\n        public TypeReference TypedReference\n        {\n            get { return type_typedref ?? (LookupSystemValueType(ref type_typedref, \"TypedReference\", ElementType.TypedByRef)); }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil/VariantType.cs",
    "content": "//\n// VariantType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum VariantType {\n\t\tNone = 0,\n\t\tI2 = 2,\n\t\tI4 = 3,\n\t\tR4 = 4,\n\t\tR8 = 5,\n\t\tCY = 6,\n\t\tDate = 7,\n\t\tBStr = 8,\n\t\tDispatch = 9,\n\t\tError = 10,\n\t\tBool = 11,\n\t\tVariant = 12,\n\t\tUnknown = 13,\n\t\tDecimal = 14,\n\t\tI1 = 16,\n\t\tUI1 = 17,\n\t\tUI2 = 18,\n\t\tUI4 = 19,\n\t\tInt = 22,\n\t\tUInt = 23\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/Code.cs",
    "content": "//\n// Code.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic enum Code {\n\t\tNop,\n\t\tBreak,\n\t\tLdarg_0,\n\t\tLdarg_1,\n\t\tLdarg_2,\n\t\tLdarg_3,\n\t\tLdloc_0,\n\t\tLdloc_1,\n\t\tLdloc_2,\n\t\tLdloc_3,\n\t\tStloc_0,\n\t\tStloc_1,\n\t\tStloc_2,\n\t\tStloc_3,\n\t\tLdarg_S,\n\t\tLdarga_S,\n\t\tStarg_S,\n\t\tLdloc_S,\n\t\tLdloca_S,\n\t\tStloc_S,\n\t\tLdnull,\n\t\tLdc_I4_M1,\n\t\tLdc_I4_0,\n\t\tLdc_I4_1,\n\t\tLdc_I4_2,\n\t\tLdc_I4_3,\n\t\tLdc_I4_4,\n\t\tLdc_I4_5,\n\t\tLdc_I4_6,\n\t\tLdc_I4_7,\n\t\tLdc_I4_8,\n\t\tLdc_I4_S,\n\t\tLdc_I4,\n\t\tLdc_I8,\n\t\tLdc_R4,\n\t\tLdc_R8,\n\t\tDup,\n\t\tPop,\n\t\tJmp,\n\t\tCall,\n\t\tCalli,\n\t\tRet,\n\t\tBr_S,\n\t\tBrfalse_S,\n\t\tBrtrue_S,\n\t\tBeq_S,\n\t\tBge_S,\n\t\tBgt_S,\n\t\tBle_S,\n\t\tBlt_S,\n\t\tBne_Un_S,\n\t\tBge_Un_S,\n\t\tBgt_Un_S,\n\t\tBle_Un_S,\n\t\tBlt_Un_S,\n\t\tBr,\n\t\tBrfalse,\n\t\tBrtrue,\n\t\tBeq,\n\t\tBge,\n\t\tBgt,\n\t\tBle,\n\t\tBlt,\n\t\tBne_Un,\n\t\tBge_Un,\n\t\tBgt_Un,\n\t\tBle_Un,\n\t\tBlt_Un,\n\t\tSwitch,\n\t\tLdind_I1,\n\t\tLdind_U1,\n\t\tLdind_I2,\n\t\tLdind_U2,\n\t\tLdind_I4,\n\t\tLdind_U4,\n\t\tLdind_I8,\n\t\tLdind_I,\n\t\tLdind_R4,\n\t\tLdind_R8,\n\t\tLdind_Ref,\n\t\tStind_Ref,\n\t\tStind_I1,\n\t\tStind_I2,\n\t\tStind_I4,\n\t\tStind_I8,\n\t\tStind_R4,\n\t\tStind_R8,\n\t\tAdd,\n\t\tSub,\n\t\tMul,\n\t\tDiv,\n\t\tDiv_Un,\n\t\tRem,\n\t\tRem_Un,\n\t\tAnd,\n\t\tOr,\n\t\tXor,\n\t\tShl,\n\t\tShr,\n\t\tShr_Un,\n\t\tNeg,\n\t\tNot,\n\t\tConv_I1,\n\t\tConv_I2,\n\t\tConv_I4,\n\t\tConv_I8,\n\t\tConv_R4,\n\t\tConv_R8,\n\t\tConv_U4,\n\t\tConv_U8,\n\t\tCallvirt,\n\t\tCpobj,\n\t\tLdobj,\n\t\tLdstr,\n\t\tNewobj,\n\t\tCastclass,\n\t\tIsinst,\n\t\tConv_R_Un,\n\t\tUnbox,\n\t\tThrow,\n\t\tLdfld,\n\t\tLdflda,\n\t\tStfld,\n\t\tLdsfld,\n\t\tLdsflda,\n\t\tStsfld,\n\t\tStobj,\n\t\tConv_Ovf_I1_Un,\n\t\tConv_Ovf_I2_Un,\n\t\tConv_Ovf_I4_Un,\n\t\tConv_Ovf_I8_Un,\n\t\tConv_Ovf_U1_Un,\n\t\tConv_Ovf_U2_Un,\n\t\tConv_Ovf_U4_Un,\n\t\tConv_Ovf_U8_Un,\n\t\tConv_Ovf_I_Un,\n\t\tConv_Ovf_U_Un,\n\t\tBox,\n\t\tNewarr,\n\t\tLdlen,\n\t\tLdelema,\n\t\tLdelem_I1,\n\t\tLdelem_U1,\n\t\tLdelem_I2,\n\t\tLdelem_U2,\n\t\tLdelem_I4,\n\t\tLdelem_U4,\n\t\tLdelem_I8,\n\t\tLdelem_I,\n\t\tLdelem_R4,\n\t\tLdelem_R8,\n\t\tLdelem_Ref,\n\t\tStelem_I,\n\t\tStelem_I1,\n\t\tStelem_I2,\n\t\tStelem_I4,\n\t\tStelem_I8,\n\t\tStelem_R4,\n\t\tStelem_R8,\n\t\tStelem_Ref,\n\t\tLdelem_Any,\n\t\tStelem_Any,\n\t\tUnbox_Any,\n\t\tConv_Ovf_I1,\n\t\tConv_Ovf_U1,\n\t\tConv_Ovf_I2,\n\t\tConv_Ovf_U2,\n\t\tConv_Ovf_I4,\n\t\tConv_Ovf_U4,\n\t\tConv_Ovf_I8,\n\t\tConv_Ovf_U8,\n\t\tRefanyval,\n\t\tCkfinite,\n\t\tMkrefany,\n\t\tLdtoken,\n\t\tConv_U2,\n\t\tConv_U1,\n\t\tConv_I,\n\t\tConv_Ovf_I,\n\t\tConv_Ovf_U,\n\t\tAdd_Ovf,\n\t\tAdd_Ovf_Un,\n\t\tMul_Ovf,\n\t\tMul_Ovf_Un,\n\t\tSub_Ovf,\n\t\tSub_Ovf_Un,\n\t\tEndfinally,\n\t\tLeave,\n\t\tLeave_S,\n\t\tStind_I,\n\t\tConv_U,\n\t\tArglist,\n\t\tCeq,\n\t\tCgt,\n\t\tCgt_Un,\n\t\tClt,\n\t\tClt_Un,\n\t\tLdftn,\n\t\tLdvirtftn,\n\t\tLdarg,\n\t\tLdarga,\n\t\tStarg,\n\t\tLdloc,\n\t\tLdloca,\n\t\tStloc,\n\t\tLocalloc,\n\t\tEndfilter,\n\t\tUnaligned,\n\t\tVolatile,\n\t\tTail,\n\t\tInitobj,\n\t\tConstrained,\n\t\tCpblk,\n\t\tInitblk,\n\t\tNo,\n\t\tRethrow,\n\t\tSizeof,\n\t\tRefanytype,\n\t\tReadonly,\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/CodeReader.cs",
    "content": "//\n// CodeReader.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.PE;\nusing Mono.Collections.Generic;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil.Cil\n{\n\n    sealed class CodeReader : ByteBuffer\n    {\n\n        readonly internal MetadataReader reader;\n\n        int start;\n        Section code_section;\n\n        MethodDefinition method;\n        MethodBody body;\n\n        int Offset\n        {\n            get { return base.position - start; }\n        }\n\n        public CodeReader(Section section, MetadataReader reader)\n            : base(section.Data)\n        {\n            this.code_section = section;\n            this.reader = reader;\n        }\n\n        public MethodBody ReadMethodBody(MethodDefinition method)\n        {\n            this.method = method;\n            this.body = new MethodBody(method);\n\n            reader.context = method;\n\n            ReadMethodBody();\n\n            return this.body;\n        }\n\n        public void MoveTo(int rva)\n        {\n            if (!IsInSection(rva))\n            {\n                code_section = reader.image.GetSectionAtVirtualAddress((uint)rva);\n                Reset(code_section.Data);\n            }\n\n            base.position = rva - (int)code_section.VirtualAddress;\n        }\n\n        bool IsInSection(int rva)\n        {\n            return code_section.VirtualAddress <= rva && rva < code_section.VirtualAddress + code_section.SizeOfRawData;\n        }\n\n        void ReadMethodBody()\n        {\n            MoveTo(method.RVA);\n\n            var flags = ReadByte();\n            switch (flags & 0x3)\n            {\n                case 0x2: // tiny\n                    body.code_size = flags >> 2;\n                    body.MaxStackSize = 8;\n                    ReadCode();\n                    break;\n                case 0x3: // fat\n                    base.position--;\n                    ReadFatMethod();\n                    break;\n                default:\n                    throw new InvalidOperationException();\n            }\n\n            var symbol_reader = reader.module.symbol_reader;\n\n            if (symbol_reader != null)\n            {\n                var instructions = body.Instructions;\n                symbol_reader.Read(body, offset => GetInstruction(instructions, offset));\n            }\n        }\n\n        void ReadFatMethod()\n        {\n            var flags = ReadUInt16();\n            body.max_stack_size = ReadUInt16();\n            body.code_size = (int)ReadUInt32();\n            body.local_var_token = new MetadataToken(ReadUInt32());\n            body.init_locals = (flags & 0x10) != 0;\n\n            if (body.local_var_token.RID != 0)\n                body.variables = ReadVariables(body.local_var_token);\n\n            ReadCode();\n\n            if ((flags & 0x8) != 0)\n                ReadSection();\n        }\n\n        public VariableDefinitionCollection ReadVariables(MetadataToken local_var_token)\n        {\n            var position = reader.position;\n            var variables = reader.ReadVariables(local_var_token);\n            reader.position = position;\n\n            return variables;\n        }\n\n        void ReadCode()\n        {\n            start = position;\n            var code_size = body.code_size;\n\n            if (code_size < 0 || buffer.Length <= (uint)(code_size + position))\n                code_size = 0;\n\n            var end = start + code_size;\n            var instructions = body.instructions = new InstructionCollection((code_size + 1) / 2);\n\n            while (position < end)\n            {\n                var offset = base.position - start;\n                var opcode = ReadOpCode();\n                var current = new Instruction(offset, opcode);\n\n                if (opcode.OperandType != OperandType.InlineNone)\n                    current.operand = ReadOperand(current);\n\n                instructions.Add(current);\n            }\n\n            ResolveBranches(instructions);\n        }\n\n        OpCode ReadOpCode()\n        {\n            var il_opcode = ReadByte();\n            return il_opcode != 0xfe\n                ? OpCodes.OneByteOpCode[il_opcode]\n                : OpCodes.TwoBytesOpCode[ReadByte()];\n        }\n\n        object ReadOperand(Instruction instruction)\n        {\n            switch (instruction.opcode.OperandType)\n            {\n                case OperandType.InlineSwitch:\n                    var length = ReadInt32();\n                    var base_offset = Offset + (4 * length);\n                    var branches = new int[length];\n                    for (int i = 0; i < length; i++)\n                        branches[i] = base_offset + ReadInt32();\n                    return branches;\n                case OperandType.ShortInlineBrTarget:\n                    return ReadSByte() + Offset;\n                case OperandType.InlineBrTarget:\n                    return ReadInt32() + Offset;\n                case OperandType.ShortInlineI:\n                    if (instruction.opcode == OpCodes.Ldc_I4_S)\n                        return ReadSByte();\n\n                    return ReadByte();\n                case OperandType.InlineI:\n                    return ReadInt32();\n                case OperandType.ShortInlineR:\n                    return ReadSingle();\n                case OperandType.InlineR:\n                    return ReadDouble();\n                case OperandType.InlineI8:\n                    return ReadInt64();\n                case OperandType.ShortInlineVar:\n                    return GetVariable(ReadByte());\n                case OperandType.InlineVar:\n                    return GetVariable(ReadUInt16());\n                case OperandType.ShortInlineArg:\n                    return GetParameter(ReadByte());\n                case OperandType.InlineArg:\n                    return GetParameter(ReadUInt16());\n                case OperandType.InlineSig:\n                    return GetCallSite(ReadToken());\n                case OperandType.InlineString:\n                    return GetString(ReadToken());\n                case OperandType.InlineTok:\n                case OperandType.InlineType:\n                case OperandType.InlineMethod:\n                case OperandType.InlineField:\n                    return reader.LookupToken(ReadToken());\n                default:\n                    throw new NotSupportedException();\n            }\n        }\n\n        public string GetString(MetadataToken token)\n        {\n            return reader.image.UserStringHeap.Read(token.RID);\n        }\n\n        public ParameterDefinition GetParameter(int index)\n        {\n            return Mixin.GetParameter(body, index);\n        }\n\n        public VariableDefinition GetVariable(int index)\n        {\n            return Mixin.GetVariable(body, index);\n        }\n\n        public CallSite GetCallSite(MetadataToken token)\n        {\n            return reader.ReadCallSite(token);\n        }\n\n        void ResolveBranches(Collection<Instruction> instructions)\n        {\n            var items = instructions.items;\n            var size = instructions.size;\n\n            for (int i = 0; i < size; i++)\n            {\n                var instruction = items[i];\n                switch (instruction.opcode.OperandType)\n                {\n                    case OperandType.ShortInlineBrTarget:\n                    case OperandType.InlineBrTarget:\n                        instruction.operand = GetInstruction((int)instruction.operand);\n                        break;\n                    case OperandType.InlineSwitch:\n                        var offsets = (int[])instruction.operand;\n                        var branches = new Instruction[offsets.Length];\n                        for (int j = 0; j < offsets.Length; j++)\n                            branches[j] = GetInstruction(offsets[j]);\n\n                        instruction.operand = branches;\n                        break;\n                }\n            }\n        }\n\n        Instruction GetInstruction(int offset)\n        {\n            return GetInstruction(body.Instructions, offset);\n        }\n\n        static Instruction GetInstruction(Collection<Instruction> instructions, int offset)\n        {\n            var size = instructions.size;\n            var items = instructions.items;\n            if (offset < 0 || offset > items[size - 1].offset)\n                return null;\n\n            int min = 0;\n            int max = size - 1;\n            while (min <= max)\n            {\n                int mid = min + ((max - min) / 2);\n                var instruction = items[mid];\n                var instruction_offset = instruction.offset;\n\n                if (offset == instruction_offset)\n                    return instruction;\n\n                if (offset < instruction_offset)\n                    max = mid - 1;\n                else\n                    min = mid + 1;\n            }\n\n            return null;\n        }\n\n        void ReadSection()\n        {\n            Align(4);\n\n            const byte fat_format = 0x40;\n            const byte more_sects = 0x80;\n\n            var flags = ReadByte();\n            if ((flags & fat_format) == 0)\n                ReadSmallSection();\n            else\n                ReadFatSection();\n\n            if ((flags & more_sects) != 0)\n                ReadSection();\n        }\n\n        void ReadSmallSection()\n        {\n            var count = ReadByte() / 12;\n            Advance(2);\n\n            ReadExceptionHandlers(\n                count,\n                () => (int)ReadUInt16(),\n                () => (int)ReadByte());\n        }\n\n        void ReadFatSection()\n        {\n            position--;\n            var count = (ReadInt32() >> 8) / 24;\n\n            ReadExceptionHandlers(\n                count,\n                ReadInt32,\n                ReadInt32);\n        }\n\n        // inline ?\n        void ReadExceptionHandlers(int count, Func<int> read_entry, Func<int> read_length)\n        {\n            for (int i = 0; i < count; i++)\n            {\n                var handler = new ExceptionHandler(\n                    (ExceptionHandlerType)(read_entry() & 0x7));\n\n                handler.TryStart = GetInstruction(read_entry());\n                handler.TryEnd = GetInstruction(handler.TryStart.Offset + read_length());\n\n                handler.HandlerStart = GetInstruction(read_entry());\n                handler.HandlerEnd = GetInstruction(handler.HandlerStart.Offset + read_length());\n\n                ReadExceptionHandlerSpecific(handler);\n\n                this.body.ExceptionHandlers.Add(handler);\n            }\n        }\n\n        void ReadExceptionHandlerSpecific(ExceptionHandler handler)\n        {\n            switch (handler.HandlerType)\n            {\n                case ExceptionHandlerType.Catch:\n                    handler.CatchType = (TypeReference)reader.LookupToken(ReadToken());\n                    break;\n                case ExceptionHandlerType.Filter:\n                    handler.FilterStart = GetInstruction(ReadInt32());\n                    break;\n                default:\n                    Advance(4);\n                    break;\n            }\n        }\n\n        void Align(int align)\n        {\n            align--;\n            Advance(((position + align) & ~align) - position);\n        }\n\n        public MetadataToken ReadToken()\n        {\n            return new MetadataToken(ReadUInt32());\n        }\n\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/CodeWriter.cs",
    "content": "//\n// CodeWriter.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\n\nusing Mono.Collections.Generic;\n\nusing Mono.Cecil.Metadata;\nusing Mono.Cecil.PE;\n\nusing RVA = System.UInt32;\n\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/Document.cs",
    "content": "//\n// Document.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic enum DocumentType {\n\t\tOther,\n\t\tText,\n\t}\n\n\tpublic enum DocumentHashAlgorithm {\n\t\tNone,\n\t\tMD5,\n\t\tSHA1,\n\t}\n\n\tpublic enum DocumentLanguage {\n\t\tOther,\n\t\tC,\n\t\tCpp,\n\t\tCSharp,\n\t\tBasic,\n\t\tJava,\n\t\tCobol,\n\t\tPascal,\n\t\tCil,\n\t\tJScript,\n\t\tSmc,\n\t\tMCpp,\n\t\tFSharp,\n\t}\n\n\tpublic enum DocumentLanguageVendor {\n\t\tOther,\n\t\tMicrosoft,\n\t}\n\n\tpublic sealed class Document {\n\n\t\tstring url;\n\n\t\tbyte type;\n\t\tbyte hash_algorithm;\n\t\tbyte language;\n\t\tbyte language_vendor;\n\n\t\tbyte [] hash;\n\n\t\tpublic string Url {\n\t\t\tget { return url; }\n\t\t\tset { url = value; }\n\t\t}\n\n\t\tpublic DocumentType Type {\n\t\t\tget { return (DocumentType) type; }\n\t\t\tset { type = (byte) value; }\n\t\t}\n\n\t\tpublic DocumentHashAlgorithm HashAlgorithm {\n\t\t\tget { return (DocumentHashAlgorithm) hash_algorithm; }\n\t\t\tset { hash_algorithm = (byte) value; }\n\t\t}\n\n\t\tpublic DocumentLanguage Language {\n\t\t\tget { return (DocumentLanguage) language; }\n\t\t\tset { language = (byte) value; }\n\t\t}\n\n\t\tpublic DocumentLanguageVendor LanguageVendor {\n\t\t\tget { return (DocumentLanguageVendor) language_vendor; }\n\t\t\tset { language_vendor = (byte) value; }\n\t\t}\n\n\t\tpublic byte [] Hash {\n\t\t\tget { return hash; }\n\t\t\tset { hash = value; }\n\t\t}\n\n\t\tpublic Document (string url)\n\t\t{\n\t\t\tthis.url = url;\n\t\t\tthis.hash = Empty<byte>.Array;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/ExceptionHandler.cs",
    "content": "//\n// ExceptionHandler.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic enum ExceptionHandlerType {\n\t\tCatch = 0,\n\t\tFilter = 1,\n\t\tFinally = 2,\n\t\tFault = 4,\n\t}\n\n\tpublic sealed class ExceptionHandler {\n\n\t\tInstruction try_start;\n\t\tInstruction try_end;\n\t\tInstruction filter_start;\n\t\tInstruction handler_start;\n\t\tInstruction handler_end;\n\n\t\tTypeReference catch_type;\n\t\tExceptionHandlerType handler_type;\n\n\t\tpublic Instruction TryStart {\n\t\t\tget { return try_start; }\n\t\t\tset { try_start = value; }\n\t\t}\n\n\t\tpublic Instruction TryEnd {\n\t\t\tget { return try_end; }\n\t\t\tset { try_end = value; }\n\t\t}\n\n\t\tpublic Instruction FilterStart {\n\t\t\tget { return filter_start; }\n\t\t\tset { filter_start = value; }\n\t\t}\n\n\t\tpublic Instruction HandlerStart {\n\t\t\tget { return handler_start; }\n\t\t\tset { handler_start = value; }\n\t\t}\n\n\t\tpublic Instruction HandlerEnd {\n\t\t\tget { return handler_end; }\n\t\t\tset { handler_end = value; }\n\t\t}\n\n\t\tpublic TypeReference CatchType {\n\t\t\tget { return catch_type; }\n\t\t\tset { catch_type = value; }\n\t\t}\n\n\t\tpublic ExceptionHandlerType HandlerType {\n\t\t\tget { return handler_type; }\n\t\t\tset { handler_type = value; }\n\t\t}\n\n\t\tpublic ExceptionHandler (ExceptionHandlerType handlerType)\n\t\t{\n\t\t\tthis.handler_type = handlerType;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/ILProcessor.cs",
    "content": "//\n// ILProcessor.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic sealed class ILProcessor {\n\n\t\treadonly MethodBody body;\n\t\treadonly Collection<Instruction> instructions;\n\n\t\tpublic MethodBody Body {\n\t\t\tget { return body; }\n\t\t}\n\n\t\tinternal ILProcessor (MethodBody body)\n\t\t{\n\t\t\tthis.body = body;\n\t\t\tthis.instructions = body.Instructions;\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode)\n\t\t{\n\t\t\treturn Instruction.Create (opcode);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, TypeReference type)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, type);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, CallSite site)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, site);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, MethodReference method)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, method);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, FieldReference field)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, field);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, string value)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, sbyte value)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, byte value)\n\t\t{\n\t\t\tif (opcode.OperandType == OperandType.ShortInlineVar)\n\t\t\t\treturn Instruction.Create (opcode, body.Variables [value]);\n\n\t\t\tif (opcode.OperandType == OperandType.ShortInlineArg)\n\t\t\t\treturn Instruction.Create (opcode, Mixin.GetParameter (body,value));\n\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, int value)\n\t\t{\n\t\t\tif (opcode.OperandType == OperandType.InlineVar)\n\t\t\t\treturn Instruction.Create (opcode, body.Variables [value]);\n\n\t\t\tif (opcode.OperandType == OperandType.InlineArg)\n\t\t\t\treturn Instruction.Create (opcode, Mixin.GetParameter (body,value));\n\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, long value)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, float value)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, double value)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, value);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, Instruction target)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, target);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, Instruction [] targets)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, targets);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, VariableDefinition variable)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, variable);\n\t\t}\n\n\t\tpublic Instruction Create (OpCode opcode, ParameterDefinition parameter)\n\t\t{\n\t\t\treturn Instruction.Create (opcode, parameter);\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode)\n\t\t{\n\t\t\tAppend (Create (opcode));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, TypeReference type)\n\t\t{\n\t\t\tAppend (Create (opcode, type));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, MethodReference method)\n\t\t{\n\t\t\tAppend (Create (opcode, method));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, CallSite site)\n\t\t{\n\t\t\tAppend (Create (opcode, site));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, FieldReference field)\n\t\t{\n\t\t\tAppend (Create (opcode, field));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, string value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, byte value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, sbyte value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, int value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, long value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, float value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, double value)\n\t\t{\n\t\t\tAppend (Create (opcode, value));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, Instruction target)\n\t\t{\n\t\t\tAppend (Create (opcode, target));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, Instruction [] targets)\n\t\t{\n\t\t\tAppend (Create (opcode, targets));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, VariableDefinition variable)\n\t\t{\n\t\t\tAppend (Create (opcode, variable));\n\t\t}\n\n\t\tpublic void Emit (OpCode opcode, ParameterDefinition parameter)\n\t\t{\n\t\t\tAppend (Create (opcode, parameter));\n\t\t}\n\n\t\tpublic void InsertBefore (Instruction target, Instruction instruction)\n\t\t{\n\t\t\tif (target == null)\n\t\t\t\tthrow new ArgumentNullException (\"target\");\n\t\t\tif (instruction == null)\n\t\t\t\tthrow new ArgumentNullException (\"instruction\");\n\n\t\t\tvar index = instructions.IndexOf (target);\n\t\t\tif (index == -1)\n\t\t\t\tthrow new ArgumentOutOfRangeException (\"target\");\n\n\t\t\tinstructions.Insert (index, instruction);\n\t\t}\n\n\t\tpublic void InsertAfter (Instruction target, Instruction instruction)\n\t\t{\n\t\t\tif (target == null)\n\t\t\t\tthrow new ArgumentNullException (\"target\");\n\t\t\tif (instruction == null)\n\t\t\t\tthrow new ArgumentNullException (\"instruction\");\n\n\t\t\tvar index = instructions.IndexOf (target);\n\t\t\tif (index == -1)\n\t\t\t\tthrow new ArgumentOutOfRangeException (\"target\");\n\n\t\t\tinstructions.Insert (index + 1, instruction);\n\t\t}\n\n\t\tpublic void Append (Instruction instruction)\n\t\t{\n\t\t\tif (instruction == null)\n\t\t\t\tthrow new ArgumentNullException (\"instruction\");\n\n\t\t\tinstructions.Add (instruction);\n\t\t}\n\n\t\tpublic void Replace (Instruction target, Instruction instruction)\n\t\t{\n\t\t\tif (target == null)\n\t\t\t\tthrow new ArgumentNullException (\"target\");\n\t\t\tif (instruction == null)\n\t\t\t\tthrow new ArgumentNullException (\"instruction\");\n\n\t\t\tInsertAfter (target, instruction);\n\t\t\tRemove (target);\n\t\t}\n\n\t\tpublic void Remove (Instruction instruction)\n\t\t{\n\t\t\tif (instruction == null)\n\t\t\t\tthrow new ArgumentNullException (\"instruction\");\n\n\t\t\tif (!instructions.Remove (instruction))\n\t\t\t\tthrow new ArgumentOutOfRangeException (\"instruction\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/Instruction.cs",
    "content": "//\n// Instruction.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Text;\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic sealed class Instruction {\n\n\t\tinternal int offset;\n\t\tinternal OpCode opcode;\n\t\tinternal object operand;\n\n\t\tinternal Instruction previous;\n\t\tinternal Instruction next;\n\n\t\tSequencePoint sequence_point;\n\n\t\tpublic int Offset {\n\t\t\tget { return offset; }\n\t\t\tset { offset = value; }\n\t\t}\n\n\t\tpublic OpCode OpCode {\n\t\t\tget { return opcode; }\n\t\t\tset { opcode = value; }\n\t\t}\n\n\t\tpublic object Operand {\n\t\t\tget { return operand; }\n\t\t\tset { operand = value; }\n\t\t}\n\n\t\tpublic Instruction Previous {\n\t\t\tget { return previous; }\n\t\t\tset { previous = value; }\n\t\t}\n\n\t\tpublic Instruction Next {\n\t\t\tget { return next; }\n\t\t\tset { next = value; }\n\t\t}\n\n\t\tpublic SequencePoint SequencePoint {\n\t\t\tget { return sequence_point; }\n\t\t\tset { sequence_point = value; }\n\t\t}\n\n\t\tinternal Instruction (int offset, OpCode opCode)\n\t\t{\n\t\t\tthis.offset = offset;\n\t\t\tthis.opcode = opCode;\n\t\t}\n\n\t\tinternal Instruction (OpCode opcode, object operand)\n\t\t{\n\t\t\tthis.opcode = opcode;\n\t\t\tthis.operand = operand;\n\t\t}\n\n\t\tpublic int GetSize ()\n\t\t{\n\t\t\tint size = opcode.Size;\n\n\t\t\tswitch (opcode.OperandType) {\n\t\t\tcase OperandType.InlineSwitch:\n\t\t\t\treturn size + (1 + ((Instruction []) operand).Length) * 4;\n\t\t\tcase OperandType.InlineI8:\n\t\t\tcase OperandType.InlineR:\n\t\t\t\treturn size + 8;\n\t\t\tcase OperandType.InlineBrTarget:\n\t\t\tcase OperandType.InlineField:\n\t\t\tcase OperandType.InlineI:\n\t\t\tcase OperandType.InlineMethod:\n\t\t\tcase OperandType.InlineString:\n\t\t\tcase OperandType.InlineTok:\n\t\t\tcase OperandType.InlineType:\n\t\t\tcase OperandType.ShortInlineR:\n\t\t\tcase OperandType.InlineSig:\n\t\t\t\treturn size + 4;\n\t\t\tcase OperandType.InlineArg:\n\t\t\tcase OperandType.InlineVar:\n\t\t\t\treturn size + 2;\n\t\t\tcase OperandType.ShortInlineBrTarget:\n\t\t\tcase OperandType.ShortInlineI:\n\t\t\tcase OperandType.ShortInlineArg:\n\t\t\tcase OperandType.ShortInlineVar:\n\t\t\t\treturn size + 1;\n\t\t\tdefault:\n\t\t\t\treturn size;\n\t\t\t}\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\tvar instruction = new StringBuilder ();\n\n\t\t\tAppendLabel (instruction, this);\n\t\t\tinstruction.Append (':');\n\t\t\tinstruction.Append (' ');\n\t\t\tinstruction.Append (opcode.Name);\n\n\t\t\tif (operand == null)\n\t\t\t\treturn instruction.ToString ();\n\n\t\t\tinstruction.Append (' ');\n\n\t\t\tswitch (opcode.OperandType) {\n\t\t\tcase OperandType.ShortInlineBrTarget:\n\t\t\tcase OperandType.InlineBrTarget:\n\t\t\t\tAppendLabel (instruction, (Instruction) operand);\n\t\t\t\tbreak;\n\t\t\tcase OperandType.InlineSwitch:\n\t\t\t\tvar labels = (Instruction []) operand;\n\t\t\t\tfor (int i = 0; i < labels.Length; i++) {\n\t\t\t\t\tif (i > 0)\n\t\t\t\t\t\tinstruction.Append (',');\n\n\t\t\t\t\tAppendLabel (instruction, labels [i]);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OperandType.InlineString:\n\t\t\t\tinstruction.Append ('\\\"');\n\t\t\t\tinstruction.Append (operand);\n\t\t\t\tinstruction.Append ('\\\"');\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tinstruction.Append (operand);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn instruction.ToString ();\n\t\t}\n\n\t\tstatic void AppendLabel (StringBuilder builder, Instruction instruction)\n\t\t{\n\t\t\tbuilder.Append (\"IL_\");\n\t\t\tbuilder.Append (instruction.offset.ToString (\"x4\"));\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.InlineNone)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, null);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, TypeReference type)\n\t\t{\n\t\t\tif (type == null)\n\t\t\t\tthrow new ArgumentNullException (\"type\");\n\t\t\tif (opcode.OperandType != OperandType.InlineType &&\n\t\t\t\topcode.OperandType != OperandType.InlineTok)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, type);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, CallSite site)\n\t\t{\n\t\t\tif (site == null)\n\t\t\t\tthrow new ArgumentNullException (\"site\");\n\t\t\tif (opcode.Code != Code.Calli)\n\t\t\t\tthrow new ArgumentException (\"code\");\n\n\t\t\treturn new Instruction (opcode, site);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, MethodReference method)\n\t\t{\n\t\t\tif (method == null)\n\t\t\t\tthrow new ArgumentNullException (\"method\");\n\t\t\tif (opcode.OperandType != OperandType.InlineMethod &&\n\t\t\t\topcode.OperandType != OperandType.InlineTok)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, method);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, FieldReference field)\n\t\t{\n\t\t\tif (field == null)\n\t\t\t\tthrow new ArgumentNullException (\"field\");\n\t\t\tif (opcode.OperandType != OperandType.InlineField &&\n\t\t\t\topcode.OperandType != OperandType.InlineTok)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, field);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, string value)\n\t\t{\n\t\t\tif (value == null)\n\t\t\t\tthrow new ArgumentNullException (\"value\");\n\t\t\tif (opcode.OperandType != OperandType.InlineString)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, sbyte value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.ShortInlineI &&\n\t\t\t\topcode != OpCodes.Ldc_I4_S)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, byte value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.ShortInlineI ||\n\t\t\t\topcode == OpCodes.Ldc_I4_S)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, int value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.InlineI)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, long value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.InlineI8)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, float value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.ShortInlineR)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, double value)\n\t\t{\n\t\t\tif (opcode.OperandType != OperandType.InlineR)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, value);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, Instruction target)\n\t\t{\n\t\t\tif (target == null)\n\t\t\t\tthrow new ArgumentNullException (\"target\");\n\t\t\tif (opcode.OperandType != OperandType.InlineBrTarget &&\n\t\t\t\topcode.OperandType != OperandType.ShortInlineBrTarget)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, target);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, Instruction [] targets)\n\t\t{\n\t\t\tif (targets == null)\n\t\t\t\tthrow new ArgumentNullException (\"targets\");\n\t\t\tif (opcode.OperandType != OperandType.InlineSwitch)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, targets);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, VariableDefinition variable)\n\t\t{\n\t\t\tif (variable == null)\n\t\t\t\tthrow new ArgumentNullException (\"variable\");\n\t\t\tif (opcode.OperandType != OperandType.ShortInlineVar &&\n\t\t\t\topcode.OperandType != OperandType.InlineVar)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, variable);\n\t\t}\n\n\t\tpublic static Instruction Create (OpCode opcode, ParameterDefinition parameter)\n\t\t{\n\t\t\tif (parameter == null)\n\t\t\t\tthrow new ArgumentNullException (\"parameter\");\n\t\t\tif (opcode.OperandType != OperandType.ShortInlineArg &&\n\t\t\t\topcode.OperandType != OperandType.InlineArg)\n\t\t\t\tthrow new ArgumentException (\"opcode\");\n\n\t\t\treturn new Instruction (opcode, parameter);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/MethodBody.cs",
    "content": "//\n// MethodBody.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Threading;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil.Cil\n{\n\n    public sealed class MethodBody : IVariableDefinitionProvider\n    {\n\n        readonly internal MethodDefinition method;\n\n        internal ParameterDefinition this_parameter;\n        internal int max_stack_size;\n        internal int code_size;\n        internal bool init_locals;\n        internal MetadataToken local_var_token;\n\n        internal Collection<Instruction> instructions;\n        internal Collection<ExceptionHandler> exceptions;\n        internal Collection<VariableDefinition> variables;\n        Scope scope;\n\n        public MethodDefinition Method\n        {\n            get { return method; }\n        }\n\n        public int MaxStackSize\n        {\n            get { return max_stack_size; }\n            set { max_stack_size = value; }\n        }\n\n        public int CodeSize\n        {\n            get { return code_size; }\n        }\n\n        public bool InitLocals\n        {\n            get { return init_locals; }\n            set { init_locals = value; }\n        }\n\n        public MetadataToken LocalVarToken\n        {\n            get { return local_var_token; }\n            set { local_var_token = value; }\n        }\n\n        public Collection<Instruction> Instructions\n        {\n            get { return instructions ?? (instructions = new InstructionCollection()); }\n        }\n\n        public bool HasExceptionHandlers\n        {\n            get { return !Mixin.IsNullOrEmpty(exceptions); }\n        }\n\n        public Collection<ExceptionHandler> ExceptionHandlers\n        {\n            get { return exceptions ?? (exceptions = new Collection<ExceptionHandler>()); }\n        }\n\n        public bool HasVariables\n        {\n            get { return !Mixin.IsNullOrEmpty(variables); }\n        }\n\n        public Collection<VariableDefinition> Variables\n        {\n            get { return variables ?? (variables = new VariableDefinitionCollection()); }\n        }\n\n        public Scope Scope\n        {\n            get { return scope; }\n            set { scope = value; }\n        }\n\n        public ParameterDefinition ThisParameter\n        {\n            get\n            {\n                if (method == null || method.DeclaringType == null)\n                    throw new NotSupportedException();\n\n                if (!method.HasThis)\n                    return null;\n\n                if (this_parameter == null)\n                    this_parameter = ThisParameterFor(method);\n\n                return this_parameter;\n            }\n        }\n\n        static ParameterDefinition ThisParameterFor(MethodDefinition method)\n        {\n            var declaring_type = method.DeclaringType;\n            var type = declaring_type.IsValueType || declaring_type.IsPrimitive\n                ? new PointerType(declaring_type)\n                : declaring_type as TypeReference;\n\n            return new ParameterDefinition(type, method);\n        }\n\n        public MethodBody(MethodDefinition method)\n        {\n            this.method = method;\n        }\n\n        public ILProcessor GetILProcessor()\n        {\n            return new ILProcessor(this);\n        }\n    }\n\n    public interface IVariableDefinitionProvider\n    {\n        bool HasVariables { get; }\n        Collection<VariableDefinition> Variables { get; }\n    }\n\n    class VariableDefinitionCollection : Collection<VariableDefinition>\n    {\n\n        internal VariableDefinitionCollection()\n        {\n        }\n\n        internal VariableDefinitionCollection(int capacity)\n            : base(capacity)\n        {\n        }\n\n        protected override void OnAdd(VariableDefinition item, int index)\n        {\n            item.index = index;\n        }\n\n        protected override void OnInsert(VariableDefinition item, int index)\n        {\n            item.index = index;\n\n            for (int i = index; i < size; i++)\n                items[i].index = i + 1;\n        }\n\n        protected override void OnSet(VariableDefinition item, int index)\n        {\n            item.index = index;\n        }\n\n        protected override void OnRemove(VariableDefinition item, int index)\n        {\n            item.index = -1;\n\n            for (int i = index + 1; i < size; i++)\n                items[i].index = i - 1;\n        }\n    }\n\n    class InstructionCollection : Collection<Instruction>\n    {\n\n        internal InstructionCollection()\n        {\n        }\n\n        internal InstructionCollection(int capacity)\n            : base(capacity)\n        {\n        }\n\n        protected override void OnAdd(Instruction item, int index)\n        {\n            if (index == 0)\n                return;\n\n            var previous = items[index - 1];\n            previous.next = item;\n            item.previous = previous;\n        }\n\n        protected override void OnInsert(Instruction item, int index)\n        {\n            if (size == 0)\n                return;\n\n            var current = items[index];\n            if (current == null)\n            {\n                var last = items[index - 1];\n                last.next = item;\n                item.previous = last;\n                return;\n            }\n\n            var previous = current.previous;\n            if (previous != null)\n            {\n                previous.next = item;\n                item.previous = previous;\n            }\n\n            current.previous = item;\n            item.next = current;\n        }\n\n        protected override void OnSet(Instruction item, int index)\n        {\n            var current = items[index];\n\n            item.previous = current.previous;\n            item.next = current.next;\n\n            current.previous = null;\n            current.next = null;\n        }\n\n        protected override void OnRemove(Instruction item, int index)\n        {\n            var previous = item.previous;\n            if (previous != null)\n                previous.next = item.next;\n\n            var next = item.next;\n            if (next != null)\n                next.previous = item.previous;\n\n            item.previous = null;\n            item.next = null;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/OpCode.cs",
    "content": "//\n// OpCode.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic enum FlowControl {\n\t\tBranch,\n\t\tBreak,\n\t\tCall,\n\t\tCond_Branch,\n\t\tMeta,\n\t\tNext,\n\t\tPhi,\n\t\tReturn,\n\t\tThrow,\n\t}\n\n\tpublic enum OpCodeType {\n\t\tAnnotation,\n\t\tMacro,\n\t\tNternal,\n\t\tObjmodel,\n\t\tPrefix,\n\t\tPrimitive,\n\t}\n\n\tpublic enum OperandType {\n\t\tInlineBrTarget,\n\t\tInlineField,\n\t\tInlineI,\n\t\tInlineI8,\n\t\tInlineMethod,\n\t\tInlineNone,\n\t\tInlinePhi,\n\t\tInlineR,\n\t\tInlineSig,\n\t\tInlineString,\n\t\tInlineSwitch,\n\t\tInlineTok,\n\t\tInlineType,\n\t\tInlineVar,\n\t\tInlineArg,\n\t\tShortInlineBrTarget,\n\t\tShortInlineI,\n\t\tShortInlineR,\n\t\tShortInlineVar,\n\t\tShortInlineArg,\n\t}\n\n\tpublic enum StackBehaviour {\n\t\tPop0,\n\t\tPop1,\n\t\tPop1_pop1,\n\t\tPopi,\n\t\tPopi_pop1,\n\t\tPopi_popi,\n\t\tPopi_popi8,\n\t\tPopi_popi_popi,\n\t\tPopi_popr4,\n\t\tPopi_popr8,\n\t\tPopref,\n\t\tPopref_pop1,\n\t\tPopref_popi,\n\t\tPopref_popi_popi,\n\t\tPopref_popi_popi8,\n\t\tPopref_popi_popr4,\n\t\tPopref_popi_popr8,\n\t\tPopref_popi_popref,\n\t\tPopAll,\n\t\tPush0,\n\t\tPush1,\n\t\tPush1_push1,\n\t\tPushi,\n\t\tPushi8,\n\t\tPushr4,\n\t\tPushr8,\n\t\tPushref,\n\t\tVarpop,\n\t\tVarpush,\n\t}\n\n\tpublic struct OpCode {\n\n\t\treadonly byte op1;\n\t\treadonly byte op2;\n\t\treadonly byte code;\n\t\treadonly byte flow_control;\n\t\treadonly byte opcode_type;\n\t\treadonly byte operand_type;\n\t\treadonly byte stack_behavior_pop;\n\t\treadonly byte stack_behavior_push;\n\n\t\tpublic string Name {\n\t\t\tget { return OpCodeNames.names [(int) Code]; }\n\t\t}\n\n\t\tpublic int Size {\n\t\t\tget { return op1 == 0xff ? 1 : 2; }\n\t\t}\n\n\t\tpublic byte Op1 {\n\t\t\tget { return op1; }\n\t\t}\n\n\t\tpublic byte Op2 {\n\t\t\tget { return op2; }\n\t\t}\n\n\t\tpublic short Value {\n\t\t\tget { return op1 == 0xff ? op2 : (short) ((op1 << 8) | op2); }\n\t\t}\n\n\t\tpublic Code Code {\n\t\t\tget { return (Code) code; }\n\t\t}\n\n\t\tpublic FlowControl FlowControl {\n\t\t\tget { return (FlowControl) flow_control; }\n\t\t}\n\n\t\tpublic OpCodeType OpCodeType {\n\t\t\tget { return (OpCodeType) opcode_type; }\n\t\t}\n\n\t\tpublic OperandType OperandType {\n\t\t\tget { return (OperandType) operand_type; }\n\t\t}\n\n\t\tpublic StackBehaviour StackBehaviourPop {\n\t\t\tget { return (StackBehaviour) stack_behavior_pop; }\n\t\t}\n\n\t\tpublic StackBehaviour StackBehaviourPush {\n\t\t\tget { return (StackBehaviour) stack_behavior_push; }\n\t\t}\n\n\t\tinternal OpCode (int x, int y)\n\t\t{\n\t\t\tthis.op1 = (byte) ((x >> 0) & 0xff);\n\t\t\tthis.op2 = (byte) ((x >> 8) & 0xff);\n\t\t\tthis.code = (byte) ((x >> 16) & 0xff);\n\t\t\tthis.flow_control = (byte) ((x >> 24) & 0xff);\n\n\t\t\tthis.opcode_type = (byte) ((y >> 0) & 0xff);\n\t\t\tthis.operand_type = (byte) ((y >> 8) & 0xff);\n\t\t\tthis.stack_behavior_pop = (byte) ((y >> 16) & 0xff);\n\t\t\tthis.stack_behavior_push = (byte) ((y >> 24) & 0xff);\n\n\t\t\tif (op1 == 0xff)\n\t\t\t\tOpCodes.OneByteOpCode [op2] = this;\n\t\t\telse\n\t\t\t\tOpCodes.TwoBytesOpCode [op2] = this;\n\t\t}\n\n\t\tpublic override int GetHashCode ()\n\t\t{\n\t\t\treturn Value;\n\t\t}\n\n\t\tpublic override bool Equals (object obj)\n\t\t{\n\t\t\tif (!(obj is OpCode))\n\t\t\t\treturn false;\n\n\t\t\tvar opcode = (OpCode) obj;\n\t\t\treturn op1 == opcode.op1 && op2 == opcode.op2;\n\t\t}\n\n\t\tpublic bool Equals (OpCode opcode)\n\t\t{\n\t\t\treturn op1 == opcode.op1 && op2 == opcode.op2;\n\t\t}\n\n\t\tpublic static bool operator == (OpCode one, OpCode other)\n\t\t{\n\t\t\treturn one.op1 == other.op1 && one.op2 == other.op2;\n\t\t}\n\n\t\tpublic static bool operator != (OpCode one, OpCode other)\n\t\t{\n\t\t\treturn one.op1 != other.op1 || one.op2 != other.op2;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn Name;\n\t\t}\n\t}\n\n\tstatic class OpCodeNames {\n\n\t\tinternal static readonly string [] names;\n\n\t\tstatic OpCodeNames ()\n\t\t{\n\t\t\tvar table = new byte [] {\n\t\t\t\t3, 110, 111, 112,\n\t\t\t\t5, 98, 114, 101, 97, 107,\n\t\t\t\t7, 108, 100, 97, 114, 103, 46, 48,\n\t\t\t\t7, 108, 100, 97, 114, 103, 46, 49,\n\t\t\t\t7, 108, 100, 97, 114, 103, 46, 50,\n\t\t\t\t7, 108, 100, 97, 114, 103, 46, 51,\n\t\t\t\t7, 108, 100, 108, 111, 99, 46, 48,\n\t\t\t\t7, 108, 100, 108, 111, 99, 46, 49,\n\t\t\t\t7, 108, 100, 108, 111, 99, 46, 50,\n\t\t\t\t7, 108, 100, 108, 111, 99, 46, 51,\n\t\t\t\t7, 115, 116, 108, 111, 99, 46, 48,\n\t\t\t\t7, 115, 116, 108, 111, 99, 46, 49,\n\t\t\t\t7, 115, 116, 108, 111, 99, 46, 50,\n\t\t\t\t7, 115, 116, 108, 111, 99, 46, 51,\n\t\t\t\t7, 108, 100, 97, 114, 103, 46, 115,\n\t\t\t\t8, 108, 100, 97, 114, 103, 97, 46, 115,\n\t\t\t\t7, 115, 116, 97, 114, 103, 46, 115,\n\t\t\t\t7, 108, 100, 108, 111, 99, 46, 115,\n\t\t\t\t8, 108, 100, 108, 111, 99, 97, 46, 115,\n\t\t\t\t7, 115, 116, 108, 111, 99, 46, 115,\n\t\t\t\t6, 108, 100, 110, 117, 108, 108,\n\t\t\t\t9, 108, 100, 99, 46, 105, 52, 46, 109, 49,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 48,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 49,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 50,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 51,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 52,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 53,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 54,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 55,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 56,\n\t\t\t\t8, 108, 100, 99, 46, 105, 52, 46, 115,\n\t\t\t\t6, 108, 100, 99, 46, 105, 52,\n\t\t\t\t6, 108, 100, 99, 46, 105, 56,\n\t\t\t\t6, 108, 100, 99, 46, 114, 52,\n\t\t\t\t6, 108, 100, 99, 46, 114, 56,\n\t\t\t\t3, 100, 117, 112,\n\t\t\t\t3, 112, 111, 112,\n\t\t\t\t3, 106, 109, 112,\n\t\t\t\t4, 99, 97, 108, 108,\n\t\t\t\t5, 99, 97, 108, 108, 105,\n\t\t\t\t3, 114, 101, 116,\n\t\t\t\t4, 98, 114, 46, 115,\n\t\t\t\t9, 98, 114, 102, 97, 108, 115, 101, 46, 115,\n\t\t\t\t8, 98, 114, 116, 114, 117, 101, 46, 115,\n\t\t\t\t5, 98, 101, 113, 46, 115,\n\t\t\t\t5, 98, 103, 101, 46, 115,\n\t\t\t\t5, 98, 103, 116, 46, 115,\n\t\t\t\t5, 98, 108, 101, 46, 115,\n\t\t\t\t5, 98, 108, 116, 46, 115,\n\t\t\t\t8, 98, 110, 101, 46, 117, 110, 46, 115,\n\t\t\t\t8, 98, 103, 101, 46, 117, 110, 46, 115,\n\t\t\t\t8, 98, 103, 116, 46, 117, 110, 46, 115,\n\t\t\t\t8, 98, 108, 101, 46, 117, 110, 46, 115,\n\t\t\t\t8, 98, 108, 116, 46, 117, 110, 46, 115,\n\t\t\t\t2, 98, 114,\n\t\t\t\t7, 98, 114, 102, 97, 108, 115, 101,\n\t\t\t\t6, 98, 114, 116, 114, 117, 101,\n\t\t\t\t3, 98, 101, 113,\n\t\t\t\t3, 98, 103, 101,\n\t\t\t\t3, 98, 103, 116,\n\t\t\t\t3, 98, 108, 101,\n\t\t\t\t3, 98, 108, 116,\n\t\t\t\t6, 98, 110, 101, 46, 117, 110,\n\t\t\t\t6, 98, 103, 101, 46, 117, 110,\n\t\t\t\t6, 98, 103, 116, 46, 117, 110,\n\t\t\t\t6, 98, 108, 101, 46, 117, 110,\n\t\t\t\t6, 98, 108, 116, 46, 117, 110,\n\t\t\t\t6, 115, 119, 105, 116, 99, 104,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 105, 49,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 117, 49,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 105, 50,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 117, 50,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 105, 52,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 117, 52,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 105, 56,\n\t\t\t\t7, 108, 100, 105, 110, 100, 46, 105,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 114, 52,\n\t\t\t\t8, 108, 100, 105, 110, 100, 46, 114, 56,\n\t\t\t\t9, 108, 100, 105, 110, 100, 46, 114, 101, 102,\n\t\t\t\t9, 115, 116, 105, 110, 100, 46, 114, 101, 102,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 105, 49,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 105, 50,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 105, 52,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 105, 56,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 114, 52,\n\t\t\t\t8, 115, 116, 105, 110, 100, 46, 114, 56,\n\t\t\t\t3, 97, 100, 100,\n\t\t\t\t3, 115, 117, 98,\n\t\t\t\t3, 109, 117, 108,\n\t\t\t\t3, 100, 105, 118,\n\t\t\t\t6, 100, 105, 118, 46, 117, 110,\n\t\t\t\t3, 114, 101, 109,\n\t\t\t\t6, 114, 101, 109, 46, 117, 110,\n\t\t\t\t3, 97, 110, 100,\n\t\t\t\t2, 111, 114,\n\t\t\t\t3, 120, 111, 114,\n\t\t\t\t3, 115, 104, 108,\n\t\t\t\t3, 115, 104, 114,\n\t\t\t\t6, 115, 104, 114, 46, 117, 110,\n\t\t\t\t3, 110, 101, 103,\n\t\t\t\t3, 110, 111, 116,\n\t\t\t\t7, 99, 111, 110, 118, 46, 105, 49,\n\t\t\t\t7, 99, 111, 110, 118, 46, 105, 50,\n\t\t\t\t7, 99, 111, 110, 118, 46, 105, 52,\n\t\t\t\t7, 99, 111, 110, 118, 46, 105, 56,\n\t\t\t\t7, 99, 111, 110, 118, 46, 114, 52,\n\t\t\t\t7, 99, 111, 110, 118, 46, 114, 56,\n\t\t\t\t7, 99, 111, 110, 118, 46, 117, 52,\n\t\t\t\t7, 99, 111, 110, 118, 46, 117, 56,\n\t\t\t\t8, 99, 97, 108, 108, 118, 105, 114, 116,\n\t\t\t\t5, 99, 112, 111, 98, 106,\n\t\t\t\t5, 108, 100, 111, 98, 106,\n\t\t\t\t5, 108, 100, 115, 116, 114,\n\t\t\t\t6, 110, 101, 119, 111, 98, 106,\n\t\t\t\t9, 99, 97, 115, 116, 99, 108, 97, 115, 115,\n\t\t\t\t6, 105, 115, 105, 110, 115, 116,\n\t\t\t\t9, 99, 111, 110, 118, 46, 114, 46, 117, 110,\n\t\t\t\t5, 117, 110, 98, 111, 120,\n\t\t\t\t5, 116, 104, 114, 111, 119,\n\t\t\t\t5, 108, 100, 102, 108, 100,\n\t\t\t\t6, 108, 100, 102, 108, 100, 97,\n\t\t\t\t5, 115, 116, 102, 108, 100,\n\t\t\t\t6, 108, 100, 115, 102, 108, 100,\n\t\t\t\t7, 108, 100, 115, 102, 108, 100, 97,\n\t\t\t\t6, 115, 116, 115, 102, 108, 100,\n\t\t\t\t5, 115, 116, 111, 98, 106,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 49, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 50, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 52, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 56, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 49, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 50, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 52, 46, 117, 110,\n\t\t\t\t14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 56, 46, 117, 110,\n\t\t\t\t13, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 46, 117, 110,\n\t\t\t\t13, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 46, 117, 110,\n\t\t\t\t3, 98, 111, 120,\n\t\t\t\t6, 110, 101, 119, 97, 114, 114,\n\t\t\t\t5, 108, 100, 108, 101, 110,\n\t\t\t\t7, 108, 100, 101, 108, 101, 109, 97,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 105, 49,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 117, 49,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 105, 50,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 117, 50,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 105, 52,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 117, 52,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 105, 56,\n\t\t\t\t8, 108, 100, 101, 108, 101, 109, 46, 105,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 114, 52,\n\t\t\t\t9, 108, 100, 101, 108, 101, 109, 46, 114, 56,\n\t\t\t\t10, 108, 100, 101, 108, 101, 109, 46, 114, 101, 102,\n\t\t\t\t8, 115, 116, 101, 108, 101, 109, 46, 105,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 105, 49,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 105, 50,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 105, 52,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 105, 56,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 114, 52,\n\t\t\t\t9, 115, 116, 101, 108, 101, 109, 46, 114, 56,\n\t\t\t\t10, 115, 116, 101, 108, 101, 109, 46, 114, 101, 102,\n\t\t\t\t10, 108, 100, 101, 108, 101, 109, 46, 97, 110, 121,\n\t\t\t\t10, 115, 116, 101, 108, 101, 109, 46, 97, 110, 121,\n\t\t\t\t9, 117, 110, 98, 111, 120, 46, 97, 110, 121,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 49,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 49,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 50,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 50,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 52,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 52,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 56,\n\t\t\t\t11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 56,\n\t\t\t\t9, 114, 101, 102, 97, 110, 121, 118, 97, 108,\n\t\t\t\t8, 99, 107, 102, 105, 110, 105, 116, 101,\n\t\t\t\t8, 109, 107, 114, 101, 102, 97, 110, 121,\n\t\t\t\t7, 108, 100, 116, 111, 107, 101, 110,\n\t\t\t\t7, 99, 111, 110, 118, 46, 117, 50,\n\t\t\t\t7, 99, 111, 110, 118, 46, 117, 49,\n\t\t\t\t6, 99, 111, 110, 118, 46, 105,\n\t\t\t\t10, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105,\n\t\t\t\t10, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117,\n\t\t\t\t7, 97, 100, 100, 46, 111, 118, 102,\n\t\t\t\t10, 97, 100, 100, 46, 111, 118, 102, 46, 117, 110,\n\t\t\t\t7, 109, 117, 108, 46, 111, 118, 102,\n\t\t\t\t10, 109, 117, 108, 46, 111, 118, 102, 46, 117, 110,\n\t\t\t\t7, 115, 117, 98, 46, 111, 118, 102,\n\t\t\t\t10, 115, 117, 98, 46, 111, 118, 102, 46, 117, 110,\n\t\t\t\t10, 101, 110, 100, 102, 105, 110, 97, 108, 108, 121,\n\t\t\t\t5, 108, 101, 97, 118, 101,\n\t\t\t\t7, 108, 101, 97, 118, 101, 46, 115,\n\t\t\t\t7, 115, 116, 105, 110, 100, 46, 105,\n\t\t\t\t6, 99, 111, 110, 118, 46, 117,\n\t\t\t\t7, 97, 114, 103, 108, 105, 115, 116,\n\t\t\t\t3, 99, 101, 113,\n\t\t\t\t3, 99, 103, 116,\n\t\t\t\t6, 99, 103, 116, 46, 117, 110,\n\t\t\t\t3, 99, 108, 116,\n\t\t\t\t6, 99, 108, 116, 46, 117, 110,\n\t\t\t\t5, 108, 100, 102, 116, 110,\n\t\t\t\t9, 108, 100, 118, 105, 114, 116, 102, 116, 110,\n\t\t\t\t5, 108, 100, 97, 114, 103,\n\t\t\t\t6, 108, 100, 97, 114, 103, 97,\n\t\t\t\t5, 115, 116, 97, 114, 103,\n\t\t\t\t5, 108, 100, 108, 111, 99,\n\t\t\t\t6, 108, 100, 108, 111, 99, 97,\n\t\t\t\t5, 115, 116, 108, 111, 99,\n\t\t\t\t8, 108, 111, 99, 97, 108, 108, 111, 99,\n\t\t\t\t9, 101, 110, 100, 102, 105, 108, 116, 101, 114,\n\t\t\t\t10, 117, 110, 97, 108, 105, 103, 110, 101, 100, 46,\n\t\t\t\t9, 118, 111, 108, 97, 116, 105, 108, 101, 46,\n\t\t\t\t5, 116, 97, 105, 108, 46,\n\t\t\t\t7, 105, 110, 105, 116, 111, 98, 106,\n\t\t\t\t12, 99, 111, 110, 115, 116, 114, 97, 105, 110, 101, 100, 46,\n\t\t\t\t5, 99, 112, 98, 108, 107,\n\t\t\t\t7, 105, 110, 105, 116, 98, 108, 107,\n\t\t\t\t3, 110, 111, 46,\n\t\t\t\t7, 114, 101, 116, 104, 114, 111, 119,\n\t\t\t\t6, 115, 105, 122, 101, 111, 102,\n\t\t\t\t10, 114, 101, 102, 97, 110, 121, 116, 121, 112, 101,\n\t\t\t\t9, 114, 101, 97, 100, 111, 110, 108, 121, 46,\n\t\t\t};\n\n\t\t\tnames = new string [219];\n\n\t\t\tfor (int i = 0, p = 0; i < names.Length; i++) {\n\t\t\t\tvar buffer = new char [table [p++]];\n\n\t\t\t\tfor (int j = 0; j < buffer.Length; j++)\n\t\t\t\t\tbuffer [j] = (char) table [p++];\n\n\t\t\t\tnames [i] = new string (buffer);\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/OpCodes.cs",
    "content": "//\n// OpCodes.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic static class OpCodes {\n\n\t\tinternal static readonly OpCode [] OneByteOpCode = new OpCode [0xe0 + 1];\n\t\tinternal static readonly OpCode [] TwoBytesOpCode = new OpCode [0x1e + 1];\n\n\t\tpublic static readonly OpCode Nop = new OpCode (\n\t\t\t0xff << 0 | 0x00 << 8 | (byte) Code.Nop << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Break = new OpCode (\n\t\t\t0xff << 0 | 0x01 << 8 | (byte) Code.Break << 16 | (byte) FlowControl.Break << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldarg_0 = new OpCode (\n\t\t\t0xff << 0 | 0x02 << 8 | (byte) Code.Ldarg_0 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldarg_1 = new OpCode (\n\t\t\t0xff << 0 | 0x03 << 8 | (byte) Code.Ldarg_1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldarg_2 = new OpCode (\n\t\t\t0xff << 0 | 0x04 << 8 | (byte) Code.Ldarg_2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldarg_3 = new OpCode (\n\t\t\t0xff << 0 | 0x05 << 8 | (byte) Code.Ldarg_3 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloc_0 = new OpCode (\n\t\t\t0xff << 0 | 0x06 << 8 | (byte) Code.Ldloc_0 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloc_1 = new OpCode (\n\t\t\t0xff << 0 | 0x07 << 8 | (byte) Code.Ldloc_1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloc_2 = new OpCode (\n\t\t\t0xff << 0 | 0x08 << 8 | (byte) Code.Ldloc_2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloc_3 = new OpCode (\n\t\t\t0xff << 0 | 0x09 << 8 | (byte) Code.Ldloc_3 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Stloc_0 = new OpCode (\n\t\t\t0xff << 0 | 0x0a << 8 | (byte) Code.Stloc_0 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stloc_1 = new OpCode (\n\t\t\t0xff << 0 | 0x0b << 8 | (byte) Code.Stloc_1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stloc_2 = new OpCode (\n\t\t\t0xff << 0 | 0x0c << 8 | (byte) Code.Stloc_2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stloc_3 = new OpCode (\n\t\t\t0xff << 0 | 0x0d << 8 | (byte) Code.Stloc_3 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldarg_S = new OpCode (\n\t\t\t0xff << 0 | 0x0e << 8 | (byte) Code.Ldarg_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldarga_S = new OpCode (\n\t\t\t0xff << 0 | 0x0f << 8 | (byte) Code.Ldarga_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Starg_S = new OpCode (\n\t\t\t0xff << 0 | 0x10 << 8 | (byte) Code.Starg_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineArg << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldloc_S = new OpCode (\n\t\t\t0xff << 0 | 0x11 << 8 | (byte) Code.Ldloc_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloca_S = new OpCode (\n\t\t\t0xff << 0 | 0x12 << 8 | (byte) Code.Ldloca_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Stloc_S = new OpCode (\n\t\t\t0xff << 0 | 0x13 << 8 | (byte) Code.Stloc_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineVar << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldnull = new OpCode (\n\t\t\t0xff << 0 | 0x14 << 8 | (byte) Code.Ldnull << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_M1 = new OpCode (\n\t\t\t0xff << 0 | 0x15 << 8 | (byte) Code.Ldc_I4_M1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_0 = new OpCode (\n\t\t\t0xff << 0 | 0x16 << 8 | (byte) Code.Ldc_I4_0 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_1 = new OpCode (\n\t\t\t0xff << 0 | 0x17 << 8 | (byte) Code.Ldc_I4_1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_2 = new OpCode (\n\t\t\t0xff << 0 | 0x18 << 8 | (byte) Code.Ldc_I4_2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_3 = new OpCode (\n\t\t\t0xff << 0 | 0x19 << 8 | (byte) Code.Ldc_I4_3 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_4 = new OpCode (\n\t\t\t0xff << 0 | 0x1a << 8 | (byte) Code.Ldc_I4_4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_5 = new OpCode (\n\t\t\t0xff << 0 | 0x1b << 8 | (byte) Code.Ldc_I4_5 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_6 = new OpCode (\n\t\t\t0xff << 0 | 0x1c << 8 | (byte) Code.Ldc_I4_6 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_7 = new OpCode (\n\t\t\t0xff << 0 | 0x1d << 8 | (byte) Code.Ldc_I4_7 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_8 = new OpCode (\n\t\t\t0xff << 0 | 0x1e << 8 | (byte) Code.Ldc_I4_8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4_S = new OpCode (\n\t\t\t0xff << 0 | 0x1f << 8 | (byte) Code.Ldc_I4_S << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x20 << 8 | (byte) Code.Ldc_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldc_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x21 << 8 | (byte) Code.Ldc_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineI8 << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Ldc_R4 = new OpCode (\n\t\t\t0xff << 0 | 0x22 << 8 | (byte) Code.Ldc_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.ShortInlineR << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushr4 << 24);\n\n\t\tpublic static readonly OpCode Ldc_R8 = new OpCode (\n\t\t\t0xff << 0 | 0x23 << 8 | (byte) Code.Ldc_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineR << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Dup = new OpCode (\n\t\t\t0xff << 0 | 0x25 << 8 | (byte) Code.Dup << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push1_push1 << 24);\n\n\t\tpublic static readonly OpCode Pop = new OpCode (\n\t\t\t0xff << 0 | 0x26 << 8 | (byte) Code.Pop << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Jmp = new OpCode (\n\t\t\t0xff << 0 | 0x27 << 8 | (byte) Code.Jmp << 16 | (byte) FlowControl.Call << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Call = new OpCode (\n\t\t\t0xff << 0 | 0x28 << 8 | (byte) Code.Call << 16 | (byte) FlowControl.Call << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Varpush << 24);\n\n\t\tpublic static readonly OpCode Calli = new OpCode (\n\t\t\t0xff << 0 | 0x29 << 8 | (byte) Code.Calli << 16 | (byte) FlowControl.Call << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineSig << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Varpush << 24);\n\n\t\tpublic static readonly OpCode Ret = new OpCode (\n\t\t\t0xff << 0 | 0x2a << 8 | (byte) Code.Ret << 16 | (byte) FlowControl.Return << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Br_S = new OpCode (\n\t\t\t0xff << 0 | 0x2b << 8 | (byte) Code.Br_S << 16 | (byte) FlowControl.Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Brfalse_S = new OpCode (\n\t\t\t0xff << 0 | 0x2c << 8 | (byte) Code.Brfalse_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Brtrue_S = new OpCode (\n\t\t\t0xff << 0 | 0x2d << 8 | (byte) Code.Brtrue_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Beq_S = new OpCode (\n\t\t\t0xff << 0 | 0x2e << 8 | (byte) Code.Beq_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bge_S = new OpCode (\n\t\t\t0xff << 0 | 0x2f << 8 | (byte) Code.Bge_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bgt_S = new OpCode (\n\t\t\t0xff << 0 | 0x30 << 8 | (byte) Code.Bgt_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ble_S = new OpCode (\n\t\t\t0xff << 0 | 0x31 << 8 | (byte) Code.Ble_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Blt_S = new OpCode (\n\t\t\t0xff << 0 | 0x32 << 8 | (byte) Code.Blt_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bne_Un_S = new OpCode (\n\t\t\t0xff << 0 | 0x33 << 8 | (byte) Code.Bne_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bge_Un_S = new OpCode (\n\t\t\t0xff << 0 | 0x34 << 8 | (byte) Code.Bge_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bgt_Un_S = new OpCode (\n\t\t\t0xff << 0 | 0x35 << 8 | (byte) Code.Bgt_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ble_Un_S = new OpCode (\n\t\t\t0xff << 0 | 0x36 << 8 | (byte) Code.Ble_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Blt_Un_S = new OpCode (\n\t\t\t0xff << 0 | 0x37 << 8 | (byte) Code.Blt_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Br = new OpCode (\n\t\t\t0xff << 0 | 0x38 << 8 | (byte) Code.Br << 16 | (byte) FlowControl.Branch << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Brfalse = new OpCode (\n\t\t\t0xff << 0 | 0x39 << 8 | (byte) Code.Brfalse << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Brtrue = new OpCode (\n\t\t\t0xff << 0 | 0x3a << 8 | (byte) Code.Brtrue << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Beq = new OpCode (\n\t\t\t0xff << 0 | 0x3b << 8 | (byte) Code.Beq << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bge = new OpCode (\n\t\t\t0xff << 0 | 0x3c << 8 | (byte) Code.Bge << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bgt = new OpCode (\n\t\t\t0xff << 0 | 0x3d << 8 | (byte) Code.Bgt << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ble = new OpCode (\n\t\t\t0xff << 0 | 0x3e << 8 | (byte) Code.Ble << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Blt = new OpCode (\n\t\t\t0xff << 0 | 0x3f << 8 | (byte) Code.Blt << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bne_Un = new OpCode (\n\t\t\t0xff << 0 | 0x40 << 8 | (byte) Code.Bne_Un << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bge_Un = new OpCode (\n\t\t\t0xff << 0 | 0x41 << 8 | (byte) Code.Bge_Un << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Bgt_Un = new OpCode (\n\t\t\t0xff << 0 | 0x42 << 8 | (byte) Code.Bgt_Un << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ble_Un = new OpCode (\n\t\t\t0xff << 0 | 0x43 << 8 | (byte) Code.Ble_Un << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Blt_Un = new OpCode (\n\t\t\t0xff << 0 | 0x44 << 8 | (byte) Code.Blt_Un << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Switch = new OpCode (\n\t\t\t0xff << 0 | 0x45 << 8 | (byte) Code.Switch << 16 | (byte) FlowControl.Cond_Branch << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineSwitch << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldind_I1 = new OpCode (\n\t\t\t0xff << 0 | 0x46 << 8 | (byte) Code.Ldind_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_U1 = new OpCode (\n\t\t\t0xff << 0 | 0x47 << 8 | (byte) Code.Ldind_U1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_I2 = new OpCode (\n\t\t\t0xff << 0 | 0x48 << 8 | (byte) Code.Ldind_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_U2 = new OpCode (\n\t\t\t0xff << 0 | 0x49 << 8 | (byte) Code.Ldind_U2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x4a << 8 | (byte) Code.Ldind_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_U4 = new OpCode (\n\t\t\t0xff << 0 | 0x4b << 8 | (byte) Code.Ldind_U4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x4c << 8 | (byte) Code.Ldind_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Ldind_I = new OpCode (\n\t\t\t0xff << 0 | 0x4d << 8 | (byte) Code.Ldind_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldind_R4 = new OpCode (\n\t\t\t0xff << 0 | 0x4e << 8 | (byte) Code.Ldind_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushr4 << 24);\n\n\t\tpublic static readonly OpCode Ldind_R8 = new OpCode (\n\t\t\t0xff << 0 | 0x4f << 8 | (byte) Code.Ldind_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Ldind_Ref = new OpCode (\n\t\t\t0xff << 0 | 0x50 << 8 | (byte) Code.Ldind_Ref << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Stind_Ref = new OpCode (\n\t\t\t0xff << 0 | 0x51 << 8 | (byte) Code.Stind_Ref << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_I1 = new OpCode (\n\t\t\t0xff << 0 | 0x52 << 8 | (byte) Code.Stind_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_I2 = new OpCode (\n\t\t\t0xff << 0 | 0x53 << 8 | (byte) Code.Stind_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x54 << 8 | (byte) Code.Stind_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x55 << 8 | (byte) Code.Stind_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi8 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_R4 = new OpCode (\n\t\t\t0xff << 0 | 0x56 << 8 | (byte) Code.Stind_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popr4 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_R8 = new OpCode (\n\t\t\t0xff << 0 | 0x57 << 8 | (byte) Code.Stind_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popr8 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Add = new OpCode (\n\t\t\t0xff << 0 | 0x58 << 8 | (byte) Code.Add << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Sub = new OpCode (\n\t\t\t0xff << 0 | 0x59 << 8 | (byte) Code.Sub << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Mul = new OpCode (\n\t\t\t0xff << 0 | 0x5a << 8 | (byte) Code.Mul << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Div = new OpCode (\n\t\t\t0xff << 0 | 0x5b << 8 | (byte) Code.Div << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Div_Un = new OpCode (\n\t\t\t0xff << 0 | 0x5c << 8 | (byte) Code.Div_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Rem = new OpCode (\n\t\t\t0xff << 0 | 0x5d << 8 | (byte) Code.Rem << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Rem_Un = new OpCode (\n\t\t\t0xff << 0 | 0x5e << 8 | (byte) Code.Rem_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode And = new OpCode (\n\t\t\t0xff << 0 | 0x5f << 8 | (byte) Code.And << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Or = new OpCode (\n\t\t\t0xff << 0 | 0x60 << 8 | (byte) Code.Or << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Xor = new OpCode (\n\t\t\t0xff << 0 | 0x61 << 8 | (byte) Code.Xor << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Shl = new OpCode (\n\t\t\t0xff << 0 | 0x62 << 8 | (byte) Code.Shl << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Shr = new OpCode (\n\t\t\t0xff << 0 | 0x63 << 8 | (byte) Code.Shr << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Shr_Un = new OpCode (\n\t\t\t0xff << 0 | 0x64 << 8 | (byte) Code.Shr_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Neg = new OpCode (\n\t\t\t0xff << 0 | 0x65 << 8 | (byte) Code.Neg << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Not = new OpCode (\n\t\t\t0xff << 0 | 0x66 << 8 | (byte) Code.Not << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Conv_I1 = new OpCode (\n\t\t\t0xff << 0 | 0x67 << 8 | (byte) Code.Conv_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_I2 = new OpCode (\n\t\t\t0xff << 0 | 0x68 << 8 | (byte) Code.Conv_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x69 << 8 | (byte) Code.Conv_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x6a << 8 | (byte) Code.Conv_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Conv_R4 = new OpCode (\n\t\t\t0xff << 0 | 0x6b << 8 | (byte) Code.Conv_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr4 << 24);\n\n\t\tpublic static readonly OpCode Conv_R8 = new OpCode (\n\t\t\t0xff << 0 | 0x6c << 8 | (byte) Code.Conv_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Conv_U4 = new OpCode (\n\t\t\t0xff << 0 | 0x6d << 8 | (byte) Code.Conv_U4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_U8 = new OpCode (\n\t\t\t0xff << 0 | 0x6e << 8 | (byte) Code.Conv_U8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Callvirt = new OpCode (\n\t\t\t0xff << 0 | 0x6f << 8 | (byte) Code.Callvirt << 16 | (byte) FlowControl.Call << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Varpush << 24);\n\n\t\tpublic static readonly OpCode Cpobj = new OpCode (\n\t\t\t0xff << 0 | 0x70 << 8 | (byte) Code.Cpobj << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldobj = new OpCode (\n\t\t\t0xff << 0 | 0x71 << 8 | (byte) Code.Ldobj << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldstr = new OpCode (\n\t\t\t0xff << 0 | 0x72 << 8 | (byte) Code.Ldstr << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineString << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Newobj = new OpCode (\n\t\t\t0xff << 0 | 0x73 << 8 | (byte) Code.Newobj << 16 | (byte) FlowControl.Call << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Castclass = new OpCode (\n\t\t\t0xff << 0 | 0x74 << 8 | (byte) Code.Castclass << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Isinst = new OpCode (\n\t\t\t0xff << 0 | 0x75 << 8 | (byte) Code.Isinst << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_R_Un = new OpCode (\n\t\t\t0xff << 0 | 0x76 << 8 | (byte) Code.Conv_R_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Unbox = new OpCode (\n\t\t\t0xff << 0 | 0x79 << 8 | (byte) Code.Unbox << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Throw = new OpCode (\n\t\t\t0xff << 0 | 0x7a << 8 | (byte) Code.Throw << 16 | (byte) FlowControl.Throw << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldfld = new OpCode (\n\t\t\t0xff << 0 | 0x7b << 8 | (byte) Code.Ldfld << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldflda = new OpCode (\n\t\t\t0xff << 0 | 0x7c << 8 | (byte) Code.Ldflda << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Stfld = new OpCode (\n\t\t\t0xff << 0 | 0x7d << 8 | (byte) Code.Stfld << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Popref_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldsfld = new OpCode (\n\t\t\t0xff << 0 | 0x7e << 8 | (byte) Code.Ldsfld << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldsflda = new OpCode (\n\t\t\t0xff << 0 | 0x7f << 8 | (byte) Code.Ldsflda << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Stsfld = new OpCode (\n\t\t\t0xff << 0 | 0x80 << 8 | (byte) Code.Stsfld << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stobj = new OpCode (\n\t\t\t0xff << 0 | 0x81 << 8 | (byte) Code.Stobj << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I1_Un = new OpCode (\n\t\t\t0xff << 0 | 0x82 << 8 | (byte) Code.Conv_Ovf_I1_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I2_Un = new OpCode (\n\t\t\t0xff << 0 | 0x83 << 8 | (byte) Code.Conv_Ovf_I2_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I4_Un = new OpCode (\n\t\t\t0xff << 0 | 0x84 << 8 | (byte) Code.Conv_Ovf_I4_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I8_Un = new OpCode (\n\t\t\t0xff << 0 | 0x85 << 8 | (byte) Code.Conv_Ovf_I8_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U1_Un = new OpCode (\n\t\t\t0xff << 0 | 0x86 << 8 | (byte) Code.Conv_Ovf_U1_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U2_Un = new OpCode (\n\t\t\t0xff << 0 | 0x87 << 8 | (byte) Code.Conv_Ovf_U2_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U4_Un = new OpCode (\n\t\t\t0xff << 0 | 0x88 << 8 | (byte) Code.Conv_Ovf_U4_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U8_Un = new OpCode (\n\t\t\t0xff << 0 | 0x89 << 8 | (byte) Code.Conv_Ovf_U8_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I_Un = new OpCode (\n\t\t\t0xff << 0 | 0x8a << 8 | (byte) Code.Conv_Ovf_I_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U_Un = new OpCode (\n\t\t\t0xff << 0 | 0x8b << 8 | (byte) Code.Conv_Ovf_U_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Box = new OpCode (\n\t\t\t0xff << 0 | 0x8c << 8 | (byte) Code.Box << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Newarr = new OpCode (\n\t\t\t0xff << 0 | 0x8d << 8 | (byte) Code.Newarr << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Ldlen = new OpCode (\n\t\t\t0xff << 0 | 0x8e << 8 | (byte) Code.Ldlen << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelema = new OpCode (\n\t\t\t0xff << 0 | 0x8f << 8 | (byte) Code.Ldelema << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_I1 = new OpCode (\n\t\t\t0xff << 0 | 0x90 << 8 | (byte) Code.Ldelem_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_U1 = new OpCode (\n\t\t\t0xff << 0 | 0x91 << 8 | (byte) Code.Ldelem_U1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_I2 = new OpCode (\n\t\t\t0xff << 0 | 0x92 << 8 | (byte) Code.Ldelem_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_U2 = new OpCode (\n\t\t\t0xff << 0 | 0x93 << 8 | (byte) Code.Ldelem_U2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x94 << 8 | (byte) Code.Ldelem_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_U4 = new OpCode (\n\t\t\t0xff << 0 | 0x95 << 8 | (byte) Code.Ldelem_U4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x96 << 8 | (byte) Code.Ldelem_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Ldelem_I = new OpCode (\n\t\t\t0xff << 0 | 0x97 << 8 | (byte) Code.Ldelem_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldelem_R4 = new OpCode (\n\t\t\t0xff << 0 | 0x98 << 8 | (byte) Code.Ldelem_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushr4 << 24);\n\n\t\tpublic static readonly OpCode Ldelem_R8 = new OpCode (\n\t\t\t0xff << 0 | 0x99 << 8 | (byte) Code.Ldelem_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Ldelem_Ref = new OpCode (\n\t\t\t0xff << 0 | 0x9a << 8 | (byte) Code.Ldelem_Ref << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushref << 24);\n\n\t\tpublic static readonly OpCode Stelem_I = new OpCode (\n\t\t\t0xff << 0 | 0x9b << 8 | (byte) Code.Stelem_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_I1 = new OpCode (\n\t\t\t0xff << 0 | 0x9c << 8 | (byte) Code.Stelem_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_I2 = new OpCode (\n\t\t\t0xff << 0 | 0x9d << 8 | (byte) Code.Stelem_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_I4 = new OpCode (\n\t\t\t0xff << 0 | 0x9e << 8 | (byte) Code.Stelem_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_I8 = new OpCode (\n\t\t\t0xff << 0 | 0x9f << 8 | (byte) Code.Stelem_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi8 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_R4 = new OpCode (\n\t\t\t0xff << 0 | 0xa0 << 8 | (byte) Code.Stelem_R4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popr4 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_R8 = new OpCode (\n\t\t\t0xff << 0 | 0xa1 << 8 | (byte) Code.Stelem_R8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popr8 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stelem_Ref = new OpCode (\n\t\t\t0xff << 0 | 0xa2 << 8 | (byte) Code.Stelem_Ref << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popref << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldelem_Any = new OpCode (\n\t\t\t0xff << 0 | 0xa3 << 8 | (byte) Code.Ldelem_Any << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Stelem_Any = new OpCode (\n\t\t\t0xff << 0 | 0xa4 << 8 | (byte) Code.Stelem_Any << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref_popi_popref << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Unbox_Any = new OpCode (\n\t\t\t0xff << 0 | 0xa5 << 8 | (byte) Code.Unbox_Any << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I1 = new OpCode (\n\t\t\t0xff << 0 | 0xb3 << 8 | (byte) Code.Conv_Ovf_I1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U1 = new OpCode (\n\t\t\t0xff << 0 | 0xb4 << 8 | (byte) Code.Conv_Ovf_U1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I2 = new OpCode (\n\t\t\t0xff << 0 | 0xb5 << 8 | (byte) Code.Conv_Ovf_I2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U2 = new OpCode (\n\t\t\t0xff << 0 | 0xb6 << 8 | (byte) Code.Conv_Ovf_U2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I4 = new OpCode (\n\t\t\t0xff << 0 | 0xb7 << 8 | (byte) Code.Conv_Ovf_I4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U4 = new OpCode (\n\t\t\t0xff << 0 | 0xb8 << 8 | (byte) Code.Conv_Ovf_U4 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I8 = new OpCode (\n\t\t\t0xff << 0 | 0xb9 << 8 | (byte) Code.Conv_Ovf_I8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U8 = new OpCode (\n\t\t\t0xff << 0 | 0xba << 8 | (byte) Code.Conv_Ovf_U8 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);\n\n\t\tpublic static readonly OpCode Refanyval = new OpCode (\n\t\t\t0xff << 0 | 0xc2 << 8 | (byte) Code.Refanyval << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ckfinite = new OpCode (\n\t\t\t0xff << 0 | 0xc3 << 8 | (byte) Code.Ckfinite << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr8 << 24);\n\n\t\tpublic static readonly OpCode Mkrefany = new OpCode (\n\t\t\t0xff << 0 | 0xc6 << 8 | (byte) Code.Mkrefany << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldtoken = new OpCode (\n\t\t\t0xff << 0 | 0xd0 << 8 | (byte) Code.Ldtoken << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineTok << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_U2 = new OpCode (\n\t\t\t0xff << 0 | 0xd1 << 8 | (byte) Code.Conv_U2 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_U1 = new OpCode (\n\t\t\t0xff << 0 | 0xd2 << 8 | (byte) Code.Conv_U1 << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_I = new OpCode (\n\t\t\t0xff << 0 | 0xd3 << 8 | (byte) Code.Conv_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_I = new OpCode (\n\t\t\t0xff << 0 | 0xd4 << 8 | (byte) Code.Conv_Ovf_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Conv_Ovf_U = new OpCode (\n\t\t\t0xff << 0 | 0xd5 << 8 | (byte) Code.Conv_Ovf_U << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Add_Ovf = new OpCode (\n\t\t\t0xff << 0 | 0xd6 << 8 | (byte) Code.Add_Ovf << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Add_Ovf_Un = new OpCode (\n\t\t\t0xff << 0 | 0xd7 << 8 | (byte) Code.Add_Ovf_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Mul_Ovf = new OpCode (\n\t\t\t0xff << 0 | 0xd8 << 8 | (byte) Code.Mul_Ovf << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Mul_Ovf_Un = new OpCode (\n\t\t\t0xff << 0 | 0xd9 << 8 | (byte) Code.Mul_Ovf_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Sub_Ovf = new OpCode (\n\t\t\t0xff << 0 | 0xda << 8 | (byte) Code.Sub_Ovf << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Sub_Ovf_Un = new OpCode (\n\t\t\t0xff << 0 | 0xdb << 8 | (byte) Code.Sub_Ovf_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Endfinally = new OpCode (\n\t\t\t0xff << 0 | 0xdc << 8 | (byte) Code.Endfinally << 16 | (byte) FlowControl.Return << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Leave = new OpCode (\n\t\t\t0xff << 0 | 0xdd << 8 | (byte) Code.Leave << 16 | (byte) FlowControl.Branch << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.PopAll << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Leave_S = new OpCode (\n\t\t\t0xff << 0 | 0xde << 8 | (byte) Code.Leave_S << 16 | (byte) FlowControl.Branch << 24,\n\t\t\t(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.PopAll << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Stind_I = new OpCode (\n\t\t\t0xff << 0 | 0xdf << 8 | (byte) Code.Stind_I << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Conv_U = new OpCode (\n\t\t\t0xff << 0 | 0xe0 << 8 | (byte) Code.Conv_U << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Arglist = new OpCode (\n\t\t\t0xfe << 0 | 0x00 << 8 | (byte) Code.Arglist << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ceq = new OpCode (\n\t\t\t0xfe << 0 | 0x01 << 8 | (byte) Code.Ceq << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Cgt = new OpCode (\n\t\t\t0xfe << 0 | 0x02 << 8 | (byte) Code.Cgt << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Cgt_Un = new OpCode (\n\t\t\t0xfe << 0 | 0x03 << 8 | (byte) Code.Cgt_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Clt = new OpCode (\n\t\t\t0xfe << 0 | 0x04 << 8 | (byte) Code.Clt << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Clt_Un = new OpCode (\n\t\t\t0xfe << 0 | 0x05 << 8 | (byte) Code.Clt_Un << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldftn = new OpCode (\n\t\t\t0xfe << 0 | 0x06 << 8 | (byte) Code.Ldftn << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldvirtftn = new OpCode (\n\t\t\t0xfe << 0 | 0x07 << 8 | (byte) Code.Ldvirtftn << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Ldarg = new OpCode (\n\t\t\t0xfe << 0 | 0x09 << 8 | (byte) Code.Ldarg << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldarga = new OpCode (\n\t\t\t0xfe << 0 | 0x0a << 8 | (byte) Code.Ldarga << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Starg = new OpCode (\n\t\t\t0xfe << 0 | 0x0b << 8 | (byte) Code.Starg << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineArg << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Ldloc = new OpCode (\n\t\t\t0xfe << 0 | 0x0c << 8 | (byte) Code.Ldloc << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);\n\n\t\tpublic static readonly OpCode Ldloca = new OpCode (\n\t\t\t0xfe << 0 | 0x0d << 8 | (byte) Code.Ldloca << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Stloc = new OpCode (\n\t\t\t0xfe << 0 | 0x0e << 8 | (byte) Code.Stloc << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineVar << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Localloc = new OpCode (\n\t\t\t0xfe << 0 | 0x0f << 8 | (byte) Code.Localloc << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Endfilter = new OpCode (\n\t\t\t0xfe << 0 | 0x11 << 8 | (byte) Code.Endfilter << 16 | (byte) FlowControl.Return << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Unaligned = new OpCode (\n\t\t\t0xfe << 0 | 0x12 << 8 | (byte) Code.Unaligned << 16 | (byte) FlowControl.Meta << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.ShortInlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Volatile = new OpCode (\n\t\t\t0xfe << 0 | 0x13 << 8 | (byte) Code.Volatile << 16 | (byte) FlowControl.Meta << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Tail = new OpCode (\n\t\t\t0xfe << 0 | 0x14 << 8 | (byte) Code.Tail << 16 | (byte) FlowControl.Meta << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Initobj = new OpCode (\n\t\t\t0xfe << 0 | 0x15 << 8 | (byte) Code.Initobj << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Constrained = new OpCode (\n\t\t\t0xfe << 0 | 0x16 << 8 | (byte) Code.Constrained << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Cpblk = new OpCode (\n\t\t\t0xfe << 0 | 0x17 << 8 | (byte) Code.Cpblk << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Initblk = new OpCode (\n\t\t\t0xfe << 0 | 0x18 << 8 | (byte) Code.Initblk << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode No = new OpCode (\n\t\t\t0xfe << 0 | 0x19 << 8 | (byte) Code.No << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.ShortInlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Rethrow = new OpCode (\n\t\t\t0xfe << 0 | 0x1a << 8 | (byte) Code.Rethrow << 16 | (byte) FlowControl.Throw << 24,\n\t\t\t(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\n\t\tpublic static readonly OpCode Sizeof = new OpCode (\n\t\t\t0xfe << 0 | 0x1c << 8 | (byte) Code.Sizeof << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Refanytype = new OpCode (\n\t\t\t0xfe << 0 | 0x1d << 8 | (byte) Code.Refanytype << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);\n\n\t\tpublic static readonly OpCode Readonly = new OpCode (\n\t\t\t0xfe << 0 | 0x1e << 8 | (byte) Code.Readonly << 16 | (byte) FlowControl.Next << 24,\n\t\t\t(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/SequencePoint.cs",
    "content": "//\n// SequencePoint.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic sealed class SequencePoint {\n\n\t\tDocument document;\n\n\t\tint start_line;\n\t\tint start_column;\n\t\tint end_line;\n\t\tint end_column;\n\n\t\tpublic int StartLine {\n\t\t\tget { return start_line; }\n\t\t\tset { start_line = value; }\n\t\t}\n\n\t\tpublic int StartColumn {\n\t\t\tget { return start_column; }\n\t\t\tset { start_column = value; }\n\t\t}\n\n\t\tpublic int EndLine {\n\t\t\tget { return end_line; }\n\t\t\tset { end_line = value; }\n\t\t}\n\n\t\tpublic int EndColumn {\n\t\t\tget { return end_column; }\n\t\t\tset { end_column = value; }\n\t\t}\n\n\t\tpublic Document Document {\n\t\t\tget { return document; }\n\t\t\tset { document = value; }\n\t\t}\n\n\t\tpublic SequencePoint (Document document)\n\t\t{\n\t\t\tthis.document = document;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/Symbols.cs",
    "content": "//\n// Symbols.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\nusing System.Runtime.InteropServices;\nusing SR = System.Reflection;\n\nusing Mono.Collections.Generic;\n\nnamespace Mono.Cecil.Cil {\n\n\t[StructLayout (LayoutKind.Sequential)]\n\tpublic struct ImageDebugDirectory {\n\t\tpublic int Characteristics;\n\t\tpublic int TimeDateStamp;\n\t\tpublic short MajorVersion;\n\t\tpublic short MinorVersion;\n\t\tpublic int Type;\n\t\tpublic int SizeOfData;\n\t\tpublic int AddressOfRawData;\n\t\tpublic int PointerToRawData;\n\t}\n\n\tpublic sealed class Scope : IVariableDefinitionProvider {\n\n\t\tInstruction start;\n\t\tInstruction end;\n\n\t\tCollection<Scope> scopes;\n\t\tCollection<VariableDefinition> variables;\n\n\t\tpublic Instruction Start {\n\t\t\tget { return start; }\n\t\t\tset { start = value; }\n\t\t}\n\n\t\tpublic Instruction End {\n\t\t\tget { return end; }\n\t\t\tset { end = value; }\n\t\t}\n\n\t\tpublic bool HasScopes {\n\t\t\tget { return !Mixin.IsNullOrEmpty (scopes); }\n\t\t}\n\n\t\tpublic Collection<Scope> Scopes {\n\t\t\tget {\n\t\t\t\tif (scopes == null)\n\t\t\t\t\tscopes = new Collection<Scope> ();\n\n\t\t\t\treturn scopes;\n\t\t\t}\n\t\t}\n\n\t\tpublic bool HasVariables {\n\t\t\tget { return !Mixin.IsNullOrEmpty (variables); }\n\t\t}\n\n\t\tpublic Collection<VariableDefinition> Variables {\n\t\t\tget {\n\t\t\t\tif (variables == null)\n\t\t\t\t\tvariables = new Collection<VariableDefinition> ();\n\n\t\t\t\treturn variables;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic struct InstructionSymbol {\n\n\t\tpublic readonly int Offset;\n\t\tpublic readonly SequencePoint SequencePoint;\n\n\t\tpublic InstructionSymbol (int offset, SequencePoint sequencePoint)\n\t\t{\n\t\t\tthis.Offset = offset;\n\t\t\tthis.SequencePoint = sequencePoint;\n\t\t}\n\t}\n\n\tpublic sealed class MethodSymbols {\n\n\t\tinternal int code_size;\n\t\tinternal string method_name;\n\t\tinternal MetadataToken method_token;\n\t\tinternal MetadataToken local_var_token;\n\t\tinternal Collection<VariableDefinition> variables;\n\t\tpublic Collection<InstructionSymbol> instructions;\n\n\t\tpublic bool HasVariables {\n\t\t\tget { return !Mixin.IsNullOrEmpty (variables); }\n\t\t}\n\n\t\tpublic Collection<VariableDefinition> Variables {\n\t\t\tget {\n\t\t\t\tif (variables == null)\n\t\t\t\t\tvariables = new Collection<VariableDefinition> ();\n\n\t\t\t\treturn variables;\n\t\t\t}\n\t\t}\n\n\t\tpublic Collection<InstructionSymbol> Instructions {\n\t\t\tget {\n\t\t\t\tif (instructions == null)\n\t\t\t\t\tinstructions = new Collection<InstructionSymbol> ();\n\n\t\t\t\treturn instructions;\n\t\t\t}\n\t\t}\n\n\t\tpublic int CodeSize {\n\t\t\tget { return code_size; }\n\t\t}\n\n\t\tpublic string MethodName {\n\t\t\tget { return method_name; }\n\t\t}\n\n\t\tpublic MetadataToken MethodToken {\n\t\t\tget { return method_token; }\n\t\t}\n\n\t\tpublic MetadataToken LocalVarToken {\n\t\t\tget { return local_var_token; }\n\t\t}\n\n\t\tinternal MethodSymbols (string methodName)\n\t\t{\n\t\t\tthis.method_name = methodName;\n\t\t}\n\n\t\tpublic MethodSymbols (MetadataToken methodToken)\n\t\t{\n\t\t\tthis.method_token = methodToken;\n\t\t}\n\t}\n\n\tpublic delegate Instruction InstructionMapper (int offset);\n\n\tpublic interface ISymbolReader : IDisposable {\n\n\t\tbool ProcessDebugHeader (ImageDebugDirectory directory, byte [] header);\n\t\tvoid Read (MethodBody body, InstructionMapper mapper);\n\t\tvoid Read (MethodSymbols symbols);\n\t}\n\n\tpublic interface ISymbolReaderProvider {\n\n\t\tISymbolReader GetSymbolReader (ModuleDefinition module, string fileName);\n\t\tISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream);\n\t}\n\n\tstatic class SymbolProvider {\n\n\t\tstatic readonly string symbol_kind = Type.GetType (\"Mono.Runtime\") != null ? \"Mdb\" : \"Pdb\";\n\n\t\tstatic SR.AssemblyName GetPlatformSymbolAssemblyName ()\n\t\t{\n\t\t\tvar cecil_name = typeof (SymbolProvider).Assembly.GetName ();\n\n\t\t\tvar name = new SR.AssemblyName {\n\t\t\t\tName = \"Mono.Cecil.\" + symbol_kind,\n\t\t\t\tVersion = cecil_name.Version,\n\t\t\t};\n\n\t\t\tname.SetPublicKeyToken (cecil_name.GetPublicKeyToken ());\n\n\t\t\treturn name;\n\t\t}\n\n\t\tstatic Type GetPlatformType (string fullname)\n\t\t{\n\t\t\tvar type = Type.GetType (fullname);\n\t\t\tif (type != null)\n\t\t\t\treturn type;\n\n\t\t\tvar assembly_name = GetPlatformSymbolAssemblyName ();\n\n\t\t\ttype = Type.GetType (fullname + \", \" + assembly_name.FullName);\n\t\t\tif (type != null)\n\t\t\t\treturn type;\n\n\t\t\ttry {\n\t\t\t\tvar assembly = SR.Assembly.Load (assembly_name);\n\t\t\t\tif (assembly != null)\n\t\t\t\t\treturn assembly.GetType (fullname);\n\t\t\t} catch (FileNotFoundException) {\n\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\n\t\tstatic ISymbolReaderProvider reader_provider;\n\n\t\tpublic static ISymbolReaderProvider GetPlatformReaderProvider ()\n\t\t{\n\t\t\tif (reader_provider != null)\n\t\t\t\treturn reader_provider;\n\n\t\t\tvar type = GetPlatformType (GetProviderTypeName (\"ReaderProvider\"));\n\t\t\tif (type == null)\n\t\t\t\treturn null;\n\n\t\t\treturn reader_provider = (ISymbolReaderProvider) Activator.CreateInstance (type);\n\t\t}\n\n\t\tstatic string GetProviderTypeName (string name)\n\t\t{\n\t\t\treturn \"Mono.Cecil.\" + symbol_kind + \".\" + symbol_kind + name;\n\t\t}\n\n\n\t}\n\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/VariableDefinition.cs",
    "content": "//\n// VariableDefinition.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic sealed class VariableDefinition : VariableReference {\n\n\t\tpublic bool IsPinned {\n\t\t\tget { return variable_type.IsPinned; }\n\t\t}\n\n\t\tpublic VariableDefinition (TypeReference variableType)\n\t\t\t: base (variableType)\n\t\t{\n\t\t}\n\n\t\tpublic VariableDefinition (string name, TypeReference variableType)\n\t\t\t: base (name, variableType)\n\t\t{\n\t\t}\n\n\t\tpublic override VariableDefinition Resolve ()\n\t\t{\n\t\t\treturn this;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Cil/VariableReference.cs",
    "content": "//\n// VariableReference.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Cil {\n\n\tpublic abstract class VariableReference {\n\n\t\tstring name;\n\t\tinternal int index = -1;\n\t\tprotected TypeReference variable_type;\n\n\t\tpublic string Name {\n\t\t\tget { return name; }\n\t\t\tset { name = value; }\n\t\t}\n\n\t\tpublic TypeReference VariableType {\n\t\t\tget { return variable_type; }\n\t\t\tset { variable_type = value; }\n\t\t}\n\n\t\tpublic int Index {\n\t\t\tget { return index; }\n\t\t}\n\n\t\tinternal VariableReference (TypeReference variable_type)\n\t\t\t: this (string.Empty, variable_type)\n\t\t{\n\t\t}\n\n\t\tinternal VariableReference (string name, TypeReference variable_type)\n\t\t{\n\t\t\tthis.name = name;\n\t\t\tthis.variable_type = variable_type;\n\t\t}\n\n\t\tpublic abstract VariableDefinition Resolve ();\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\tif (!string.IsNullOrEmpty (name))\n\t\t\t\treturn name;\n\n\t\t\tif (index >= 0)\n\t\t\t\treturn \"V_\" + index;\n\n\t\t\treturn string.Empty;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/BlobHeap.cs",
    "content": "//\n// BlobHeap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata\n{\n\n    sealed class BlobHeap : Heap\n    {\n\n        public BlobHeap(Section section, uint start, uint size)\n            : base(section, start, size)\n        {\n        }\n\n        public byte[] Read(uint index)\n        {\n            if (index == 0 || index > Size - 1)\n                return Empty<byte>.Array;\n\n            var data = Section.Data;\n\n            int position = (int)(index + Offset);\n            int length = (int)Mixin.ReadCompressedUInt32(data, ref position);\n\n            var buffer = new byte[length];\n\n            Buffer.BlockCopy(data, position, buffer, 0, length);\n\n            return buffer;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/Buffers.cs",
    "content": "//\n// TableHeapBuffer.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nusing Mono.Cecil.PE;\n\nusing RVA = System.UInt32;\n\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/CodedIndex.cs",
    "content": "//\n// CodedIndex.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Metadata {\n\n\tenum CodedIndex {\n\t\tTypeDefOrRef,\n\t\tHasConstant,\n\t\tHasCustomAttribute,\n\t\tHasFieldMarshal,\n\t\tHasDeclSecurity,\n\t\tMemberRefParent,\n\t\tHasSemantics,\n\t\tMethodDefOrRef,\n\t\tMemberForwarded,\n\t\tImplementation,\n\t\tCustomAttributeType,\n\t\tResolutionScope,\n\t\tTypeOrMethodDef\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/ElementType.cs",
    "content": "//\n// ElementType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil.Metadata {\n\n\tenum ElementType : byte {\n\t\tNone = 0x00,\n\t\tVoid = 0x01,\n\t\tBoolean = 0x02,\n\t\tChar = 0x03,\n\t\tI1 = 0x04,\n\t\tU1 = 0x05,\n\t\tI2 = 0x06,\n\t\tU2 = 0x07,\n\t\tI4 = 0x08,\n\t\tU4 = 0x09,\n\t\tI8 = 0x0a,\n\t\tU8 = 0x0b,\n\t\tR4 = 0x0c,\n\t\tR8 = 0x0d,\n\t\tString = 0x0e,\n\t\tPtr = 0x0f,   // Followed by <type> token\n\t\tByRef = 0x10,   // Followed by <type> token\n\t\tValueType = 0x11,   // Followed by <type> token\n\t\tClass = 0x12,   // Followed by <type> token\n\t\tVar = 0x13,   // Followed by generic parameter number\n\t\tArray = 0x14,   // <type> <rank> <boundsCount> <bound1>  <loCount> <lo1>\n\t\tGenericInst = 0x15,   // <type> <type-arg-count> <type-1> ... <type-n> */\n\t\tTypedByRef = 0x16,\n\t\tI = 0x18,   // System.IntPtr\n\t\tU = 0x19,   // System.UIntPtr\n\t\tFnPtr = 0x1b,   // Followed by full method signature\n\t\tObject = 0x1c,   // System.Object\n\t\tSzArray = 0x1d,   // Single-dim array with 0 lower bound\n\t\tMVar = 0x1e,   // Followed by generic parameter number\n\t\tCModReqD = 0x1f,   // Required modifier : followed by a TypeDef or TypeRef token\n\t\tCModOpt = 0x20,   // Optional modifier : followed by a TypeDef or TypeRef token\n\t\tInternal = 0x21,   // Implemented within the CLI\n\t\tModifier = 0x40,   // Or'd with following element types\n\t\tSentinel = 0x41,   // Sentinel for varargs method signature\n\t\tPinned = 0x45,   // Denotes a local variable that points at a pinned object\n\n\t\t// special undocumented constants\n\t\tType = 0x50,\n\t\tBoxed = 0x51,\n\t\tEnum = 0x55\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/GuidHeap.cs",
    "content": "//\n// GuidHeap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata {\n\n\tsealed class GuidHeap : Heap {\n\n\t\tpublic GuidHeap (Section section, uint start, uint size)\n\t\t\t: base (section, start, size)\n\t\t{\n\t\t}\n\n\t\tpublic Guid Read (uint index)\n\t\t{\n\t\t\tif (index == 0)\n\t\t\t\treturn new Guid ();\n\n\t\t\tconst int guid_size = 16;\n\n\t\t\tvar buffer = new byte [guid_size];\n\n\t\t\tindex--;\n\n\t\t\tBuffer.BlockCopy (Section.Data, (int) (Offset + index), buffer, 0, guid_size);\n\n\t\t\treturn new Guid (buffer);\n\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/Heap.cs",
    "content": "//\n// Heap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata {\n\n\tabstract class Heap {\n\n\t\tpublic int IndexSize;\n\n\t\tpublic readonly Section Section;\n\t\tpublic readonly uint Offset;\n\t\tpublic readonly uint Size;\n\n\t\tprotected Heap (Section section, uint offset, uint size)\n\t\t{\n\t\t\tthis.Section = section;\n\t\t\tthis.Offset = offset;\n\t\t\tthis.Size = size;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/MetadataToken.cs",
    "content": "//\n// MetadataToken.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic struct MetadataToken {\n\n\t\treadonly uint token;\n\n\t\tpublic uint RID\t{\n\t\t\tget { return token & 0x00ffffff; }\n\t\t}\n\n\t\tpublic TokenType TokenType {\n\t\t\tget { return (TokenType) (token & 0xff000000); }\n\t\t}\n\n\t\tpublic static readonly MetadataToken Zero = new MetadataToken ((uint) 0);\n\n\t\tpublic MetadataToken (uint token)\n\t\t{\n\t\t\tthis.token = token;\n\t\t}\n\n\t\tpublic MetadataToken (TokenType type)\n\t\t\t: this (type, 0)\n\t\t{\n\t\t}\n\n\t\tpublic MetadataToken (TokenType type, uint rid)\n\t\t{\n\t\t\ttoken = (uint) type | rid;\n\t\t}\n\n\t\tpublic MetadataToken (TokenType type, int rid)\n\t\t{\n\t\t\ttoken = (uint) type | (uint) rid;\n\t\t}\n\n\t\tpublic int ToInt32 ()\n\t\t{\n\t\t\treturn (int) token;\n\t\t}\n\n\t\tpublic uint ToUInt32 ()\n\t\t{\n\t\t\treturn token;\n\t\t}\n\n\t\tpublic override int GetHashCode ()\n\t\t{\n\t\t\treturn (int) token;\n\t\t}\n\n\t\tpublic override bool Equals (object obj)\n\t\t{\n\t\t\tif (obj is MetadataToken) {\n\t\t\t\tvar other = (MetadataToken) obj;\n\t\t\t\treturn other.token == token;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tpublic static bool operator == (MetadataToken one, MetadataToken other)\n\t\t{\n\t\t\treturn one.token == other.token;\n\t\t}\n\n\t\tpublic static bool operator != (MetadataToken one, MetadataToken other)\n\t\t{\n\t\t\treturn one.token != other.token;\n\t\t}\n\n\t\tpublic override string ToString ()\n\t\t{\n\t\t\treturn string.Format (\"[{0}:0x{1}]\", TokenType, RID.ToString (\"x4\"));\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/Row.cs",
    "content": "//\n// Row.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System.Collections.Generic;\n\nnamespace Mono.Cecil.Metadata {\n\n\tclass Row<T1, T2> {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\n\t\tpublic Row (T1 col1, T2 col2)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t}\n\t}\n\n    class Row<T1, T2, T3>\n    {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\t\tinternal T3 Col3;\n\n\t\tpublic Row (T1 col1, T2 col2, T3 col3)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t\tCol3 = col3;\n\t\t}\n\t}\n\n    class Row<T1, T2, T3, T4>\n    {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\t\tinternal T3 Col3;\n\t\tinternal T4 Col4;\n\n\t\tpublic Row (T1 col1, T2 col2, T3 col3, T4 col4)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t\tCol3 = col3;\n\t\t\tCol4 = col4;\n\t\t}\n\t}\n\n    class Row<T1, T2, T3, T4, T5>\n    {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\t\tinternal T3 Col3;\n\t\tinternal T4 Col4;\n\t\tinternal T5 Col5;\n\n\t\tpublic Row (T1 col1, T2 col2, T3 col3, T4 col4, T5 col5)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t\tCol3 = col3;\n\t\t\tCol4 = col4;\n\t\t\tCol5 = col5;\n\t\t}\n\t}\n\n    class Row<T1, T2, T3, T4, T5, T6>\n    {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\t\tinternal T3 Col3;\n\t\tinternal T4 Col4;\n\t\tinternal T5 Col5;\n\t\tinternal T6 Col6;\n\n\t\tpublic Row (T1 col1, T2 col2, T3 col3, T4 col4, T5 col5, T6 col6)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t\tCol3 = col3;\n\t\t\tCol4 = col4;\n\t\t\tCol5 = col5;\n\t\t\tCol6 = col6;\n\t\t}\n\t}\n\n    class Row<T1, T2, T3, T4, T5, T6, T7, T8, T9>\n    {\n\t\tinternal T1 Col1;\n\t\tinternal T2 Col2;\n\t\tinternal T3 Col3;\n\t\tinternal T4 Col4;\n\t\tinternal T5 Col5;\n\t\tinternal T6 Col6;\n\t\tinternal T7 Col7;\n\t\tinternal T8 Col8;\n\t\tinternal T9 Col9;\n\n\t\tpublic Row (T1 col1, T2 col2, T3 col3, T4 col4, T5 col5, T6 col6, T7 col7, T8 col8, T9 col9)\n\t\t{\n\t\t\tCol1 = col1;\n\t\t\tCol2 = col2;\n\t\t\tCol3 = col3;\n\t\t\tCol4 = col4;\n\t\t\tCol5 = col5;\n\t\t\tCol6 = col6;\n\t\t\tCol7 = col7;\n\t\t\tCol8 = col8;\n\t\t\tCol9 = col9;\n\t\t}\n\t}\n\n\tsealed class RowEqualityComparer : IEqualityComparer<Row<string, string>>, IEqualityComparer<Row<uint, uint>>, IEqualityComparer<Row<uint, uint, uint>> {\n\n\t\tpublic bool Equals (Row<string, string> x, Row<string, string> y)\n\t\t{\n\t\t\treturn x.Col1 == y.Col1\n\t\t\t\t&& x.Col2 == y.Col2;\n\t\t}\n\n\t\tpublic int GetHashCode (Row<string, string> obj)\n\t\t{\n\t\t\tstring x = obj.Col1, y = obj.Col2;\n\t\t\treturn (x != null ? x.GetHashCode () : 0) ^ (y != null ? y.GetHashCode () : 0);\n\t\t}\n\n\t\tpublic bool Equals (Row<uint, uint> x, Row<uint, uint> y)\n\t\t{\n\t\t\treturn x.Col1 == y.Col1\n\t\t\t\t&& x.Col2 == y.Col2;\n\t\t}\n\n\t\tpublic int GetHashCode (Row<uint, uint> obj)\n\t\t{\n\t\t\treturn (int) (obj.Col1 ^ obj.Col2);\n\t\t}\n\n\t\tpublic bool Equals (Row<uint, uint, uint> x, Row<uint, uint, uint> y)\n\t\t{\n\t\t\treturn x.Col1 == y.Col1\n\t\t\t\t&& x.Col2 == y.Col2\n\t\t\t\t&& x.Col3 == y.Col3;\n\t\t}\n\n\t\tpublic int GetHashCode (Row<uint, uint, uint> obj)\n\t\t{\n\t\t\treturn (int) (obj.Col1 ^ obj.Col2 ^ obj.Col3);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/StringHeap.cs",
    "content": "//\n// StringHeap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata {\n\n\tclass StringHeap : Heap {\n\n\t\treadonly Dictionary<uint, string> strings = new Dictionary<uint, string> ();\n\n\t\tpublic StringHeap (Section section, uint start, uint size)\n\t\t\t: base (section, start, size)\n\t\t{\n\t\t}\n\n\t\tpublic string Read (uint index)\n\t\t{\n\t\t\tif (index == 0)\n\t\t\t\treturn string.Empty;\n\n\t\t\tstring @string;\n\t\t\tif (strings.TryGetValue (index, out @string))\n\t\t\t\treturn @string;\n\n\t\t\tif (index > Size - 1)\n\t\t\t\treturn string.Empty;\n\n\t\t\t@string = ReadStringAt (index);\n\t\t\tif (@string.Length != 0)\n\t\t\t\tstrings.Add (index, @string);\n\n\t\t\treturn @string;\n\t\t}\n\n\t\tprotected virtual string ReadStringAt (uint index)\n\t\t{\n\t\t\tint length = 0;\n\t\t\tbyte [] data = Section.Data;\n\t\t\tint start = (int) (index + Offset);\n\n\t\t\tfor (int i = start; ; i++) {\n\t\t\t\tif (data [i] == 0)\n\t\t\t\t\tbreak;\n\n\t\t\t\tlength++;\n\t\t\t}\n\n\t\t\treturn Encoding.UTF8.GetString (data, start, length);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/TableHeap.cs",
    "content": "//\n// TableHeap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata {\n\n\tenum Table : byte {\n\t\tModule = 0x00,\n\t\tTypeRef = 0x01,\n\t\tTypeDef = 0x02,\n\t\tFieldPtr = 0x03,\n\t\tField = 0x04,\n\t\tMethodPtr = 0x05,\n\t\tMethod = 0x06,\n\t\tParamPtr = 0x07,\n\t\tParam = 0x08,\n\t\tInterfaceImpl = 0x09,\n\t\tMemberRef = 0x0a,\n\t\tConstant = 0x0b,\n\t\tCustomAttribute = 0x0c,\n\t\tFieldMarshal = 0x0d,\n\t\tDeclSecurity = 0x0e,\n\t\tClassLayout = 0x0f,\n\t\tFieldLayout = 0x10,\n\t\tStandAloneSig = 0x11,\n\t\tEventMap = 0x12,\n\t\tEventPtr = 0x13,\n\t\tEvent = 0x14,\n\t\tPropertyMap = 0x15,\n\t\tPropertyPtr = 0x16,\n\t\tProperty = 0x17,\n\t\tMethodSemantics = 0x18,\n\t\tMethodImpl = 0x19,\n\t\tModuleRef = 0x1a,\n\t\tTypeSpec = 0x1b,\n\t\tImplMap = 0x1c,\n\t\tFieldRVA = 0x1d,\n\t\tEncLog = 0x1e,\n\t\tEncMap = 0x1f,\n\t\tAssembly = 0x20,\n\t\tAssemblyProcessor = 0x21,\n\t\tAssemblyOS = 0x22,\n\t\tAssemblyRef = 0x23,\n\t\tAssemblyRefProcessor = 0x24,\n\t\tAssemblyRefOS = 0x25,\n\t\tFile = 0x26,\n\t\tExportedType = 0x27,\n\t\tManifestResource = 0x28,\n\t\tNestedClass = 0x29,\n\t\tGenericParam = 0x2a,\n\t\tMethodSpec = 0x2b,\n\t\tGenericParamConstraint = 0x2c,\n\t}\n\n\tstruct TableInformation {\n\t\tpublic uint Offset;\n\t\tpublic uint Length;\n\t\tpublic uint RowSize;\n\t}\n\n\tsealed class TableHeap : Heap {\n\n\t\tpublic long Valid;\n\t\tpublic long Sorted;\n\n\t\tpublic const int TableCount = 45;\n\n\t\tpublic readonly TableInformation [] Tables = new TableInformation [TableCount];\n\n\t\tpublic TableInformation this [Table table] {\n\t\t\tget { return Tables [(int) table]; }\n\t\t}\n\n\t\tpublic TableHeap (Section section, uint start, uint size)\n\t\t\t: base (section, start, size)\n\t\t{\n\t\t}\n\n\t\tpublic bool HasTable (Table table)\n\t\t{\n\t\t\treturn (Valid & (1L << (int) table)) != 0;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/TokenType.cs",
    "content": "//\n// TokenType.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nnamespace Mono.Cecil {\n\n\tpublic enum TokenType : uint {\n\t\tModule = 0x00000000,\n\t\tTypeRef = 0x01000000,\n\t\tTypeDef = 0x02000000,\n\t\tField = 0x04000000,\n\t\tMethod = 0x06000000,\n\t\tParam = 0x08000000,\n\t\tInterfaceImpl = 0x09000000,\n\t\tMemberRef = 0x0a000000,\n\t\tCustomAttribute = 0x0c000000,\n\t\tPermission = 0x0e000000,\n\t\tSignature = 0x11000000,\n\t\tEvent = 0x14000000,\n\t\tProperty = 0x17000000,\n\t\tModuleRef = 0x1a000000,\n\t\tTypeSpec = 0x1b000000,\n\t\tAssembly = 0x20000000,\n\t\tAssemblyRef = 0x23000000,\n\t\tFile = 0x26000000,\n\t\tExportedType = 0x27000000,\n\t\tManifestResource = 0x28000000,\n\t\tGenericParam = 0x2a000000,\n\t\tMethodSpec = 0x2b000000,\n\t\tString = 0x70000000,\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/UserStringHeap.cs",
    "content": "//\n// UserStringHeap.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.PE;\n\nnamespace Mono.Cecil.Metadata\n{\n\n    sealed class UserStringHeap : StringHeap\n    {\n\n        public UserStringHeap(Section section, uint start, uint size)\n            : base(section, start, size)\n        {\n        }\n\n        protected override string ReadStringAt(uint index)\n        {\n            byte[] data = Section.Data;\n            int start = (int)(index + Offset);\n\n            uint length = (uint)(Mixin.ReadCompressedUInt32(data, ref start) & ~1);\n            if (length < 1)\n                return string.Empty;\n\n            var chars = new char[length / 2];\n\n            for (int i = start, j = 0; i < start + length; i += 2)\n                chars[j++] = (char)(data[i] | (data[i + 1] << 8));\n\n            return new string(chars);\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/Utilities.cs",
    "content": "//\n// Utilities.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono.Cecil.Metadata;\n\nnamespace Mono.Cecil\n{\n\n    static partial class Mixin\n    {\n\n        public static uint ReadCompressedUInt32(byte[] data, ref int position)\n        {\n            uint integer;\n            if ((data[position] & 0x80) == 0)\n            {\n                integer = data[position];\n                position++;\n            }\n            else if ((data[position] & 0x40) == 0)\n            {\n                integer = (uint)(data[position] & ~0x80) << 8;\n                integer |= data[position + 1];\n                position += 2;\n            }\n            else\n            {\n                integer = (uint)(data[position] & ~0xc0) << 24;\n                integer |= (uint)data[position + 1] << 16;\n                integer |= (uint)data[position + 2] << 8;\n                integer |= (uint)data[position + 3];\n                position += 4;\n            }\n            return integer;\n        }\n\n        public static MetadataToken GetMetadataToken(CodedIndex self, uint data)\n        {\n            uint rid;\n            TokenType token_type;\n            switch (self)\n            {\n                case CodedIndex.TypeDefOrRef:\n                    rid = data >> 2;\n                    switch (data & 3)\n                    {\n                        case 0:\n                            token_type = TokenType.TypeDef; goto ret;\n                        case 1:\n                            token_type = TokenType.TypeRef; goto ret;\n                        case 2:\n                            token_type = TokenType.TypeSpec; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.HasConstant:\n                    rid = data >> 2;\n                    switch (data & 3)\n                    {\n                        case 0:\n                            token_type = TokenType.Field; goto ret;\n                        case 1:\n                            token_type = TokenType.Param; goto ret;\n                        case 2:\n                            token_type = TokenType.Property; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.HasCustomAttribute:\n                    rid = data >> 5;\n                    switch (data & 31)\n                    {\n                        case 0:\n                            token_type = TokenType.Method; goto ret;\n                        case 1:\n                            token_type = TokenType.Field; goto ret;\n                        case 2:\n                            token_type = TokenType.TypeRef; goto ret;\n                        case 3:\n                            token_type = TokenType.TypeDef; goto ret;\n                        case 4:\n                            token_type = TokenType.Param; goto ret;\n                        case 5:\n                            token_type = TokenType.InterfaceImpl; goto ret;\n                        case 6:\n                            token_type = TokenType.MemberRef; goto ret;\n                        case 7:\n                            token_type = TokenType.Module; goto ret;\n                        case 8:\n                            token_type = TokenType.Permission; goto ret;\n                        case 9:\n                            token_type = TokenType.Property; goto ret;\n                        case 10:\n                            token_type = TokenType.Event; goto ret;\n                        case 11:\n                            token_type = TokenType.Signature; goto ret;\n                        case 12:\n                            token_type = TokenType.ModuleRef; goto ret;\n                        case 13:\n                            token_type = TokenType.TypeSpec; goto ret;\n                        case 14:\n                            token_type = TokenType.Assembly; goto ret;\n                        case 15:\n                            token_type = TokenType.AssemblyRef; goto ret;\n                        case 16:\n                            token_type = TokenType.File; goto ret;\n                        case 17:\n                            token_type = TokenType.ExportedType; goto ret;\n                        case 18:\n                            token_type = TokenType.ManifestResource; goto ret;\n                        case 19:\n                            token_type = TokenType.GenericParam; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.HasFieldMarshal:\n                    rid = data >> 1;\n                    switch (data & 1)\n                    {\n                        case 0:\n                            token_type = TokenType.Field; goto ret;\n                        case 1:\n                            token_type = TokenType.Param; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.HasDeclSecurity:\n                    rid = data >> 2;\n                    switch (data & 3)\n                    {\n                        case 0:\n                            token_type = TokenType.TypeDef; goto ret;\n                        case 1:\n                            token_type = TokenType.Method; goto ret;\n                        case 2:\n                            token_type = TokenType.Assembly; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.MemberRefParent:\n                    rid = data >> 3;\n                    switch (data & 7)\n                    {\n                        case 0:\n                            token_type = TokenType.TypeDef; goto ret;\n                        case 1:\n                            token_type = TokenType.TypeRef; goto ret;\n                        case 2:\n                            token_type = TokenType.ModuleRef; goto ret;\n                        case 3:\n                            token_type = TokenType.Method; goto ret;\n                        case 4:\n                            token_type = TokenType.TypeSpec; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.HasSemantics:\n                    rid = data >> 1;\n                    switch (data & 1)\n                    {\n                        case 0:\n                            token_type = TokenType.Event; goto ret;\n                        case 1:\n                            token_type = TokenType.Property; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.MethodDefOrRef:\n                    rid = data >> 1;\n                    switch (data & 1)\n                    {\n                        case 0:\n                            token_type = TokenType.Method; goto ret;\n                        case 1:\n                            token_type = TokenType.MemberRef; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.MemberForwarded:\n                    rid = data >> 1;\n                    switch (data & 1)\n                    {\n                        case 0:\n                            token_type = TokenType.Field; goto ret;\n                        case 1:\n                            token_type = TokenType.Method; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.Implementation:\n                    rid = data >> 2;\n                    switch (data & 3)\n                    {\n                        case 0:\n                            token_type = TokenType.File; goto ret;\n                        case 1:\n                            token_type = TokenType.AssemblyRef; goto ret;\n                        case 2:\n                            token_type = TokenType.ExportedType; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.CustomAttributeType:\n                    rid = data >> 3;\n                    switch (data & 7)\n                    {\n                        case 2:\n                            token_type = TokenType.Method; goto ret;\n                        case 3:\n                            token_type = TokenType.MemberRef; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.ResolutionScope:\n                    rid = data >> 2;\n                    switch (data & 3)\n                    {\n                        case 0:\n                            token_type = TokenType.Module; goto ret;\n                        case 1:\n                            token_type = TokenType.ModuleRef; goto ret;\n                        case 2:\n                            token_type = TokenType.AssemblyRef; goto ret;\n                        case 3:\n                            token_type = TokenType.TypeRef; goto ret;\n                        default:\n                            goto exit;\n                    }\n                case CodedIndex.TypeOrMethodDef:\n                    rid = data >> 1;\n                    switch (data & 1)\n                    {\n                        case 0:\n                            token_type = TokenType.TypeDef; goto ret;\n                        case 1:\n                            token_type = TokenType.Method; goto ret;\n                        default: goto exit;\n                    }\n                default:\n                    goto exit;\n            }\n        ret:\n            return new MetadataToken(token_type, rid);\n        exit:\n            return MetadataToken.Zero;\n        }\n\n\n        public static int GetSize(CodedIndex self, Func<Table, int> counter)\n        {\n            int bits;\n            Table[] tables;\n\n            switch (self)\n            {\n                case CodedIndex.TypeDefOrRef:\n                    bits = 2;\n                    tables = new[] { Table.TypeDef, Table.TypeRef, Table.TypeSpec };\n                    break;\n                case CodedIndex.HasConstant:\n                    bits = 2;\n                    tables = new[] { Table.Field, Table.Param, Table.Property };\n                    break;\n                case CodedIndex.HasCustomAttribute:\n                    bits = 5;\n                    tables = new[] {\n\t\t\t\t\tTable.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef,\n\t\t\t\t\tTable.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef,\n\t\t\t\t\tTable.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType,\n\t\t\t\t\tTable.ManifestResource, Table.GenericParam\n\t\t\t\t};\n                    break;\n                case CodedIndex.HasFieldMarshal:\n                    bits = 1;\n                    tables = new[] { Table.Field, Table.Param };\n                    break;\n                case CodedIndex.HasDeclSecurity:\n                    bits = 2;\n                    tables = new[] { Table.TypeDef, Table.Method, Table.Assembly };\n                    break;\n                case CodedIndex.MemberRefParent:\n                    bits = 3;\n                    tables = new[] { Table.TypeDef, Table.TypeRef, Table.ModuleRef, Table.Method, Table.TypeSpec };\n                    break;\n                case CodedIndex.HasSemantics:\n                    bits = 1;\n                    tables = new[] { Table.Event, Table.Property };\n                    break;\n                case CodedIndex.MethodDefOrRef:\n                    bits = 1;\n                    tables = new[] { Table.Method, Table.MemberRef };\n                    break;\n                case CodedIndex.MemberForwarded:\n                    bits = 1;\n                    tables = new[] { Table.Field, Table.Method };\n                    break;\n                case CodedIndex.Implementation:\n                    bits = 2;\n                    tables = new[] { Table.File, Table.AssemblyRef, Table.ExportedType };\n                    break;\n                case CodedIndex.CustomAttributeType:\n                    bits = 3;\n                    tables = new[] { Table.Method, Table.MemberRef };\n                    break;\n                case CodedIndex.ResolutionScope:\n                    bits = 2;\n                    tables = new[] { Table.Module, Table.ModuleRef, Table.AssemblyRef, Table.TypeRef };\n                    break;\n                case CodedIndex.TypeOrMethodDef:\n                    bits = 1;\n                    tables = new[] { Table.TypeDef, Table.Method };\n                    break;\n                default:\n                    throw new ArgumentException();\n            }\n\n            int max = 0;\n\n            for (int i = 0; i < tables.Length; i++)\n            {\n                max = System.Math.Max(counter(tables[i]), max);\n            }\n\n            return max < (1 << (16 - bits)) ? 2 : 4;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/BinaryStreamReader.cs",
    "content": "//\n// BinaryStreamReader.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\n\nnamespace Mono.Cecil.PE {\n\n\tclass BinaryStreamReader : BinaryReader {\n\n\t\tpublic BinaryStreamReader (Stream stream)\n\t\t\t: base (stream)\n\t\t{\n\t\t}\n\n\t\tprotected void Advance (int bytes)\n\t\t{\n\t\t\tBaseStream.Seek (bytes, SeekOrigin.Current);\n\t\t}\n\n\t\tprotected DataDirectory ReadDataDirectory ()\n\t\t{\n\t\t\treturn new DataDirectory (ReadUInt32 (), ReadUInt32 ());\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/BinaryStreamWriter.cs",
    "content": "//\n// BinaryStreamWriter.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\n\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/ByteBuffer.cs",
    "content": "//\n// ByteBuffer.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nnamespace Mono.Cecil.PE {\n\n\tclass ByteBuffer {\n\n\t\tinternal byte [] buffer;\n\t\tinternal int length;\n\t\tinternal int position;\n\n\t\tpublic ByteBuffer ()\n\t\t{\n\t\t\tthis.buffer = Empty<byte>.Array;\n\t\t}\n\n\t\tpublic ByteBuffer (int length)\n\t\t{\n\t\t\tthis.buffer = new byte [length];\n\t\t}\n\n\t\tpublic ByteBuffer (byte [] buffer)\n\t\t{\n\t\t\tthis.buffer = buffer ?? Empty<byte>.Array;\n\t\t\tthis.length = this.buffer.Length;\n\t\t}\n\n\t\tpublic void Reset (byte [] buffer)\n\t\t{\n\t\t\tthis.buffer = buffer ?? Empty<byte>.Array;\n\t\t\tthis.length = this.buffer.Length;\n\t\t}\n\n\t\tpublic void Advance (int length)\n\t\t{\n\t\t\tposition += length;\n\t\t}\n\n\t\tpublic byte ReadByte ()\n\t\t{\n\t\t\treturn buffer [position++];\n\t\t}\n\n\t\tpublic sbyte ReadSByte ()\n\t\t{\n\t\t\treturn (sbyte) ReadByte ();\n\t\t}\n\n\t\tpublic byte [] ReadBytes (int length)\n\t\t{\n\t\t\tvar bytes = new byte [length];\n\t\t\tBuffer.BlockCopy (buffer, position, bytes, 0, length);\n\t\t\tposition += length;\n\t\t\treturn bytes;\n\t\t}\n\n\t\tpublic ushort ReadUInt16 ()\n\t\t{\n\t\t\tushort value = (ushort) (buffer [position]\n\t\t\t\t| (buffer [position + 1] << 8));\n\t\t\tposition += 2;\n\t\t\treturn value;\n\t\t}\n\n\t\tpublic short ReadInt16 ()\n\t\t{\n\t\t\treturn (short) ReadUInt16 ();\n\t\t}\n\n\t\tpublic uint ReadUInt32 ()\n\t\t{\n\t\t\tuint value = (uint) (buffer [position]\n\t\t\t\t| (buffer [position + 1] << 8)\n\t\t\t\t| (buffer [position + 2] << 16)\n\t\t\t\t| (buffer [position + 3] << 24));\n\t\t\tposition += 4;\n\t\t\treturn value;\n\t\t}\n\n\t\tpublic int ReadInt32 ()\n\t\t{\n\t\t\treturn (int) ReadUInt32 ();\n\t\t}\n\n\t\tpublic ulong ReadUInt64 ()\n\t\t{\n\t\t\tuint low = ReadUInt32 ();\n\t\t\tuint high = ReadUInt32 ();\n\n\t\t\treturn (((ulong) high) << 32) | low;\n\t\t}\n\n\t\tpublic long ReadInt64 ()\n\t\t{\n\t\t\treturn (long) ReadUInt64 ();\n\t\t}\n\n\t\tpublic uint ReadCompressedUInt32 ()\n\t\t{\n\t\t\tbyte first = ReadByte ();\n\t\t\tif ((first & 0x80) == 0)\n\t\t\t\treturn first;\n\n\t\t\tif ((first & 0x40) == 0)\n\t\t\t\treturn ((uint) (first & ~0x80) << 8)\n\t\t\t\t\t| ReadByte ();\n\n\t\t\treturn ((uint) (first & ~0xc0) << 24)\n\t\t\t\t| (uint) ReadByte () << 16\n\t\t\t\t| (uint) ReadByte () << 8\n\t\t\t\t| ReadByte ();\n\t\t}\n\n\t\tpublic int ReadCompressedInt32 ()\n\t\t{\n\t\t\tvar value = (int) (ReadCompressedUInt32 () >> 1);\n\t\t\tif ((value & 1) == 0)\n\t\t\t\treturn value;\n\t\t\tif (value < 0x40)\n\t\t\t\treturn value - 0x40;\n\t\t\tif (value < 0x2000)\n\t\t\t\treturn value - 0x2000;\n\t\t\tif (value < 0x10000000)\n\t\t\t\treturn value - 0x10000000;\n\t\t\treturn value - 0x20000000;\n\t\t}\n\n\t\tpublic float ReadSingle ()\n\t\t{\n\t\t\tif (!BitConverter.IsLittleEndian) {\n\t\t\t\tvar bytes = ReadBytes (4);\n\t\t\t\tArray.Reverse (bytes);\n\t\t\t\treturn BitConverter.ToSingle (bytes, 0);\n\t\t\t}\n\n\t\t\tfloat value = BitConverter.ToSingle (buffer, position);\n\t\t\tposition += 4;\n\t\t\treturn value;\n\t\t}\n\n\t\tpublic double ReadDouble ()\n\t\t{\n\t\t\tif (!BitConverter.IsLittleEndian) {\n\t\t\t\tvar bytes = ReadBytes (8);\n\t\t\t\tArray.Reverse (bytes);\n\t\t\t\treturn BitConverter.ToDouble (bytes, 0);\n\t\t\t}\n\n\t\t\tdouble value = BitConverter.ToDouble (buffer, position);\n\t\t\tposition += 8;\n\t\t\treturn value;\n\t\t}\n\n\n\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/ByteBufferEqualityComparer.cs",
    "content": "//\n// ByteBufferEqualityComparer.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections.Generic;\n\nnamespace Mono.Cecil.PE {\n\n\tsealed class ByteBufferEqualityComparer : IEqualityComparer<ByteBuffer> {\n\n\t\tpublic bool Equals (ByteBuffer x, ByteBuffer y)\n\t\t{\n\t\t\tif (x.length != y.length)\n\t\t\t\treturn false;\n\n\t\t\tvar x_buffer = x.buffer;\n\t\t\tvar y_buffer = y.buffer;\n\n\t\t\tfor (int i = 0; i < x.length; i++)\n\t\t\t\tif (x_buffer [i] != y_buffer [i])\n\t\t\t\t\treturn false;\n\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic int GetHashCode (ByteBuffer buffer)\n\t\t{\n#if !BYTE_BUFFER_WELL_DISTRIBUTED_HASH\n\t\t\tvar hash = 0;\n\t\t\tvar bytes = buffer.buffer;\n\t\t\tfor (int i = 0; i < buffer.length; i++)\n\t\t\t\thash = (hash * 37) ^ bytes [i];\n\n\t\t\treturn hash;\n#else\n\t\t\tconst uint p = 16777619;\n\t\t\tuint hash = 2166136261;\n\n\t\t\tvar bytes = buffer.buffer;\n\t\t\tfor (int i = 0; i < buffer.length; i++)\n\t\t\t    hash = (hash ^ bytes [i]) * p;\n\n\t\t\thash += hash << 13;\n\t\t\thash ^= hash >> 7;\n\t\t\thash += hash << 3;\n\t\t\thash ^= hash >> 17;\n\t\t\thash += hash << 5;\n\n\t\t\treturn (int) hash;\n#endif\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/DataDirectory.cs",
    "content": "//\n// DataDirectory.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil.PE {\n\n\tstruct DataDirectory {\n\n\t\tpublic readonly RVA VirtualAddress;\n\t\tpublic readonly uint Size;\n\n\t\tpublic bool IsZero {\n\t\t\tget { return VirtualAddress == 0 && Size == 0; }\n\t\t}\n\n\t\tpublic DataDirectory (RVA rva, uint size)\n\t\t{\n\t\t\tthis.VirtualAddress = rva;\n\t\t\tthis.Size = size;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/Image.cs",
    "content": "//\n// Image.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing Mono;\nusing Mono.Cecil.Cil;\nusing Mono.Cecil.Metadata;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil.PE\n{\n\n    sealed class Image\n    {\n\n        public ModuleKind Kind;\n        public TargetRuntime Runtime;\n        public TargetArchitecture Architecture;\n        public ModuleCharacteristics Characteristics;\n        public string FileName;\n\n        public Section[] Sections;\n\n        public Section MetadataSection;\n\n        public uint EntryPointToken;\n        public ModuleAttributes Attributes;\n\n        public DataDirectory Debug;\n        public DataDirectory Resources;\n        public DataDirectory StrongName;\n\n        public StringHeap StringHeap;\n        public BlobHeap BlobHeap;\n        public UserStringHeap UserStringHeap;\n        public GuidHeap GuidHeap;\n        public TableHeap TableHeap;\n\n        readonly int[] coded_index_sizes = new int[13];\n\n        readonly Func<Table, int> counter;\n\n        public Image()\n        {\n            counter = GetTableLength;\n        }\n\n        public bool HasTable(Table table)\n        {\n            return GetTableLength(table) > 0;\n        }\n\n        public int GetTableLength(Table table)\n        {\n            return (int)TableHeap[table].Length;\n        }\n\n        public int GetTableIndexSize(Table table)\n        {\n            return GetTableLength(table) < 65536 ? 2 : 4;\n        }\n\n        public int GetCodedIndexSize(CodedIndex coded_index)\n        {\n            var index = (int)coded_index;\n            var size = coded_index_sizes[index];\n            if (size != 0)\n                return size;\n\n            return coded_index_sizes[index] = Mixin.GetSize(coded_index, counter);\n        }\n\n        public uint ResolveVirtualAddress(RVA rva)\n        {\n            var section = GetSectionAtVirtualAddress(rva);\n            if (section == null)\n                throw new ArgumentOutOfRangeException();\n\n            return ResolveVirtualAddressInSection(rva, section);\n        }\n\n        public uint ResolveVirtualAddressInSection(RVA rva, Section section)\n        {\n            return rva + section.PointerToRawData - section.VirtualAddress;\n        }\n\n        public Section GetSection(string name)\n        {\n            var sections = this.Sections;\n            for (int i = 0; i < sections.Length; i++)\n            {\n                var section = sections[i];\n                if (section.Name == name)\n                    return section;\n            }\n\n            return null;\n        }\n\n        public Section GetSectionAtVirtualAddress(RVA rva)\n        {\n            var sections = this.Sections;\n            for (int i = 0; i < sections.Length; i++)\n            {\n                var section = sections[i];\n                if (rva >= section.VirtualAddress && rva < section.VirtualAddress + section.SizeOfRawData)\n                    return section;\n            }\n\n            return null;\n        }\n\n        public ImageDebugDirectory GetDebugHeader(out byte[] header)\n        {\n            var section = GetSectionAtVirtualAddress(Debug.VirtualAddress);\n            var buffer = new ByteBuffer(section.Data);\n            buffer.position = (int)(Debug.VirtualAddress - section.VirtualAddress);\n\n            var directory = new ImageDebugDirectory\n            {\n                Characteristics = buffer.ReadInt32(),\n                TimeDateStamp = buffer.ReadInt32(),\n                MajorVersion = buffer.ReadInt16(),\n                MinorVersion = buffer.ReadInt16(),\n                Type = buffer.ReadInt32(),\n                SizeOfData = buffer.ReadInt32(),\n                AddressOfRawData = buffer.ReadInt32(),\n                PointerToRawData = buffer.ReadInt32(),\n            };\n\n            buffer.position = (int)(directory.PointerToRawData - section.PointerToRawData);\n\n            header = new byte[directory.SizeOfData];\n            Buffer.BlockCopy(buffer.buffer, buffer.position, header, 0, header.Length);\n\n            return directory;\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/ImageReader.cs",
    "content": "//\n// ImageReader.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\n\nusing Mono.Cecil.Metadata;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil.PE\n{\n\n    sealed class ImageReader : BinaryStreamReader\n    {\n\n        readonly Image image;\n\n        DataDirectory cli;\n        DataDirectory metadata;\n\n        public ImageReader(Stream stream)\n            : base(stream)\n        {\n            image = new Image();\n\n            image.FileName = Mixin.GetFullyQualifiedName(stream);\n        }\n\n        void MoveTo(DataDirectory directory)\n        {\n            BaseStream.Position = image.ResolveVirtualAddress(directory.VirtualAddress);\n        }\n\n        void MoveTo(uint position)\n        {\n            BaseStream.Position = position;\n        }\n\n        void ReadImage()\n        {\n            if (BaseStream.Length < 128)\n                throw new BadImageFormatException();\n\n            // - DOSHeader\n\n            // PE\t\t\t\t\t2\n            // Start\t\t\t\t58\n            // Lfanew\t\t\t\t4\n            // End\t\t\t\t\t64\n\n            if (ReadUInt16() != 0x5a4d)\n                throw new BadImageFormatException();\n\n            Advance(58);\n\n            MoveTo(ReadUInt32());\n\n            if (ReadUInt32() != 0x00004550)\n                throw new BadImageFormatException();\n\n            // - PEFileHeader\n\n            // Machine\t\t\t\t2\n            image.Architecture = ReadArchitecture();\n\n            // NumberOfSections\t\t2\n            ushort sections = ReadUInt16();\n\n            // TimeDateStamp\t\t4\n            // PointerToSymbolTable\t4\n            // NumberOfSymbols\t\t4\n            // OptionalHeaderSize\t2\n            Advance(14);\n\n            // Characteristics\t\t2\n            ushort characteristics = ReadUInt16();\n\n            ushort subsystem, dll_characteristics;\n            ReadOptionalHeaders(out subsystem, out dll_characteristics);\n            ReadSections(sections);\n            ReadCLIHeader();\n            ReadMetadata();\n\n            image.Kind = GetModuleKind(characteristics, subsystem);\n            image.Characteristics = (ModuleCharacteristics)dll_characteristics;\n        }\n\n        TargetArchitecture ReadArchitecture()\n        {\n            var machine = ReadUInt16();\n            switch (machine)\n            {\n                case 0x014c:\n                    return TargetArchitecture.I386;\n                case 0x8664:\n                    return TargetArchitecture.AMD64;\n                case 0x0200:\n                    return TargetArchitecture.IA64;\n                case 0x01c4:\n                    return TargetArchitecture.ARMv7;\n            }\n\n            throw new NotSupportedException();\n        }\n\n        static ModuleKind GetModuleKind(ushort characteristics, ushort subsystem)\n        {\n            if ((characteristics & 0x2000) != 0) // ImageCharacteristics.Dll\n                return ModuleKind.Dll;\n\n            if (subsystem == 0x2 || subsystem == 0x9) // SubSystem.WindowsGui || SubSystem.WindowsCeGui\n                return ModuleKind.Windows;\n\n            return ModuleKind.Console;\n        }\n\n        void ReadOptionalHeaders(out ushort subsystem, out ushort dll_characteristics)\n        {\n            // - PEOptionalHeader\n            //   - StandardFieldsHeader\n\n            // Magic\t\t\t\t2\n            bool pe64 = ReadUInt16() == 0x20b;\n\n            //\t\t\t\t\t\tpe32 || pe64\n\n            // LMajor\t\t\t\t1\n            // LMinor\t\t\t\t1\n            // CodeSize\t\t\t\t4\n            // InitializedDataSize\t4\n            // UninitializedDataSize4\n            // EntryPointRVA\t\t4\n            // BaseOfCode\t\t\t4\n            // BaseOfData\t\t\t4 || 0\n\n            //   - NTSpecificFieldsHeader\n\n            // ImageBase\t\t\t4 || 8\n            // SectionAlignment\t\t4\n            // FileAlignement\t\t4\n            // OSMajor\t\t\t\t2\n            // OSMinor\t\t\t\t2\n            // UserMajor\t\t\t2\n            // UserMinor\t\t\t2\n            // SubSysMajor\t\t\t2\n            // SubSysMinor\t\t\t2\n            // Reserved\t\t\t\t4\n            // ImageSize\t\t\t4\n            // HeaderSize\t\t\t4\n            // FileChecksum\t\t\t4\n            Advance(66);\n\n            // SubSystem\t\t\t2\n            subsystem = ReadUInt16();\n\n            // DLLFlags\t\t\t\t2\n            dll_characteristics = ReadUInt16();\n            // StackReserveSize\t\t4 || 8\n            // StackCommitSize\t\t4 || 8\n            // HeapReserveSize\t\t4 || 8\n            // HeapCommitSize\t\t4 || 8\n            // LoaderFlags\t\t\t4\n            // NumberOfDataDir\t\t4\n\n            //   - DataDirectoriesHeader\n\n            // ExportTable\t\t\t8\n            // ImportTable\t\t\t8\n            // ResourceTable\t\t8\n            // ExceptionTable\t\t8\n            // CertificateTable\t\t8\n            // BaseRelocationTable\t8\n\n            Advance(pe64 ? 88 : 72);\n\n            // Debug\t\t\t\t8\n            image.Debug = ReadDataDirectory();\n\n            // Copyright\t\t\t8\n            // GlobalPtr\t\t\t8\n            // TLSTable\t\t\t\t8\n            // LoadConfigTable\t\t8\n            // BoundImport\t\t\t8\n            // IAT\t\t\t\t\t8\n            // DelayImportDescriptor8\n            Advance(56);\n\n            // CLIHeader\t\t\t8\n            cli = ReadDataDirectory();\n\n            if (cli.IsZero)\n                throw new BadImageFormatException();\n\n            // Reserved\t\t\t\t8\n            Advance(8);\n        }\n\n        string ReadAlignedString(int length)\n        {\n            int read = 0;\n            var buffer = new char[length];\n            while (read < length)\n            {\n                var current = ReadByte();\n                if (current == 0)\n                    break;\n\n                buffer[read++] = (char)current;\n            }\n\n            Advance(-1 + ((read + 4) & ~3) - read);\n\n            return new string(buffer, 0, read);\n        }\n\n        string ReadZeroTerminatedString(int length)\n        {\n            int read = 0;\n            var buffer = new char[length];\n            var bytes = ReadBytes(length);\n            while (read < length)\n            {\n                var current = bytes[read];\n                if (current == 0)\n                    break;\n\n                buffer[read++] = (char)current;\n            }\n\n            return new string(buffer, 0, read);\n        }\n\n        void ReadSections(ushort count)\n        {\n            var sections = new Section[count];\n\n            for (int i = 0; i < count; i++)\n            {\n                var section = new Section();\n\n                // Name\n                section.Name = ReadZeroTerminatedString(8);\n\n                // VirtualSize\t\t4\n                Advance(4);\n\n                // VirtualAddress\t4\n                section.VirtualAddress = ReadUInt32();\n                // SizeOfRawData\t4\n                section.SizeOfRawData = ReadUInt32();\n                // PointerToRawData\t4\n                section.PointerToRawData = ReadUInt32();\n\n                // PointerToRelocations\t\t4\n                // PointerToLineNumbers\t\t4\n                // NumberOfRelocations\t\t2\n                // NumberOfLineNumbers\t\t2\n                // Characteristics\t\t\t4\n                Advance(16);\n\n                sections[i] = section;\n\n                ReadSectionData(section);\n            }\n\n            image.Sections = sections;\n        }\n\n        void ReadSectionData(Section section)\n        {\n            var position = BaseStream.Position;\n\n            MoveTo(section.PointerToRawData);\n\n            var length = (int)section.SizeOfRawData;\n            var data = new byte[length];\n            int offset = 0, read;\n\n            while ((read = Read(data, offset, length - offset)) > 0)\n                offset += read;\n\n            section.Data = data;\n\n            BaseStream.Position = position;\n        }\n\n        void ReadCLIHeader()\n        {\n            MoveTo(cli);\n\n            // - CLIHeader\n\n            // Cb\t\t\t\t\t\t4\n            // MajorRuntimeVersion\t\t2\n            // MinorRuntimeVersion\t\t2\n            Advance(8);\n\n            // Metadata\t\t\t\t\t8\n            metadata = ReadDataDirectory();\n            // Flags\t\t\t\t\t4\n            image.Attributes = (ModuleAttributes)ReadUInt32();\n            // EntryPointToken\t\t\t4\n            image.EntryPointToken = ReadUInt32();\n            // Resources\t\t\t\t8\n            image.Resources = ReadDataDirectory();\n            // StrongNameSignature\t\t8\n            image.StrongName = ReadDataDirectory();\n            // CodeManagerTable\t\t\t8\n            // VTableFixups\t\t\t\t8\n            // ExportAddressTableJumps\t8\n            // ManagedNativeHeader\t\t8\n        }\n\n        void ReadMetadata()\n        {\n            MoveTo(metadata);\n\n            if (ReadUInt32() != 0x424a5342)\n                throw new BadImageFormatException();\n\n            // MajorVersion\t\t\t2\n            // MinorVersion\t\t\t2\n            // Reserved\t\t\t\t4\n            Advance(8);\n\n            var version = ReadZeroTerminatedString(ReadInt32());\n            image.Runtime = Mixin.ParseRuntime(version);\n\n            // Flags\t\t2\n            Advance(2);\n\n            var streams = ReadUInt16();\n\n            var section = image.GetSectionAtVirtualAddress(metadata.VirtualAddress);\n            if (section == null)\n                throw new BadImageFormatException();\n\n            image.MetadataSection = section;\n\n            for (int i = 0; i < streams; i++)\n                ReadMetadataStream(section);\n\n            if (image.TableHeap != null)\n                ReadTableHeap();\n        }\n\n        void ReadMetadataStream(Section section)\n        {\n            // Offset\t\t4\n            uint start = metadata.VirtualAddress - section.VirtualAddress + ReadUInt32(); // relative to the section start\n\n            // Size\t\t\t4\n            uint size = ReadUInt32();\n\n            var name = ReadAlignedString(16);\n            switch (name)\n            {\n                case \"#~\":\n                case \"#-\":\n                    image.TableHeap = new TableHeap(section, start, size);\n                    break;\n                case \"#Strings\":\n                    image.StringHeap = new StringHeap(section, start, size);\n                    break;\n                case \"#Blob\":\n                    image.BlobHeap = new BlobHeap(section, start, size);\n                    break;\n                case \"#GUID\":\n                    image.GuidHeap = new GuidHeap(section, start, size);\n                    break;\n                case \"#US\":\n                    image.UserStringHeap = new UserStringHeap(section, start, size);\n                    break;\n            }\n        }\n\n        void ReadTableHeap()\n        {\n            var heap = image.TableHeap;\n\n            uint start = heap.Section.PointerToRawData;\n\n            MoveTo(heap.Offset + start);\n\n            // Reserved\t\t\t4\n            // MajorVersion\t\t1\n            // MinorVersion\t\t1\n            Advance(6);\n\n            // HeapSizes\t\t1\n            var sizes = ReadByte();\n\n            // Reserved2\t\t1\n            Advance(1);\n\n            // Valid\t\t\t8\n            heap.Valid = ReadInt64();\n\n            // Sorted\t\t\t8\n            heap.Sorted = ReadInt64();\n\n            for (int i = 0; i < TableHeap.TableCount; i++)\n            {\n                if (!heap.HasTable((Table)i))\n                    continue;\n\n                heap.Tables[i].Length = ReadUInt32();\n            }\n\n            SetIndexSize(image.StringHeap, sizes, 0x1);\n            SetIndexSize(image.GuidHeap, sizes, 0x2);\n            SetIndexSize(image.BlobHeap, sizes, 0x4);\n\n            ComputeTableInformations();\n        }\n\n        static void SetIndexSize(Heap heap, uint sizes, byte flag)\n        {\n            if (heap == null)\n                return;\n\n            heap.IndexSize = (sizes & flag) > 0 ? 4 : 2;\n        }\n\n        int GetTableIndexSize(Table table)\n        {\n            return image.GetTableIndexSize(table);\n        }\n\n        int GetCodedIndexSize(CodedIndex index)\n        {\n            return image.GetCodedIndexSize(index);\n        }\n\n        void ComputeTableInformations()\n        {\n            uint offset = (uint)BaseStream.Position - image.MetadataSection.PointerToRawData; // header\n\n            int stridx_size = image.StringHeap.IndexSize;\n            int blobidx_size = image.BlobHeap != null ? image.BlobHeap.IndexSize : 2;\n\n            var heap = image.TableHeap;\n            var tables = heap.Tables;\n\n            for (int i = 0; i < TableHeap.TableCount; i++)\n            {\n                var table = (Table)i;\n                if (!heap.HasTable(table))\n                    continue;\n\n                int size;\n                switch (table)\n                {\n                    case Table.Module:\n                        size = 2\t// Generation\n                            + stridx_size\t// Name\n                            + (image.GuidHeap.IndexSize * 3);\t// Mvid, EncId, EncBaseId\n                        break;\n                    case Table.TypeRef:\n                        size = GetCodedIndexSize(CodedIndex.ResolutionScope)\t// ResolutionScope\n                            + (stridx_size * 2);\t// Name, Namespace\n                        break;\n                    case Table.TypeDef:\n                        size = 4\t// Flags\n                            + (stridx_size * 2)\t// Name, Namespace\n                            + GetCodedIndexSize(CodedIndex.TypeDefOrRef)\t// BaseType\n                            + GetTableIndexSize(Table.Field)\t// FieldList\n                            + GetTableIndexSize(Table.Method);\t// MethodList\n                        break;\n                    case Table.FieldPtr:\n                        size = GetTableIndexSize(Table.Field);\t// Field\n                        break;\n                    case Table.Field:\n                        size = 2\t// Flags\n                            + stridx_size\t// Name\n                            + blobidx_size;\t// Signature\n                        break;\n                    case Table.MethodPtr:\n                        size = GetTableIndexSize(Table.Method);\t// Method\n                        break;\n                    case Table.Method:\n                        size = 8\t// Rva 4, ImplFlags 2, Flags 2\n                            + stridx_size\t// Name\n                            + blobidx_size\t// Signature\n                            + GetTableIndexSize(Table.Param); // ParamList\n                        break;\n                    case Table.ParamPtr:\n                        size = GetTableIndexSize(Table.Param); // Param\n                        break;\n                    case Table.Param:\n                        size = 4\t// Flags 2, Sequence 2\n                            + stridx_size;\t// Name\n                        break;\n                    case Table.InterfaceImpl:\n                        size = GetTableIndexSize(Table.TypeDef)\t// Class\n                            + GetCodedIndexSize(CodedIndex.TypeDefOrRef);\t// Interface\n                        break;\n                    case Table.MemberRef:\n                        size = GetCodedIndexSize(CodedIndex.MemberRefParent)\t// Class\n                            + stridx_size\t// Name\n                            + blobidx_size;\t// Signature\n                        break;\n                    case Table.Constant:\n                        size = 2\t// Type\n                            + GetCodedIndexSize(CodedIndex.HasConstant)\t// Parent\n                            + blobidx_size;\t// Value\n                        break;\n                    case Table.CustomAttribute:\n                        size = GetCodedIndexSize(CodedIndex.HasCustomAttribute)\t// Parent\n                            + GetCodedIndexSize(CodedIndex.CustomAttributeType)\t// Type\n                            + blobidx_size;\t// Value\n                        break;\n                    case Table.FieldMarshal:\n                        size = GetCodedIndexSize(CodedIndex.HasFieldMarshal)\t// Parent\n                            + blobidx_size;\t// NativeType\n                        break;\n                    case Table.DeclSecurity:\n                        size = 2\t// Action\n                            + GetCodedIndexSize(CodedIndex.HasDeclSecurity)\t// Parent\n                            + blobidx_size;\t// PermissionSet\n                        break;\n                    case Table.ClassLayout:\n                        size = 6\t// PackingSize 2, ClassSize 4\n                            + GetTableIndexSize(Table.TypeDef);\t// Parent\n                        break;\n                    case Table.FieldLayout:\n                        size = 4\t// Offset\n                            + GetTableIndexSize(Table.Field);\t// Field\n                        break;\n                    case Table.StandAloneSig:\n                        size = blobidx_size;\t// Signature\n                        break;\n                    case Table.EventMap:\n                        size = GetTableIndexSize(Table.TypeDef)\t// Parent\n                            + GetTableIndexSize(Table.Event);\t// EventList\n                        break;\n                    case Table.EventPtr:\n                        size = GetTableIndexSize(Table.Event);\t// Event\n                        break;\n                    case Table.Event:\n                        size = 2\t// Flags\n                            + stridx_size // Name\n                            + GetCodedIndexSize(CodedIndex.TypeDefOrRef);\t// EventType\n                        break;\n                    case Table.PropertyMap:\n                        size = GetTableIndexSize(Table.TypeDef)\t// Parent\n                            + GetTableIndexSize(Table.Property);\t// PropertyList\n                        break;\n                    case Table.PropertyPtr:\n                        size = GetTableIndexSize(Table.Property);\t// Property\n                        break;\n                    case Table.Property:\n                        size = 2\t// Flags\n                            + stridx_size\t// Name\n                            + blobidx_size;\t// Type\n                        break;\n                    case Table.MethodSemantics:\n                        size = 2\t// Semantics\n                            + GetTableIndexSize(Table.Method)\t// Method\n                            + GetCodedIndexSize(CodedIndex.HasSemantics);\t// Association\n                        break;\n                    case Table.MethodImpl:\n                        size = GetTableIndexSize(Table.TypeDef)\t// Class\n                            + GetCodedIndexSize(CodedIndex.MethodDefOrRef)\t// MethodBody\n                            + GetCodedIndexSize(CodedIndex.MethodDefOrRef);\t// MethodDeclaration\n                        break;\n                    case Table.ModuleRef:\n                        size = stridx_size;\t// Name\n                        break;\n                    case Table.TypeSpec:\n                        size = blobidx_size;\t// Signature\n                        break;\n                    case Table.ImplMap:\n                        size = 2\t// MappingFlags\n                            + GetCodedIndexSize(CodedIndex.MemberForwarded)\t// MemberForwarded\n                            + stridx_size\t// ImportName\n                            + GetTableIndexSize(Table.ModuleRef);\t// ImportScope\n                        break;\n                    case Table.FieldRVA:\n                        size = 4\t// RVA\n                            + GetTableIndexSize(Table.Field);\t// Field\n                        break;\n                    case Table.EncLog:\n                    case Table.EncMap:\n                        size = 4;\n                        break;\n                    case Table.Assembly:\n                        size = 16 // HashAlgId 4, Version 4 * 2, Flags 4\n                            + blobidx_size\t// PublicKey\n                            + (stridx_size * 2);\t// Name, Culture\n                        break;\n                    case Table.AssemblyProcessor:\n                        size = 4;\t// Processor\n                        break;\n                    case Table.AssemblyOS:\n                        size = 12;\t// Platform 4, Version 2 * 4\n                        break;\n                    case Table.AssemblyRef:\n                        size = 12\t// Version 2 * 4 + Flags 4\n                            + (blobidx_size * 2)\t// PublicKeyOrToken, HashValue\n                            + (stridx_size * 2);\t// Name, Culture\n                        break;\n                    case Table.AssemblyRefProcessor:\n                        size = 4\t// Processor\n                            + GetTableIndexSize(Table.AssemblyRef);\t// AssemblyRef\n                        break;\n                    case Table.AssemblyRefOS:\n                        size = 12\t// Platform 4, Version 2 * 4\n                            + GetTableIndexSize(Table.AssemblyRef);\t// AssemblyRef\n                        break;\n                    case Table.File:\n                        size = 4\t// Flags\n                            + stridx_size\t// Name\n                            + blobidx_size;\t// HashValue\n                        break;\n                    case Table.ExportedType:\n                        size = 8\t// Flags 4, TypeDefId 4\n                            + (stridx_size * 2)\t// Name, Namespace\n                            + GetCodedIndexSize(CodedIndex.Implementation);\t// Implementation\n                        break;\n                    case Table.ManifestResource:\n                        size = 8\t// Offset, Flags\n                            + stridx_size\t// Name\n                            + GetCodedIndexSize(CodedIndex.Implementation);\t// Implementation\n                        break;\n                    case Table.NestedClass:\n                        size = GetTableIndexSize(Table.TypeDef)\t// NestedClass\n                            + GetTableIndexSize(Table.TypeDef);\t// EnclosingClass\n                        break;\n                    case Table.GenericParam:\n                        size = 4\t// Number, Flags\n                            + GetCodedIndexSize(CodedIndex.TypeOrMethodDef)\t// Owner\n                            + stridx_size;\t// Name\n                        break;\n                    case Table.MethodSpec:\n                        size = GetCodedIndexSize(CodedIndex.MethodDefOrRef)\t// Method\n                            + blobidx_size;\t// Instantiation\n                        break;\n                    case Table.GenericParamConstraint:\n                        size = GetTableIndexSize(Table.GenericParam)\t// Owner\n                            + GetCodedIndexSize(CodedIndex.TypeDefOrRef);\t// Constraint\n                        break;\n                    default:\n                        throw new NotSupportedException();\n                }\n\n                tables[i].RowSize = (uint)size;\n                tables[i].Offset = offset;\n\n                offset += (uint)size * tables[i].Length;\n            }\n        }\n\n        public static Image ReadImageFrom(Stream stream)\n        {\n            try\n            {\n                var reader = new ImageReader(stream);\n                reader.ReadImage();\n                return reader.image;\n            }\n            catch (EndOfStreamException e)\n            {\n                throw new BadImageFormatException(Mixin.GetFullyQualifiedName(stream), e);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/ImageWriter.cs",
    "content": ""
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/Section.cs",
    "content": "//\n// Section.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\n\nusing RVA = System.UInt32;\n\nnamespace Mono.Cecil.PE {\n\n\tsealed class Section {\n\t\tpublic string Name;\n\t\tpublic RVA VirtualAddress;\n\t\tpublic uint VirtualSize;\n\t\tpublic uint SizeOfRawData;\n\t\tpublic uint PointerToRawData;\n\t\tpublic byte [] Data;\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Cecil.PE/TextMap.cs",
    "content": ""
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Collections.Generic/Collection.cs",
    "content": "//\n// Collection.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace Mono.Collections.Generic {\n\n\tpublic class Collection<T> : IList<T>, IList {\n\n\t\tinternal T [] items;\n\t\tinternal int size;\n\t\tint version;\n\n\t\tpublic int Count {\n\t\t\tget { return size; }\n\t\t}\n\n\t\tpublic T this [int index] {\n\t\t\tget {\n\t\t\t\tif (index >= size)\n\t\t\t\t\tthrow new ArgumentOutOfRangeException ();\n\n\t\t\t\treturn items [index];\n\t\t\t}\n\t\t\tset {\n\t\t\t\tCheckIndex (index);\n\t\t\t\tif (index == size)\n\t\t\t\t\tthrow new ArgumentOutOfRangeException ();\n\n\t\t\t\tOnSet (value, index);\n\n\t\t\t\titems [index] = value;\n\t\t\t}\n\t\t}\n\n\t\tbool ICollection<T>.IsReadOnly {\n\t\t\tget { return false; }\n\t\t}\n\n\t\tbool IList.IsFixedSize {\n\t\t\tget { return false; }\n\t\t}\n\n\t\tbool IList.IsReadOnly {\n\t\t\tget { return false; }\n\t\t}\n\n\t\tobject IList.this [int index] {\n\t\t\tget { return this [index]; }\n\t\t\tset {\n\t\t\t\tCheckIndex (index);\n\n\t\t\t\ttry {\n\t\t\t\t\tthis [index] = (T) value;\n\t\t\t\t\treturn;\n\t\t\t\t} catch (InvalidCastException) {\n\t\t\t\t} catch (NullReferenceException) {\n\t\t\t\t}\n\n\t\t\t\tthrow new ArgumentException ();\n\t\t\t}\n\t\t}\n\n\t\tint ICollection.Count {\n\t\t\tget { return Count; }\n\t\t}\n\n\t\tbool ICollection.IsSynchronized {\n\t\t\tget { return false; }\n\t\t}\n\n\t\tobject ICollection.SyncRoot {\n\t\t\tget { return this; }\n\t\t}\n\n\t\tpublic Collection ()\n\t\t{\n\t\t\titems = Empty<T>.Array;\n\t\t}\n\n\t\tpublic Collection (int capacity)\n\t\t{\n\t\t\tif (capacity < 0)\n\t\t\t\tthrow new ArgumentOutOfRangeException ();\n\n\t\t\titems = new T [capacity];\n\t\t}\n\n\t\tpublic Collection (ICollection<T> items)\n\t\t{\n\t\t\tif (items == null)\n\t\t\t\tthrow new ArgumentNullException (\"items\");\n\n\t\t\tthis.items = new T [items.Count];\n\t\t\titems.CopyTo (this.items, 0);\n\t\t\tthis.size = this.items.Length;\n\t\t}\n\n\t\tpublic void Add (T item)\n\t\t{\n\t\t\tif (size == items.Length)\n\t\t\t\tGrow (1);\n\n\t\t\tOnAdd (item, size);\n\n\t\t\titems [size++] = item;\n\t\t\tversion++;\n\t\t}\n\n\t\tpublic bool Contains (T item)\n\t\t{\n\t\t\treturn IndexOf (item) != -1;\n\t\t}\n\n\t\tpublic int IndexOf (T item)\n\t\t{\n\t\t\treturn Array.IndexOf (items, item, 0, size);\n\t\t}\n\n\t\tpublic void Insert (int index, T item)\n\t\t{\n\t\t\tCheckIndex (index);\n\t\t\tif (size == items.Length)\n\t\t\t\tGrow (1);\n\n\t\t\tOnInsert (item, index);\n\n\t\t\tShift (index, 1);\n\t\t\titems [index] = item;\n\t\t\tversion++;\n\t\t}\n\n\t\tpublic void RemoveAt (int index)\n\t\t{\n\t\t\tif (index < 0 || index >= size)\n\t\t\t\tthrow new ArgumentOutOfRangeException ();\n\n\t\t\tvar item = items [index];\n\n\t\t\tOnRemove (item, index);\n\n\t\t\tShift (index, -1);\n\t\t\tArray.Clear (items, size, 1);\n\t\t\tversion++;\n\t\t}\n\n\t\tpublic bool Remove (T item)\n\t\t{\n\t\t\tvar index = IndexOf (item);\n\t\t\tif (index == -1)\n\t\t\t\treturn false;\n\n\t\t\tOnRemove (item, index);\n\n\t\t\tShift (index, -1);\n\t\t\tArray.Clear (items, size, 1);\n\t\t\tversion++;\n\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic void Clear ()\n\t\t{\n\t\t\tOnClear ();\n\n\t\t\tArray.Clear (items, 0, size);\n\t\t\tsize = 0;\n\t\t\tversion++;\n\t\t}\n\n\t\tpublic void CopyTo (T [] array, int arrayIndex)\n\t\t{\n\t\t\tArray.Copy (items, 0, array, arrayIndex, size);\n\t\t}\n\n\t\tpublic T [] ToArray ()\n\t\t{\n\t\t\tvar array = new T [size];\n\t\t\tArray.Copy (items, 0, array, 0, size);\n\t\t\treturn array;\n\t\t}\n\n\t\tvoid CheckIndex (int index)\n\t\t{\n\t\t\tif (index < 0 || index > size)\n\t\t\t\tthrow new ArgumentOutOfRangeException ();\n\t\t}\n\n\t\tvoid Shift (int start, int delta)\n\t\t{\n\t\t\tif (delta < 0)\n\t\t\t\tstart -= delta;\n\n\t\t\tif (start < size)\n\t\t\t\tArray.Copy (items, start, items, start + delta, size - start);\n\n\t\t\tsize += delta;\n\n\t\t\tif (delta < 0)\n\t\t\t\tArray.Clear (items, size, -delta);\n\t\t}\n\n\t\tprotected virtual void OnAdd (T item, int index)\n\t\t{\n\t\t}\n\n\t\tprotected virtual void OnInsert (T item, int index)\n\t\t{\n\t\t}\n\n\t\tprotected virtual void OnSet (T item, int index)\n\t\t{\n\t\t}\n\n\t\tprotected virtual void OnRemove (T item, int index)\n\t\t{\n\t\t}\n\n\t\tprotected virtual void OnClear ()\n\t\t{\n\t\t}\n\n\t\tinternal virtual void Grow (int desired)\n\t\t{\n\t\t\tint new_size = size + desired;\n\t\t\tif (new_size <= items.Length)\n\t\t\t\treturn;\n\n\t\t\tconst int default_capacity = 4;\n\n\t\t\tnew_size = System.Math.Max (\n\t\t\t\tSystem.Math.Max (items.Length * 2, default_capacity),\n\t\t\t\tnew_size);\n\n#if !CF\n\t\t\tArray.Resize (ref items, new_size);\n#else\n\t\t\tvar array = new T [new_size];\n\t\t\tArray.Copy (items, array, size);\n\t\t\titems = array;\n#endif\n\t\t}\n\n\t\tint IList.Add (object value)\n\t\t{\n\t\t\ttry {\n\t\t\t\tAdd ((T) value);\n\t\t\t\treturn size - 1;\n\t\t\t} catch (InvalidCastException) {\n\t\t\t} catch (NullReferenceException) {\n\t\t\t}\n\n\t\t\tthrow new ArgumentException ();\n\t\t}\n\n\t\tvoid IList.Clear ()\n\t\t{\n\t\t\tClear ();\n\t\t}\n\n\t\tbool IList.Contains (object value)\n\t\t{\n\t\t\treturn ((IList) this).IndexOf (value) > -1;\n\t\t}\n\n\t\tint IList.IndexOf (object value)\n\t\t{\n\t\t\ttry {\n\t\t\t\treturn IndexOf ((T) value);\n\t\t\t} catch (InvalidCastException) {\n\t\t\t} catch (NullReferenceException) {\n\t\t\t}\n\n\t\t\treturn -1;\n\t\t}\n\n\t\tvoid IList.Insert (int index, object value)\n\t\t{\n\t\t\tCheckIndex (index);\n\n\t\t\ttry {\n\t\t\t\tInsert (index, (T) value);\n\t\t\t\treturn;\n\t\t\t} catch (InvalidCastException) {\n\t\t\t} catch (NullReferenceException) {\n\t\t\t}\n\n\t\t\tthrow new ArgumentException ();\n\t\t}\n\n\t\tvoid IList.Remove (object value)\n\t\t{\n\t\t\ttry {\n\t\t\t\tRemove ((T) value);\n\t\t\t} catch (InvalidCastException) {\n\t\t\t} catch (NullReferenceException) {\n\t\t\t}\n\t\t}\n\n\t\tvoid IList.RemoveAt (int index)\n\t\t{\n\t\t\tRemoveAt (index);\n\t\t}\n\n\t\tvoid ICollection.CopyTo (Array array, int index)\n\t\t{\n\t\t\tArray.Copy (items, 0, array, index, size);\n\t\t}\n\n\t\tpublic Enumerator GetEnumerator ()\n\t\t{\n\t\t\treturn new Enumerator (this);\n\t\t}\n\n\t\tIEnumerator IEnumerable.GetEnumerator ()\n\t\t{\n\t\t\treturn new Enumerator (this);\n\t\t}\n\n\t\tIEnumerator<T> IEnumerable<T>.GetEnumerator ()\n\t\t{\n\t\t\treturn new Enumerator (this);\n\t\t}\n\n\t\tpublic struct Enumerator : IEnumerator<T>, IDisposable {\n\n\t\t\tCollection<T> collection;\n\t\t\tT current;\n\n\t\t\tint next;\n\t\t\treadonly int version;\n\n\t\t\tpublic T Current {\n\t\t\t\tget { return current; }\n\t\t\t}\n\n\t\t\tobject IEnumerator.Current {\n\t\t\t\tget {\n\t\t\t\t\tCheckState ();\n\n\t\t\t\t\tif (next <= 0)\n\t\t\t\t\t\tthrow new InvalidOperationException ();\n\n\t\t\t\t\treturn current;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinternal Enumerator (Collection<T> collection)\n\t\t\t\t: this ()\n\t\t\t{\n\t\t\t\tthis.collection = collection;\n\t\t\t\tthis.version = collection.version;\n\t\t\t}\n\n\t\t\tpublic bool MoveNext ()\n\t\t\t{\n\t\t\t\tCheckState ();\n\n\t\t\t\tif (next < 0)\n\t\t\t\t\treturn false;\n\n\t\t\t\tif (next < collection.size) {\n\t\t\t\t\tcurrent = collection.items [next++];\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\tnext = -1;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tpublic void Reset ()\n\t\t\t{\n\t\t\t\tCheckState ();\n\n\t\t\t\tnext = 0;\n\t\t\t}\n\n\t\t\tvoid CheckState ()\n\t\t\t{\n\t\t\t\tif (collection == null)\n\t\t\t\t\tthrow new ObjectDisposedException (GetType ().FullName);\n\n\t\t\t\tif (version != collection.version)\n\t\t\t\t\tthrow new InvalidOperationException ();\n\t\t\t}\n\n\t\t\tpublic void Dispose ()\n\t\t\t{\n\t\t\t\tcollection = null;\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Collections.Generic/ReadOnlyCollection.cs",
    "content": "//\n// ReadOnlyCollection.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections;\nusing System .Collections.Generic;\n\nnamespace Mono.Collections.Generic {\n\n\tpublic sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IList {\n\n\t\tstatic ReadOnlyCollection<T> empty;\n\n\t\tpublic static ReadOnlyCollection<T> Empty {\n\t\t\tget { return empty ?? (empty = new ReadOnlyCollection<T> ()); }\n\t\t}\n\n\t\tbool ICollection<T>.IsReadOnly {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tbool IList.IsFixedSize {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tbool IList.IsReadOnly {\n\t\t\tget { return true; }\n\t\t}\n\n\t\tprivate ReadOnlyCollection ()\n\t\t{\n\t\t}\n\n\t\tpublic ReadOnlyCollection (T [] array)\n\t\t{\n\t\t\tif (array == null)\n\t\t\t\tthrow new ArgumentNullException ();\n\n\t\t\tInitialize (array, array.Length);\n\t\t}\n\n\t\tpublic ReadOnlyCollection (Collection<T> collection)\n\t\t{\n\t\t\tif (collection == null)\n\t\t\t\tthrow new ArgumentNullException ();\n\n\t\t\tInitialize (collection.items, collection.size);\n\t\t}\n\n\t\tvoid Initialize (T [] items, int size)\n\t\t{\n\t\t\tthis.items = new T [size];\n\t\t\tArray.Copy (items, 0, this.items, 0, size);\n\t\t\tthis.size = size;\n\t\t}\n\n\t\tinternal override void Grow (int desired)\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tprotected override void OnAdd (T item, int index)\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tprotected override void OnClear ()\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tprotected override void OnInsert (T item, int index)\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tprotected override void OnRemove (T item, int index)\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\n\t\tprotected override void OnSet (T item, int index)\n\t\t{\n\t\t\tthrow new InvalidOperationException ();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Security.Cryptography/CryptoConvert.cs",
    "content": ""
  },
  {
    "path": "SGFUnity/Mono.Cecil.20/MonoCecil/Mono.Security.Cryptography/CryptoService.cs",
    "content": "//\n// CryptoService.cs\n//\n// Author:\n//   Jb Evain (jbevain@gmail.com)\n//\n// Copyright (c) 2008 - 2011 Jb Evain\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.IO;\nusing System.Reflection;\nusing System.Security.Cryptography;\n\n"
  },
  {
    "path": "SGFUnity/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// 有关程序集的一般信息由以下\n// 控制。更改这些特性值可修改\n// 与程序集关联的信息。\n[assembly: AssemblyTitle(\"SGFUnity\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"HP Inc.\")]\n[assembly: AssemblyProduct(\"SGFUnity\")]\n[assembly: AssemblyCopyright(\"Copyright © HP Inc. 2017\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// 将 ComVisible 设置为 false 会使此程序集中的类型\n//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型\n//请将此类型的 ComVisible 特性设置为 true。\n[assembly: ComVisible(false)]\n\n// 如果此项目向 COM 公开，则下列 GUID 用于类型库的 ID\n[assembly: Guid(\"64ecff78-ee1f-432b-a581-a70e8eb6de83\")]\n\n// 程序集的版本信息由下列四个值组成: \n//\n//      主版本\n//      次版本\n//      生成号\n//      修订号\n//\n// 可以指定所有值，也可以使用以下所示的 \"*\" 预置版本号和修订号\n//通过使用 \"*\"，如下所示:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "SGFUnity/SGFUnity.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{64ECFF78-EE1F-432B-A581-A70E8EB6DE83}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>SGF.Unity</RootNamespace>\n    <AssemblyName>SGFUnity</AssemblyName>\n    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <TargetFrameworkProfile />\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>..\\Libs\\</OutputPath>\n    <DefineConstants>TRACE;DEBUG;ENABLE_LOG</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n    <DocumentationFile>\n    </DocumentationFile>\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>..\\Libs\\</OutputPath>\n    <DefineConstants>TRACE;ENABLE_LOG</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"protobuf-net, Version=2.0.0.668, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\Common\\protobuf-net.dll</HintPath>\n    </Reference>\n    <Reference Include=\"SGFCore, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\SGFCore.dll</HintPath>\n    </Reference>\n    <Reference Include=\"SGFDebuger, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\SGFDebuger.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"UnityEngine, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\Common\\UnityEngine.dll</HintPath>\n    </Reference>\n    <Reference Include=\"UnityEngine.UI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\Common\\UnityEngine.UI.dll</HintPath>\n    </Reference>\n    <Reference Include=\"zxing.unity, Version=0.14.0.0, Culture=neutral, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\Libs\\Common\\zxing.unity.dll</HintPath>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"DebugerGUI\\NetDebugerGUI.cs\" />\n    <Compile Include=\"DebugerGUI\\SGFDebugerGUI.cs\" />\n    <Compile Include=\"DebugerGUI\\SGFDebugerGUIBase.cs\" />\n    <Compile Include=\"Extension\\BitmapDrawingExtensions.cs\" />\n    <Compile Include=\"Extension\\TransformExtensions.cs\" />\n    <Compile Include=\"ILRuntime\\Adapters\\Editor\\ILRuntimeCLRBinding.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\Method\\CLRMethod.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\Method\\ExceptionHandler.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\Method\\ILMethod.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\Method\\IMethod.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\TypeSystem\\CLRType.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\TypeSystem\\ILGenericParameterType.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\TypeSystem\\ILType.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\TypeSystem\\IType.cs\" />\n    <Compile Include=\"ILRuntime\\CLR\\Utils\\Extensions.cs\" />\n    <Compile Include=\"ILRuntime\\Other\\ByReferenceKeyComparer.cs\" />\n    <Compile Include=\"ILRuntime\\Other\\DelegateExportAttribute.cs\" />\n    <Compile Include=\"ILRuntime\\Other\\NeedAdaptorAttribute.cs\" />\n    <Compile Include=\"ILRuntime\\Other\\ThreadSafeDictionary.cs\" />\n    <Compile Include=\"ILRuntime\\Other\\UncheckedList.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\Extensions.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeConstructorInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeFieldInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeMethodInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeParameterInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimePropertyInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeType.cs\" />\n    <Compile Include=\"ILRuntime\\Reflection\\ILRuntimeWrapperType.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Adaptors\\CLRCrossBindingAdaptors.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\BindingCodeGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\BindingGeneratorExtensions.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\CommonBindingGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\ConstructorBindingGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\FieldBindingGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\MethodBindingGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\CLRBinding\\ValueTypeBindingGenerator.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\BreakPointContext.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\BreakpointInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\DebuggerServer\\DebuggerServer.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\DebugMessageType.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\DebugService.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\DebugSocket.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\CSBindBreakpoint.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\CSDeleteBreakpoint.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\CSExecute.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\CSResolveVariable.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\CSStep.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCAttachResult.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCBindBreakpointResult.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCBreakpointHit.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCModuleLoaded.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCResolveVariableResult.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCStepComplete.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\Protocol\\SCThreadStarted.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\StackFrameInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\StepTypes.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Debugger\\VariableInfo.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\AppDomain.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\CLRRedirections.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\CrossBindingAdaptor.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\DelegateManager.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\ILContext.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Enviorment\\ValueTypeBinder.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Extensions.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\DelegateAdapter.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\ILIntepreter.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\ILRuntimeException.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\ILTypeInstance.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\OpCodes\\OpCode.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Intepreter\\OpCodes\\OpCodeEnum.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Stack\\RuntimeStack.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Stack\\StackFrame.cs\" />\n    <Compile Include=\"ILRuntime\\Runtime\\Stack\\StackObject.cs\" />\n    <Compile Include=\"ILR\\DebugerILR\\DebugerMethodRedirector.cs\" />\n    <Compile Include=\"ILR\\DebugerILR\\ILogTagAdaptor.cs\" />\n    <Compile Include=\"ILR\\DelegateConvertor.cs\" />\n    <Compile Include=\"ILR\\ILRManager.cs\" />\n    <Compile Include=\"ILR\\ModuleILR\\GeneralModuleAdaptor.cs\" />\n    <Compile Include=\"ILR\\ModuleILR\\ILRModuleActivator.cs\" />\n    <Compile Include=\"ILR\\UIILR\\ILRUILoading.cs\" />\n    <Compile Include=\"ILR\\UIILR\\ILRUILoadingAdaptor.cs\" />\n    <Compile Include=\"ILR\\UIILR\\ILRUIPageAdaptor.cs\" />\n    <Compile Include=\"ILR\\UIILR\\ILRUIPage.cs\" />\n    <Compile Include=\"ILR\\UIILR\\ILRUIPanel.cs\" />\n    <Compile Include=\"ILR\\UIILR\\ILRUIPanelAdaptor.cs\" />\n    <Compile Include=\"ILR\\UIILR\\ILRUIWidget.cs\" />\n    <Compile Include=\"ILR\\UIILR\\ILRUIWidgetAdaptor.cs\" />\n    <Compile Include=\"ILR\\UIILR\\ILRUIWindow.cs\" />\n    <Compile Include=\"ILR\\UIILR\\ILRUIWindowAdaptor.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\Code.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\CodeReader.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\CodeWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\Document.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\ExceptionHandler.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\ILProcessor.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\Instruction.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\MethodBody.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\OpCode.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\OpCodes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\SequencePoint.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\Symbols.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\VariableDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Cil\\VariableReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\BlobHeap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\Buffers.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\CodedIndex.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\ElementType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\GuidHeap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\Heap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\MetadataToken.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\Row.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\StringHeap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\TableHeap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\TokenType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\UserStringHeap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.Metadata\\Utilities.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\BinaryStreamReader.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\BinaryStreamWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\ByteBuffer.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\ByteBufferEqualityComparer.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\DataDirectory.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\Image.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\ImageReader.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\ImageWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\Section.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil.PE\\TextMap.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ArrayType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyFlags.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyHashAlgorithm.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyLinkedResource.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyNameDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyNameReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyReader.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\AssemblyWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\BaseAssemblyResolver.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\CallSite.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\CustomAttribute.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\DefaultAssemblyResolver.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\EmbeddedResource.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\EventAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\EventDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\EventReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ExportedType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\FieldAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\FieldDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\FieldReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\FileAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\FunctionPointerType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\GenericInstanceMethod.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\GenericInstanceType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\GenericParameter.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\GenericParameterAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IConstantProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ICustomAttributeProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IGenericInstance.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IGenericParameterProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IMarshalInfoProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IMemberDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IMetadataScope.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IMetadataTokenProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\IMethodSignature.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\Import.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\LinkedResource.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ManifestResourceAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MarshalInfo.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MemberDefinitionCollection.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MemberReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MetadataResolver.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MetadataSystem.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodCallingConvention.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodImplAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodReturnType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodSemanticsAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\MethodSpecification.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\Modifiers.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ModuleDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ModuleKind.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ModuleReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\NativeType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ParameterAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ParameterDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ParameterDefinitionCollection.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ParameterReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PinnedType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PInvokeAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PInvokeInfo.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PointerType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PropertyAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PropertyDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\PropertyReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\ReferenceType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\Resource.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\SecurityDeclaration.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\SentinelType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TargetRuntime.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeAttributes.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeDefinition.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeDefinitionCollection.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeParser.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeReference.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeSpecification.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\TypeSystem.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Cecil\\VariantType.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Collections.Generic\\Collection.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Collections.Generic\\ReadOnlyCollection.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Security.Cryptography\\CryptoConvert.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono.Security.Cryptography\\CryptoService.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono\\Actions.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono\\Empty.cs\" />\n    <Compile Include=\"Mono.Cecil.20\\MonoCecil\\Mono\\Funcs.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\BitAccess.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\BitSet.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\CvInfo.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\DataStream.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\DbiDbgHdr.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\DbiHeader.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\DbiModuleInfo.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\DbiSecCon.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\Interfaces.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\IntHashTable.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\MsfDirectory.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbConstant.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbDebugException.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbException.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbFile.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbFileHeader.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbFunction.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbLine.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbLines.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbReader.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbScope.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbSlot.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\PdbSource.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Microsoft.Cci.Pdb\\SourceLocationProvider.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\ISymUnmanagedDocumentWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\ISymUnmanagedWriter2.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\ModuleMetadata.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\PdbHelper.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\PdbReader.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\PdbWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\SymDocumentWriter.cs\" />\n    <Compile Include=\"Mono.Cecil.Pdb\\pdb\\Mono.Cecil.Pdb\\SymWriter.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"UI\\Drag\\Draggable.cs\" />\n    <Compile Include=\"UI\\Drag\\DropZone.cs\" />\n    <Compile Include=\"UI\\SGUI\\Drawing.cs\" />\n    <Compile Include=\"UI\\SGUI\\DrawingSimple.cs\" />\n    <Compile Include=\"UI\\SGUI\\GUICurve.cs\" />\n    <Compile Include=\"UI\\UIElementBinder.cs\" />\n    <Compile Include=\"UI\\UILib\\Control\\CtlList.cs\" />\n    <Compile Include=\"UI\\UILib\\Control\\CtlListItem.cs\" />\n    <Compile Include=\"UI\\UILib\\Control\\CtlProgressBar.cs\" />\n    <Compile Include=\"UI\\UILib\\Control\\UIControl.cs\" />\n    <Compile Include=\"UI\\UILib\\UIMsgBox.cs\" />\n    <Compile Include=\"UI\\UILib\\UIMsgTips.cs\" />\n    <Compile Include=\"UI\\UILib\\UISimpleLoading.cs\" />\n    <Compile Include=\"UI\\UILoading.cs\" />\n    <Compile Include=\"UI\\UIPage.cs\" />\n    <Compile Include=\"UI\\UIWidget.cs\" />\n    <Compile Include=\"UI\\UIDefine.cs\" />\n    <Compile Include=\"UI\\UIEventTrigger.cs\" />\n    <Compile Include=\"UI\\UIManager.cs\" />\n    <Compile Include=\"UI\\UIPanel.cs\" />\n    <Compile Include=\"UI\\UIRes.cs\" />\n    <Compile Include=\"UI\\UIRoot.cs\" />\n    <Compile Include=\"UI\\UIUtils.cs\" />\n    <Compile Include=\"UI\\UIWindow.cs\" />\n    <Compile Include=\"Utils\\QRCodeUtils.cs\" />\n    <Compile Include=\"Common\\AppPrefs.cs\" />\n    <Compile Include=\"Common\\DelayInvoker.cs\" />\n    <Compile Include=\"Utils\\GameObjectUtils.cs\" />\n    <Compile Include=\"Common\\MonoHelper.cs\" />\n    <Compile Include=\"Common\\MonoSingleton.cs\" />\n    <Compile Include=\"Utils\\NetUtils.cs\" />\n    <Compile Include=\"Extension\\VectorExtensions.cs\" />\n  </ItemGroup>\n  <ItemGroup />\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <PropertyGroup>\n    <PostBuildEvent>$(ProjectDir)..\\Libs\\PublishLibrary.bat $(TargetName)</PostBuildEvent>\n  </PropertyGroup>\n</Project>"
  },
  {
    "path": "SGFUnity/SGFUnity.csproj.user",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <PropertyGroup>\n    <ProjectView>ProjectFiles</ProjectView>\n  </PropertyGroup>\n</Project>"
  },
  {
    "path": "SGFUnity/UI/Drag/Draggable.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\n\nusing UnityEngine;\nusing UnityEngine.EventSystems;\nusing UnityEngine.UI;\n\nnamespace SGF.Unity.UI.Drag\n{\n    public class Draggable:MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler\n    {\n        public static GameObject HolderPrefab;\n\n        private DropZone m_zone;\n        private DropZone m_holderZone;\n        private GameObject m_holder;\n        \n        public void OnBeginDrag(PointerEventData eventData)\n        {\n            if (HolderPrefab == null)\n            {\n                m_holder = new GameObject(this.name + \"(Holder)\");\n            }\n            else\n            {\n                m_holder = GameObject.Instantiate(HolderPrefab);\n                m_holder.name = this.name + \"(Holder)\";\n            }\n            m_holder.transform.SetParent(this.transform.parent);\n            m_holder.transform.SetSiblingIndex(this.transform.GetSiblingIndex());\n\n            if (this.GetComponent<LayoutElement>() != null)\n            {\n                LayoutElement le = m_holder.AddComponent<LayoutElement>();\n                le.preferredWidth = this.GetComponent<LayoutElement>().preferredWidth;\n                le.preferredHeight = this.GetComponent<LayoutElement>().preferredHeight;\n                le.flexibleWidth = 0;\n                le.flexibleHeight = 0;\n            }\n\n            m_zone = this.transform.parent.GetComponent<DropZone>();\n            m_holderZone = m_zone;\n\n            //如果开始拖动，将它移出公共区域\n            this.transform.SetParent(this.transform.parent.parent);\n            SetBlocksRaycasts(false);\n        }\n\n        public void OnDrag(PointerEventData eventData)\n        {\n            this.transform.position = eventData.position;\n\n            //在 拖动过程中，可以会经过一些Zone\n            if (m_holderZone != null)\n            {\n                if (m_holder.transform.parent != m_holderZone)\n                {\n                    m_holder.transform.SetParent(m_holderZone.transform);\n                }\n\n                int newSiblingIndex = m_holderZone.transform.childCount;\n\n                for (int i = 0; i < m_holderZone.transform.childCount; i++)\n                {\n                    if (this.transform.position.x < m_holderZone.transform.GetChild(i).position.x)\n                    {\n                        newSiblingIndex = i;\n\n                        if (m_holder.transform.GetSiblingIndex() < newSiblingIndex)\n                            newSiblingIndex--;\n\n                        break;\n                    }\n                }\n\n\n                m_holder.transform.SetSiblingIndex(newSiblingIndex);\n            }\n        }\n\n\n        public virtual void OnEndDrag(PointerEventData eventData)\n        {\n            this.transform.SetParent(m_zone.transform);\n            this.transform.SetSiblingIndex(m_holder.transform.GetSiblingIndex());\n            SetBlocksRaycasts(true);\n            Destroy(m_holder);\n        }\n\n\n        public void EnterZone(DropZone zone)\n        {\n            m_holderZone = zone;\n        }\n\n        public void ExitZone(DropZone zone)\n        {\n            if (m_holderZone == zone)\n            {\n                m_holderZone = m_zone;\n            }\n        }\n\n        public void DropZone(DropZone zone)\n        {\n            m_zone.OnDropOut(this);\n            m_zone = zone;\n            m_zone.OnDropIn(this);\n        }\n\n        private void SetBlocksRaycasts(bool value)\n        {\n            var group = this.GetComponent<CanvasGroup>();\n            if (group != null)\n            {\n                group.blocksRaycasts = value;\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/Drag/DropZone.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\n\nusing UnityEngine;\nusing UnityEngine.EventSystems;\n\nnamespace SGF.Unity.UI.Drag\n{\n    public class DropZone:MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler\n    {\n        public virtual void OnDrop(PointerEventData eventData)\n        {\n            Draggable d = eventData.pointerDrag.GetComponent<Draggable>();\n            if (d != null)\n            {\n                d.DropZone(this);\n            }\n        }\n\n        public void OnPointerEnter(PointerEventData eventData)\n        {\n            if (eventData.pointerDrag == null)\n                return;\n\n            Draggable d = eventData.pointerDrag.GetComponent<Draggable>();\n            if (d != null)\n            {\n                d.EnterZone(this);\n            }\n        }\n\n        public void OnPointerExit(PointerEventData eventData)\n        {\n            if (eventData.pointerDrag == null)\n                return;\n\n            Draggable d = eventData.pointerDrag.GetComponent<Draggable>();\n            if (d != null)\n            {\n                d.ExitZone(this);\n            }\n        }\n\n        public virtual void OnDropIn(Draggable item)\n        {\n        }\n\n        public virtual void OnDropOut(Draggable item)\n        {\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/SGUI/Drawing.cs",
    "content": "﻿using System.Reflection;\nusing UnityEngine;\n\n// Line drawing routine originally courtesy of Linusmartensson:\n// http://forum.unity3d.com/threads/71979-Drawing-lines-in-the-editor\n//\n// Rewritten to improve performance by Yossarian King / August 2013.\n//\n// This version produces virtually identical results to the original (tested by drawing\n// one over the other and observing errors of one pixel or less), but for large numbers\n// of lines this version is more than four times faster than the original, and comes\n// within about 70% of the raw performance of Graphics.DrawTexture.\n//\n// Peak performance on my laptop is around 200,000 lines per second. The laptop is\n// Windows 7 64-bit, Intel Core2 Duo CPU 2.53GHz, 4G RAM, NVIDIA GeForce GT 220M.\n// Line width and anti-aliasing had negligible impact on performance.\n//\n// For a graph of benchmark results in a standalone Windows build, see this image:\n// https://app.box.com/s/hyuhi565dtolqdm97e00\n//\n// For a Google spreadsheet with full benchmark results, see:\n// https://docs.google.com/spreadsheet/ccc?key=0AvJlJlbRO26VdHhzeHNRMVF2UHZHMXFCTVFZN011V1E&usp=sharing\n\npublic static class Drawing\n{\n    private static Texture2D aaLineTex = null;\n    private static Texture2D lineTex = null;\n    private static Material blitMaterial = null;\n    private static Material blendMaterial = null;\n    private static Rect lineRect = new Rect(0, 0, 1, 1);\n\n\n\n    // This static initializer works for runtime, but apparently isn't called when\n    // Editor play mode stops, so DrawLine will re-initialize if needed.\n    static Drawing()\n    {\n        Init();\n    }\n\n    private static void Init()\n    {\n        if (lineTex == null)\n        {\n            lineTex = new Texture2D(1, 1, TextureFormat.ARGB32, false);\n            lineTex.SetPixel(0, 1, Color.white);\n            lineTex.Apply();\n        }\n        if (aaLineTex == null)\n        {\n            // TODO: better anti-aliasing of wide lines with a larger texture? or use Graphics.DrawTexture with border settings\n            aaLineTex = new Texture2D(1, 3, TextureFormat.ARGB32, false);\n            aaLineTex.SetPixel(0, 0, new Color(1, 1, 1, 0));\n            aaLineTex.SetPixel(0, 1, Color.white);\n            aaLineTex.SetPixel(0, 2, new Color(1, 1, 1, 0));\n            aaLineTex.Apply();\n        }\n\n        // GUI.blitMaterial and GUI.blendMaterial are used internally by GUI.DrawTexture,\n        // depending on the alphaBlend parameter. Use reflection to \"borrow\" these references.\n        blitMaterial = (Material)typeof(GUI).GetMethod(\"get_blitMaterial\", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null);\n        blendMaterial = (Material)typeof(GUI).GetMethod(\"get_blendMaterial\", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null);\n    }\n\n\n    // Draw a line in screen space, suitable for use from OnGUI calls from either\n    // MonoBehaviour or EditorWindow. Note that this should only be called during repaint\n    // events, when (Event.current.type == EventType.Repaint).\n    //\n    // Works by computing a matrix that transforms a unit square -- Rect(0,0,1,1) -- into\n    // a scaled, rotated, and offset rectangle that corresponds to the line and its width.\n    // A DrawTexture call used to draw a line texture into the transformed rectangle.\n    //\n    // More specifically:\n    //      scale x by line length, y by line width\n    //      rotate around z by the angle of the line\n    //      offset by the position of the upper left corner of the target rectangle\n    //\n    // By working out the matrices and applying some trigonometry, the matrix calculation comes\n    // out pretty simple. See https://app.box.com/s/xi08ow8o8ujymazg100j for a picture of my\n    // notebook with the calculations.\n    public static void DrawLine(Vector2 pointA, Vector2 pointB, Color color, float width, bool antiAlias)\n    {\n        // Normally the static initializer does this, but to handle texture reinitialization\n        // after editor play mode stops we need this check in the Editor.\n#if UNITY_EDITOR\n        if (!lineTex)\n        {\n            Initialize();\n        }\n#endif\n\n        // Note that theta = atan2(dy, dx) is the angle we want to rotate by, but instead\n        // of calculating the angle we just use the sine (dy/len) and cosine (dx/len).\n        float dx = pointB.x - pointA.x;\n        float dy = pointB.y - pointA.y;\n        float len = Mathf.Sqrt(dx * dx + dy * dy);\n\n        // Early out on tiny lines to avoid divide by zero.\n        // Plus what's the point of drawing a line 1/1000th of a pixel long??\n        if (len < 0.001f)\n        {\n            return;\n        }\n\n        // Pick texture and material (and tweak width) based on anti-alias setting.\n        Texture2D tex;\n        Material mat;\n        if (antiAlias)\n        {\n            // Multiplying by three is fine for anti-aliasing width-1 lines, but make a wide \"fringe\"\n            // for thicker lines, which may or may not be desirable.\n            width = width * 3.0f;\n            tex = aaLineTex;\n            mat = blendMaterial;\n        }\n        else\n        {\n            tex = lineTex;\n            mat = blitMaterial;\n        }\n\n        float wdx = width * dy / len;\n        float wdy = width * dx / len;\n\n        Matrix4x4 matrix = Matrix4x4.identity;\n        matrix.m00 = dx;\n        matrix.m01 = -wdx;\n        matrix.m03 = pointA.x + 0.5f * wdx;\n        matrix.m10 = dy;\n        matrix.m11 = wdy;\n        matrix.m13 = pointA.y - 0.5f * wdy;\n\n        // Use GL matrix and Graphics.DrawTexture rather than GUI.matrix and GUI.DrawTexture,\n        // for better performance. (Setting GUI.matrix is slow, and GUI.DrawTexture is just a\n        // wrapper on Graphics.DrawTexture.)\n        GL.PushMatrix();\n        GL.MultMatrix(matrix);\n        //Graphics.DrawTexture(lineRect, tex, lineRect, 0, 0, 0, 0, color, mat);\n        //Replaced by:\n        GUI.color = color;//this and...\n        GUI.DrawTexture(lineRect, tex);//this\n\n        GL.PopMatrix();\n    }\n\n    public static void DrawCircle(Vector2 center, int radius, Color color, float width, int segmentsPerQuarter)\n    {\n        DrawCircle(center, radius, color, width, false, segmentsPerQuarter);\n    }\n\n    public static void DrawCircle(Vector2 center, int radius, Color color, float width, bool antiAlias, int segmentsPerQuarter)\n    {\n        float rh = (float)radius / 2;\n\n        Vector2 p1 = new Vector2(center.x, center.y - radius);\n        Vector2 p1_tan_a = new Vector2(center.x - rh, center.y - radius);\n        Vector2 p1_tan_b = new Vector2(center.x + rh, center.y - radius);\n\n        Vector2 p2 = new Vector2(center.x + radius, center.y);\n        Vector2 p2_tan_a = new Vector2(center.x + radius, center.y - rh);\n        Vector2 p2_tan_b = new Vector2(center.x + radius, center.y + rh);\n\n        Vector2 p3 = new Vector2(center.x, center.y + radius);\n        Vector2 p3_tan_a = new Vector2(center.x - rh, center.y + radius);\n        Vector2 p3_tan_b = new Vector2(center.x + rh, center.y + radius);\n\n        Vector2 p4 = new Vector2(center.x - radius, center.y);\n        Vector2 p4_tan_a = new Vector2(center.x - radius, center.y - rh);\n        Vector2 p4_tan_b = new Vector2(center.x - radius, center.y + rh);\n\n        DrawBezierLine(p1, p1_tan_b, p2, p2_tan_a, color, width, antiAlias, segmentsPerQuarter);\n        DrawBezierLine(p2, p2_tan_b, p3, p3_tan_b, color, width, antiAlias, segmentsPerQuarter);\n        DrawBezierLine(p3, p3_tan_a, p4, p4_tan_b, color, width, antiAlias, segmentsPerQuarter);\n        DrawBezierLine(p4, p4_tan_a, p1, p1_tan_a, color, width, antiAlias, segmentsPerQuarter);\n    }\n\n    // Other than method name, DrawBezierLine is unchanged from Linusmartensson's original implementation.\n    public static void DrawBezierLine(Vector2 start, Vector2 startTangent, Vector2 end, Vector2 endTangent, Color color, float width, bool antiAlias, int segments)\n    {\n        Vector2 lastV = CubeBezier(start, startTangent, end, endTangent, 0);\n        for (int i = 1; i < segments + 1; ++i)\n        {\n            Vector2 v = CubeBezier(start, startTangent, end, endTangent, i / (float)segments);\n            DrawLine(lastV, v, color, width, antiAlias);\n            lastV = v;\n        }\n    }\n\n\n    private static Vector2 CubeBezier(Vector2 s, Vector2 st, Vector2 e, Vector2 et, float t)\n    {\n        float rt = 1 - t;\n        return rt * rt * rt * s + 3 * rt * rt * t * st + 3 * rt * t * t * et + t * t * t * e;\n    }\n\n}"
  },
  {
    "path": "SGFUnity/UI/SGUI/DrawingSimple.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing UnityEngine;\n\n\npublic class DrawingSimple\n{\n    //****************************************************************************************************\n    //  static function DrawLine(rect : Rect) : void\n    //  static function DrawLine(rect : Rect, color : Color) : void\n    //  static function DrawLine(rect : Rect, width : float) : void\n    //  static function DrawLine(rect : Rect, color : Color, width : float) : void\n    //  static function DrawLine(Vector2 pointA, Vector2 pointB) : void\n    //  static function DrawLine(Vector2 pointA, Vector2 pointB, color : Color) : void\n    //  static function DrawLine(Vector2 pointA, Vector2 pointB, width : float) : void\n    //  static function DrawLine(Vector2 pointA, Vector2 pointB, color : Color, width : float) : void\n    //  \n    //  Draws a GUI line on the screen.\n    //  \n    //  DrawLine makes up for the severe lack of 2D line rendering in the Unity runtime GUI system.\n    //  This function works by drawing a 1x1 texture filled with a color, which is then scaled\n    //   and rotated by altering the GUI matrix.  The matrix is restored afterwards.\n    //****************************************************************************************************\n\n    public static Texture2D lineTex;\n\n    public static void DrawLine(Rect rect) { DrawLine(rect, GUI.contentColor, 1.0f); }\n    public static void DrawLine(Rect rect, Color color) { DrawLine(rect, color, 1.0f); }\n    public static void DrawLine(Rect rect, float width) { DrawLine(rect, GUI.contentColor, width); }\n    public static void DrawLine(Rect rect, Color color, float width) { DrawLine(new Vector2(rect.x, rect.y), new Vector2(rect.x + rect.width, rect.y + rect.height), color, width); }\n    public static void DrawLine(Vector2 pointA, Vector2 pointB) { DrawLine(pointA, pointB, GUI.contentColor, 1.0f); }\n    public static void DrawLine(Vector2 pointA, Vector2 pointB, Color color) { DrawLine(pointA, pointB, color, 1.0f); }\n    public static void DrawLine(Vector2 pointA, Vector2 pointB, float width) { DrawLine(pointA, pointB, GUI.contentColor, width); }\n    public static void DrawLine(Vector2 pointA, Vector2 pointB, Color color, float width)\n    {\n        // Save the current GUI matrix, since we're going to make changes to it.\n        Matrix4x4 matrix = GUI.matrix;\n\n        // Generate a single pixel texture if it doesn't exist\n        if (!lineTex) { lineTex = new Texture2D(1, 1); }\n\n        // Store current GUI color, so we can switch it back later,\n        // and set the GUI color to the color parameter\n        Color savedColor = GUI.color;\n        GUI.color = color;\n\n        // Determine the angle of the line.\n        float angle = Vector3.Angle(pointB - pointA, Vector2.right);\n\n        // Vector3.Angle always returns a positive number.\n        // If pointB is above pointA, then angle needs to be negative.\n        if (pointA.y > pointB.y) { angle = -angle; }\n\n        // Use ScaleAroundPivot to adjust the size of the line.\n        // We could do this when we draw the texture, but by scaling it here we can use\n        //  non-integer values for the width and length (such as sub 1 pixel widths).\n        // Note that the pivot point is at +.5 from pointA.y, this is so that the width of the line\n        //  is centered on the origin at pointA.\n        GUIUtility.ScaleAroundPivot(new Vector2((pointB - pointA).magnitude, width), new Vector2(pointA.x, pointA.y + 0.5f));\n\n        // Set the rotation for the line.\n        //  The angle was calculated with pointA as the origin.\n        GUIUtility.RotateAroundPivot(angle, pointA);\n\n        // Finally, draw the actual line.\n        // We're really only drawing a 1x1 texture from pointA.\n        // The matrix operations done with ScaleAroundPivot and RotateAroundPivot will make this\n        //  render with the proper width, length, and angle.\n        GUI.DrawTexture(new Rect(pointA.x, pointA.y, 1, 1), lineTex);\n\n        // We're done.  Restore the GUI matrix and GUI color to whatever they were before.\n        GUI.matrix = matrix;\n        GUI.color = savedColor;\n    }\n}\n\n"
  },
  {
    "path": "SGFUnity/UI/SGUI/GUICurve.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\n\nusing System.Collections.Generic;\nusing UnityEngine;\n\nnamespace SGF.Unity.UI.SGUI\n{\n    public class GUICurve\n    {\n        public bool AntiAlias = false;\n        public object state = null;\n\n        private List<Vector2> m_source;\n        private float m_maxX = float.MinValue;\n        private float m_minX = float.MaxValue;\n        private float m_maxY = float.MinValue;\n        private float m_minY = float.MaxValue;\n\n        public float MinX { get { return m_minX; } }\n        public float MinY { get { return m_minY; } }\n        public float MaxX { get { return m_maxX; } }\n        public float MaxY { get { return m_maxY; } }\n\n        \n\n        public GUICurve(List<Vector2> source)\n        {\n            m_source = new List<Vector2>();\n            if (source != null)\n            {\n                for (int i = 0; i < source.Count; i++)\n                {\n                    AddPoint(source[i]);\n                }\n            }\n        }\n\n        public GUICurve()\n        {\n            m_source = new List<Vector2>();\n        }\n\n        public int Length { get { return m_source.Count; } }\n        public List<Vector2> Source { get { return m_source; } }\n\n        public void SetRangeY(float min, float max)\n        {\n            m_minY = min;\n            m_maxY = max;\n        }\n\n        public void AddPoint(Vector2 point)\n        {\n            m_source.Add(point);\n\n            if (m_maxX < point.x)\n            {\n                m_maxX = point.x;\n            }\n\n            if (m_maxY < point.y)\n            {\n                m_maxY = point.y;\n            }\n\n            if (m_minX > point.x)\n            {\n                m_minX = point.x;\n            }\n\n            if (m_minY > point.y)\n            {\n                m_minY = point.y;\n            }\n        }\n\n        public void AddRangePoint(List<Vector2> listPoints)\n        {\n            if (listPoints == null || listPoints.Count == 0)\n            {\n                return;\n            }\n\n            for (int i = 0; i < listPoints.Count; i++)\n            {\n                AddPoint(listPoints[i]);\n            }\n        }\n\n        public void Clear()\n        {\n            m_maxX = float.MinValue;\n            m_minX = float.MaxValue;\n            m_maxY = float.MinValue;\n            m_minY = float.MaxValue;\n            m_source.Clear();\n        }\n        //==================================================================================\n\n        public Color lineColor = Color.red;\n        public Color pointColor = Color.red;\n        public int lineWidth = 2;\n        public int pointRadius = 0;\n        public int minScope = 0;\n        public int maxScope = 0;\n\n\n        public void Draw(Rect rect, Color color, int width, int minScope = 0, int maxScope = 0)\n        {\n            Draw(rect, color, width, Color.white, 0, minScope, maxScope);\n        }\n\n\n        public void Draw(Rect rect, Color color, int width, Color pointColor, int pointRadius, int minScope = 0, int maxScope = 0)\n        {\n            if (m_source == null || m_source.Count < 2)\n            {\n                return;\n            }\n\n            if (minScope < 0 || minScope >= m_source.Count)\n            {\n                minScope = 0;\n            }\n\n            if (maxScope <= 0 || maxScope > m_source.Count)\n            {\n                maxScope = m_source.Count;\n            }\n\n            if (maxScope - minScope < 2)\n            {\n                return;\n            }\n\n\n\n\n            float kx = rect.width / (m_maxX - m_minX);\n            float ky = rect.height / (m_maxY - m_minY);\n\n            Vector2 v1 = m_source[minScope];\n            v1.x = (v1.x - m_minX) * kx;\n            v1.y = rect.height - (v1.y - m_minY) * ky;\n            v1.x += rect.x;\n            v1.y += rect.y;\n\n            Vector2 v2;\n\n            for (int i = (int)minScope + 1; i < maxScope; i++)\n            {\n                v2 = m_source[i];\n                v2.x = (v2.x - m_minX) * kx;\n                v2.y = rect.height - (v2.y - m_minY) * ky;\n\n                v2.x += rect.x;\n                v2.y += rect.y;\n\n                Drawing.DrawLine(v1, v2, color, width, false);\n\n                if (pointRadius > 0)\n                {\n                    Drawing.DrawCircle(v2, pointRadius, pointColor, width, false, 3);\n                }\n\n                v1 = v2;\n            }\n        }\n\n\n        public void Draw(Rect rect)\n        {\n            Draw(rect, lineColor, lineWidth, pointColor, pointRadius, minScope, maxScope);\n        }\n\n        public void DrawLayout(params GUILayoutOption[] options)\n        {\n            GUILayout.Box(\"\", options);\n            Rect rect = GUILayoutUtility.GetLastRect();\n            Draw(rect, lineColor, lineWidth, pointColor, pointRadius, minScope, maxScope);\n        }\n\n\n    }\n}\n"
  },
  {
    "path": "SGFUnity/UI/UIDefine.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nnamespace SGF.Unity.UI\n{\n    public enum UITypeDef\n    {\n        Unkown = 0,\n        Page = 1,\n        Window=2,\n        Widget = 3,\n        Loading =4\n    }\n\n\n    public class UILayerDef\n    {\n        public const int Background = 0;\n        public const int Page = 1000;//-1999\n        public const int NormalWindow = 2000;//-2999\n        public const int TopWindow = 3000;//-3999\n        public const int Widget = 4000;//-4999\n        public const int Loading = 5000;\n        public const int Unkown = 9999;\n\n        public static int GetDefaultLayer(UITypeDef type)\n        {\n            switch (type)\n            {\n                case UITypeDef.Loading: return Loading;\n                case UITypeDef.Widget: return Widget;\n                case UITypeDef.Window: return NormalWindow;\n                case UITypeDef.Page: return Page;\n                case UITypeDef.Unkown: return Unkown;\n                default: return Unkown;\n            }\n        }\n\n    }\n\n\n}"
  },
  {
    "path": "SGFUnity/UI/UIElementBinder.cs",
    "content": "﻿using System;\nusing System.Linq;\nusing System.Reflection;\nusing UnityEngine;\n\nnamespace SGF.Unity.UI\n{\n\n    public class UIElementAttribute : Attribute\n    {\n        \n    }\n\n    public class UIElementBinder\n    {\n        public static void BindAllUIElement(MonoBehaviour parent)\n        {\n            var fis = parent.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n            for (int i = 0; i < fis.Length; i++)\n            {\n                var fi = fis[i];\n                var tokens = fi.GetCustomAttributes(typeof(UIElementAttribute), true);\n                if (tokens.Length > 0)\n                {\n                    BindUIElement(parent, fi);\n                }\n            }\n        }\n\n        private static void BindUIElement(MonoBehaviour parent, FieldInfo fi)\n        {\n            Transform element = parent.transform.Find(fi.Name);\n            string uiName = fi.Name;\n            if (element == null)\n            {\n                if (uiName.StartsWith(\"m_\"))\n                {\n                    uiName = uiName.Substring(2);\n                    element = parent.transform.Find(uiName);\n                }\n                else if (uiName.StartsWith(\"_\"))\n                {\n                    uiName = uiName.Substring(1);\n                    element = parent.transform.Find(uiName);\n                }\n            }\n\n            if (element == null)\n            {\n                var c = uiName[0];\n                c = Char.IsLower(c) ? Char.ToUpper(c) : Char.ToLower(c);\n                uiName = c + uiName.Substring(1);\n                element = parent.transform.Find(uiName);\n            }\n\n\n            if (element != null)\n            {\n                var value = element.GetComponent(fi.FieldType);\n                fi.SetValue(parent, value);\n            }\n            else\n            {\n                Debuger.LogError(\"Canot Find UIElement:{0}\", fi.Name);\n            }\n        }\n\n        public static void BindUIElement(MonoBehaviour parent, string uiName)\n        {\n            var fis = parent.GetType().GetFields();\n            for (int i = 0; i < fis.Length; i++)\n            {\n                var fi = fis[i];\n                if (fi.Name == uiName)\n                {\n                    BindUIElement(parent, fi);    \n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UIEventTrigger.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing UnityEngine;\nusing UnityEngine.EventSystems;\n\nnamespace SGF.Unity.UI\n{\n    public class UIEventTrigger:EventTrigger\n    {\n        public Action onClick;\n        public Action<GameObject> onClickWithObject;\n        public Action<string> onClickWithName;\n        public Action<PointerEventData> onClickWithEvent;\n        public Action<PointerEventData> onDown;\n        public Action<PointerEventData> onEnter;\n        public Action<PointerEventData> onExit;\n        public Action<PointerEventData> onUp;\n        public Action<PointerEventData> onBeginDrag;\n        public Action<PointerEventData> onDrag;\n        public Action<PointerEventData> onEndDrag;\n        public Action<BaseEventData> onSelect;\n        public Action<BaseEventData> onUpdateSelect;\n\n\n\n        static public UIEventTrigger Get(GameObject go)\n        {\n            UIEventTrigger listener = go.GetComponent<UIEventTrigger>();\n            if (listener == null) listener = go.AddComponent<UIEventTrigger>();\n            return listener;\n        }\n\n        static public UIEventTrigger Get(UIBehaviour control)\n        {\n            UIEventTrigger listener = control.gameObject.GetComponent<UIEventTrigger>();\n            if (listener == null) listener = control.gameObject.AddComponent<UIEventTrigger>();\n            return listener;\n        }\n\n        static public UIEventTrigger Get(Transform transform)\n        {\n            UIEventTrigger listener = transform.gameObject.GetComponent<UIEventTrigger>();\n            if (listener == null) listener = transform.gameObject.AddComponent<UIEventTrigger>();\n            return listener;\n        }\n\n        static public bool HasExistOn(Transform transform)\n        {\n            return transform.gameObject.GetComponent<UIEventTrigger>() != null;\n        }\n\n        public override void OnPointerClick(PointerEventData eventData)\n        {\n            if (onClickWithObject != null) onClickWithObject(gameObject);\n            if (onClick != null) onClick();\n            if (onClickWithEvent != null) onClickWithEvent(eventData);\n            if (onClickWithName != null) onClickWithName(gameObject.name);\n        }\n        public override void OnPointerDown(PointerEventData eventData)\n        {\n            if (onDown != null) onDown(eventData);\n        }\n        public override void OnPointerEnter(PointerEventData eventData)\n        {\n            if (onEnter != null) onEnter(eventData);\n        }\n        public override void OnPointerExit(PointerEventData eventData)\n        {\n            if (onExit != null) onExit(eventData);\n        }\n        public override void OnPointerUp(PointerEventData eventData)\n        {\n            if (onUp != null) onUp(eventData);\n        }\n        public override void OnSelect(BaseEventData eventData)\n        {\n            if (onSelect != null) onSelect(eventData);\n        }\n        public override void OnUpdateSelected(BaseEventData eventData)\n        {\n            if (onUpdateSelect != null) onUpdateSelect(eventData);\n        }\n        public override void OnBeginDrag(PointerEventData eventData)\n        {\n            if (onBeginDrag != null) { onBeginDrag(eventData); }\n        }\n        public override void OnDrag(PointerEventData eventData)\n        {\n            if (onDrag != null) { onDrag(eventData); }\n        }\n        public override void OnEndDrag(PointerEventData eventData)\n        {\n            if (onEndDrag != null) { onEndDrag(eventData); }\n        }\n\n\n\n\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UILib/Control/CtlList.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing UnityEngine.UI;\nusing UnityEngine;\nusing System.Collections.Generic;\nusing System.Collections;\n\nnamespace SGF.Unity.UI.UILib.Control\n{\n\tpublic class CtlList:UIControl\n\t{\n\n\t\tenum Direction\n\t\t{\n\t\t\tHorizontal,\n\t\t\tVertical\n\t\t}\n\n\n\t\t[SerializeField]\n\t\tprivate RectTransform m_itemTemplate;\n\n\t\t//页面的显示大小\n\t\t[SerializeField]\n\t\tprivate Vector2 m_pageRect;\n\n\t\t[SerializeField]\n\t\tprivate Direction m_direction = Direction.Horizontal;\n\n\t\t[SerializeField, Range(4, 10)]\n\t\tprivate int m_bufferSize;\n\n\t\tprivate ScrollRect m_scrollRect;\n\t\tprivate RectTransform m_content;\n\t    private RectTransform m_viewport;\n\n\t\tprivate List<RectTransform> m_listItemObject = new List<RectTransform>();\n\t    private IList m_datas;\n\t\tprivate int m_dataCount = 0;\n\n\t\t//宽高\n\t\tpublic Vector2 ItemViewRect { get { return m_itemTemplate != null ? m_itemTemplate.sizeDelta : new Vector2(100, 100); }}\n\t\tpublic float ItemViewSize { get { return m_direction == Direction.Horizontal ? ItemViewRect.x : ItemViewRect.y; } }\n\n\t\t//行列\n\t\tpublic Vector2 PageRect{get{return m_pageRect;}}\n\t\tpublic int PageSize { get { return m_direction == Direction.Horizontal ? (int)m_pageRect.x : (int)m_pageRect.y; } }\n\n\n\t\t//Content的位置\n\t\tprivate float m_prevPos = 0;\n\t\tpublic float Position { get { return m_direction == Direction.Horizontal ? m_content.anchoredPosition.x : m_content.anchoredPosition.y; } }\n\n\t\tprivate int m_currentIndex;//页面的第一行（列）在整个content中的位置\n\n\t\t//页面的实际大小（行列）\n\t\tprivate Vector2 m_pageRealRect = Vector2.zero;\n\t\tpublic Vector2 PageRealRect\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tif (m_pageRealRect == Vector2.zero)\n\t\t\t\t{\n\t\t\t\t\tfloat rows, cols;\n\t\t\t\t\tif (m_direction == Direction.Horizontal)\n\t\t\t\t\t{\n\t\t\t\t\t\trows = m_pageRect.x;\n\t\t\t\t\t\tcols = m_pageRect.y + (float)m_bufferSize;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\trows = m_pageRect.x + (float)m_bufferSize;\n\t\t\t\t\t\tcols = m_pageRect.y;\n\t\t\t\t\t}\n\t\t\t\t\tm_pageRealRect = new Vector2(rows, cols);\n\t\t\t\t}\n\t\t\t\treturn m_pageRealRect;\n\t\t\t}\n\t\t}\n\n\n\t\t/// 由Data数量获取多少行多少列\n\t\tprivate Vector2 MaxRectWithDatas\n\t\t{\n\t\t\tget\n\t\t\t{ \n\t\t\t\tint num = m_datas != null ? m_datas.Count:0;\n\t\t\t\treturn m_direction == Direction.Horizontal ?\n\t\t\t\t\tnew Vector2(m_pageRect.x, Mathf.CeilToInt(num / m_pageRect.x)) :\n\t\t\t\t\tnew Vector2(Mathf.CeilToInt(num / m_pageRect.y), m_pageRect.y);\n\t\t\t}\n\t\t}\n\n\n\n\t\tprotected override void Awake()\n\t\t{\n            base.Awake();\n\n\t\t\tm_scrollRect = GetComponent<ScrollRect >();\n\t\t\tm_scrollRect.horizontal = m_direction == Direction.Horizontal;\n\t\t\tm_scrollRect.vertical = m_direction == Direction.Vertical;\n\n\t\t\tm_content = m_scrollRect.content;\n\t\t    m_viewport = m_scrollRect.viewport;\n\n\t\t}\n\n\t    void Start()\n\t    {\n\t        if (m_direction == Direction.Vertical)\n\t        {\n\t            m_itemTemplate.sizeDelta = new Vector2(m_viewport.rect.width, m_itemTemplate.sizeDelta.y);\n\t        }\n\t        m_itemTemplate.gameObject.SetActive(false);\n        }\n\n\t    public void Clear()\n\t    {\n\t        SetData(new List<object>());\n\t    }\n\n\n\t\tpublic override void SetData(object data)\n\t\t{\n            \n\t\t\tobject oldData = m_datas;\n\t\t\tm_datas = data as IList;\n\t\t\tm_dataCount = m_datas.Count;\n\n\t\t\tint pageItemCount = (int)m_pageRect.x * (int)m_pageRect.y;\n\n\n\t\t\tif (m_datas.Count > pageItemCount)\n\t\t\t{\n\t\t\t\tSetContentBound(MaxRectWithDatas);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tSetContentBound(m_pageRect);\n\t\t\t}\n\n\n\t\t\tint pageRealItemCount = (int)PageRealRect.x * (int)PageRealRect.y;\n\n\t\t\tif (m_datas.Count > pageRealItemCount)\n\t\t\t{\n\t\t\t\twhile (m_listItemObject.Count < pageRealItemCount)\n\t\t\t\t{\n\t\t\t\t\tCreateItem(m_listItemObject.Count);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\twhile (m_listItemObject.Count > m_datas.Count)\n\t\t\t\t{\n\t\t\t\t\tRemoveItem(m_listItemObject.Count - 1);\n\t\t\t\t}\n\n\t\t\t\twhile (m_listItemObject.Count < m_datas.Count)\n\t\t\t\t{\n\t\t\t\t\tCreateItem(m_listItemObject.Count);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (oldData != data)\n\t\t\t{\n\t\t\t\tValidateItems ();\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tprivate void CreateItem(int index)\n\t\t{\n\t\t\tRectTransform item = Instantiate(m_itemTemplate);\n\t\t\titem.SetParent(m_content.transform, false);\n\t\t\titem.anchorMax = Vector2.up;\n\t\t\titem.anchorMin = Vector2.up;\n\t\t\titem.pivot = Vector2.up;\n\t\t\titem.name = \"item\" + index;\n\n\t\t\titem.anchoredPosition = m_direction == Direction.Horizontal ?\n\t\t\t\tnew Vector2(Mathf.Floor(index / PageRealRect.x) * ItemViewRect.x, -(index % PageRealRect.x) * ItemViewRect.y) :\n\t\t\t\tnew Vector2((index % PageRealRect.y) * ItemViewRect.x, -Mathf.Floor(index / PageRealRect.y) * ItemViewRect.y);\n\t\t\t\n\t\t\t\n\t\t\tm_listItemObject.Add(item);\n\t\t\titem.gameObject.SetActive(true);\n\n\t\t\tUpdateItem(index, item.gameObject);\n\t\t}\n\n\t\tprivate void RemoveItem(int index)\n\t\t{\n\t\t\tRectTransform item = m_listItemObject[index];\n\t\t\tm_listItemObject.RemoveAt(index);\n\t\t\tDestroy(item.gameObject);\n\t\t}\n\n\n\n\t\t/// 设置content的大小\n\t\tprivate void SetContentBound(Vector2 bound)\n\t\t{\n\t\t\tm_content.sizeDelta = new Vector2(bound.y * ItemViewRect.x, bound.x * ItemViewRect.y);\n\t\t}\n\n\t\tpublic float MaxPrevPos\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tfloat result;\n\t\t\t\tVector2 max = MaxRectWithDatas;\n\t\t\t\tif (m_direction == Direction.Horizontal)\n\t\t\t\t{\n\t\t\t\t\tresult = max.y - m_pageRect.y;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tresult = max.x - m_pageRect.x;\n\t\t\t\t}\n\t\t\t\treturn result * ItemViewSize;\n\t\t\t}\n\t\t}\n\n\n\n\t\tprivate void ValidateItems()\n\t\t{\n\t\t\tfor (int i = 0; i < m_listItemObject.Count; ++i) \n\t\t\t{\n\t\t\t\tUpdateItem (i, m_listItemObject [i].gameObject);\n\n\t\t\t}\n\t\t}\n\n\t\tvoid Update()\n\t\t{\n\t\t    if (m_datas == null)\n\t\t    {\n\t\t        return;\n\t\t    }\n\n\t\t\tif (m_datas != null && m_dataCount != m_datas.Count)\n\t\t\t{\n\t\t\t\tSetData(m_datas);\n\t\t\t}\n\n\n\t\t\tfloat dirAdjust = m_direction == Direction.Horizontal ? 1f : -1f;\n\n\t\t\twhile (dirAdjust * Position - m_prevPos < -ItemViewSize * 2)\n\t\t\t{\n\t\t\t\tif (m_prevPos <= -MaxPrevPos) return;\n\n\t\t\t\tm_prevPos -= ItemViewSize;\n\n\t\t\t\tList<RectTransform> range = m_listItemObject.GetRange(0, PageSize);\n\t\t\t\tm_listItemObject.RemoveRange(0, PageSize);\n\t\t\t\tm_listItemObject.AddRange(range);\n\t\t\t\tfor (int i = 0; i < range.Count; i++)\n\t\t\t\t{\n\t\t\t\t\tMoveItemToIndex(m_currentIndex * PageSize + m_listItemObject.Count + i, range[i]);\n\t\t\t\t}\n\t\t\t\tm_currentIndex++;\n\t\t\t}\n\n\t\t\twhile (dirAdjust * Position - m_prevPos > -ItemViewSize)\n\t\t\t{\n\t\t\t\tif (Mathf.RoundToInt(m_prevPos) >= 0) return;\n\n\t\t\t\tm_prevPos += ItemViewSize;\n\n\t\t\t\tm_currentIndex--;\n\n\t\t\t\tif (m_currentIndex < 0) return;\n\n\t\t\t\tList<RectTransform> range = m_listItemObject.GetRange(m_listItemObject.Count - PageSize, PageSize);\n\t\t\t\tm_listItemObject.RemoveRange(m_listItemObject.Count - PageSize, PageSize);\n\t\t\t\tm_listItemObject.InsertRange(0, range);\n\t\t\t\tfor (int i = 0; i < range.Count; i++)\n\t\t\t\t{\n\t\t\t\t\tMoveItemToIndex(m_currentIndex * PageSize + i, range[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprivate void MoveItemToIndex(int index, RectTransform item)\n\t\t{\n\t\t\titem.anchoredPosition = GetItemPosByIndex(index);\n\n\t\t    UpdateItem(index, item.gameObject);\n\t\t}\n\n\t\tprivate Vector2 GetItemPosByIndex(int index)\n\t\t{\n\t\t\tfloat x, y;\n\t\t\tif (m_direction == Direction.Horizontal)\n\t\t\t{\n\t\t\t\tx = index % m_pageRect.x;\n\t\t\t\ty = Mathf.FloorToInt(index / m_pageRect.x);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tx = Mathf.FloorToInt(index / m_pageRect.y);\n\t\t\t\ty = index % m_pageRect.y;\n\t\t\t}\n\n\t\t\treturn new Vector2(y * ItemViewRect.x, -x * ItemViewRect.y);\n\t\t}\n\n\t\tprivate void UpdateItem(int index, GameObject item)\n\t\t{\n\t\t\titem.SetActive(index < m_datas.Count);\n\n\t\t\tif (item.activeSelf)\n\t\t\t{\n\t\t\t\tCtlListItem itemComp = item.GetComponent < CtlListItem > ();\n\t\t\t\tif (itemComp != null)\n\t\t\t\t{\n\t\t\t\t\titemComp.UpdateItem(index, m_datas[index]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/UI/UILib/Control/CtlListItem.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nnamespace SGF.Unity.UI.UILib.Control\n{\n\tpublic class CtlListItem:UIControl\n\t{\n\t\tpublic CtlListItem()\n\t\t{\n\t\t}\n\n\t\tpublic virtual void UpdateItem(int index, object data)\n\t\t{ \n\t\t\t\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/UI/UILib/Control/CtlProgressBar.cs",
    "content": "/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing UnityEngine.UI;\n\nnamespace SGF.Unity.UI.UILib.Control\n{\n    public class CtlProgressBar:UIControl\n    {\n        public Image imgProgressValue;\n        public float progress = 0;\n\n\n        void Start()\n        {\n            SetData(0f);\n        }\n\n        public override void SetData(object data)\n        {\n            this.progress = (float)data;\n            imgProgressValue.fillAmount = progress;\n\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UILib/Control/UIControl.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\n\nusing UnityEngine;\nusing UnityEngine.EventSystems;\n\nnamespace SGF.Unity.UI.UILib.Control\n{\n\tpublic class UIControl:MonoBehaviour\n\t{\n\t    public bool AutoBindUIElement = false;\n\n        protected virtual void Awake()\n\t\t{\n\t\t    if (AutoBindUIElement)\n\t\t    {\n\t\t        UIElementBinder.BindAllUIElement(this);\n\t\t    }\n\t\t}\n\n\t\tpublic virtual void SetData(object data)\n\t\t{ \n\t\t}\n\n\t\t \n\n\t\tpublic void SetVisible(bool value)\n\t\t{\n\t\t\tthis.gameObject.SetActive(value);\n\t\t}\n\n\t\tpublic static void SetVisible(UIBehaviour ui, bool value)\n\t\t{\n\t\t\tif (ui != null)\n\t\t\t{\n\t\t\t\tui.gameObject.SetActive(value);\n\t\t\t}\n\t\t}\n\n\t\tpublic bool IsVisible { get { return this.gameObject.activeSelf;} }\n\n\t\tpublic static bool GetVisible(UIBehaviour ui)\n\t\t{\n\t\t\treturn ui.gameObject.activeSelf;\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "SGFUnity/UI/UILib/UIMsgBox.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing UnityEngine;\nusing UnityEngine.EventSystems;\nusing UnityEngine.UI;\n\nnamespace SGF.Unity.UI.UILib\n{\n    public class UIMsgBox:UIWindow\n    {\n        public class UIMsgBoxArg\n        {\n            public string title = \"\";\n            public string content = \"\";\n            public string btnText;//\"确定|取消|关闭\"\n        }\n\n        private UIMsgBoxArg m_arg;\n        public Text txtContent;\n        public UIBehaviour ctlTitle;\n        public Button[] buttons;\n\n\n        protected override void OnOpen(object arg = null)\n        {\n            base.OnOpen(arg);\n            m_arg = arg as UIMsgBoxArg;\n            txtContent.text = m_arg.content;\n            string[] btnTexts = m_arg.btnText.Split('|');\n\n            UIUtils.SetChildText(ctlTitle, m_arg.title);\n            UIUtils.SetActive(ctlTitle, !string.IsNullOrEmpty(m_arg.title));\n\n            float btnWidth = 200;\n            float btnStartX = (1 - btnTexts.Length) * btnWidth / 2;\n\n            for (int i = 0; i < buttons.Length; i++)\n            {\n                if (i < btnTexts.Length)\n                {\n                    UIUtils.SetActive(buttons[i], true);\n                    UIUtils.SetButtonText(buttons[i], btnTexts[i]);\n                    Vector3 pos = buttons[i].transform.localPosition;\n                    pos.x = btnStartX + i * btnWidth;\n                    buttons[i].transform.localPosition = pos;\n                }\n                else\n                {\n                    UIUtils.SetActive(buttons[i], false);\n                }\n\n                UIEventTrigger.Get(buttons[i]).onClickWithObject += OnBtnClick;\n            }\n\n            Layer = (UILayerDef.TopWindow);\n\n        }\n\n        protected override void OnClose(object arg = null)\n        {\n            base.OnClose(arg);\n            for (int i = 0; i < buttons.Length; i++)\n            {\n                UIEventTrigger.Get(buttons[i]).onClickWithObject -= OnBtnClick;\n            }\n        }\n\n        public void OnBtnClick(GameObject target)\n        {\n            Debuger.Log(target.name);\n            int btnIndex = IndexOfButton(target);\n            this.Close(btnIndex);\n        }\n\n        private int IndexOfButton(GameObject target)\n        {\n            for (int i = 0; i < buttons.Length; i++)\n            {\n                if (buttons[i].gameObject == target)\n                {\n                    return i;\n                }\n            }\n            return -1;\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UILib/UIMsgTips.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing UnityEngine.EventSystems;\n\nnamespace SGF.Unity.UI.UILib\n{\n    public class UIMsgTips:UIWidget\n    {\n        public UIBehaviour ctlTextBar;\n        private const float MaxYOffset = 20f;\n        private float m_alpha = 1;\n        private float m_yOffset = MaxYOffset;\n\n        protected override void OnOpen(object arg = null)\n        {\n            base.OnOpen(arg);\n\n            UIUtils.SetChildText(ctlTextBar, arg as string);\n\n            m_yOffset = MaxYOffset;\n            m_alpha = 1;\n            UpdateView();\n        }\n\n        void Update()\n        {\n            m_alpha -= 0.01f;\n            if (m_alpha < 0)\n            {\n                m_alpha = 0;\n                this.Close();\n            }\n\n            m_yOffset -= 0.1f;\n            if (m_yOffset < 0)\n            {\n                m_yOffset = 0;\n            }\n\n            UpdateView();\n        }\n\n        private void UpdateView()\n        {\n\n            ctlTextBar.transform.SetLocalY(MaxYOffset - m_yOffset);\n        }\n\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UILib/UISimpleLoading.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing SGF.Unity.UI.UILib.Control;\nusing UnityEngine;\nusing UnityEngine.UI;\n\nnamespace SGF.Unity.UI.UILib\n{\n    public class UISimpleLoading:UILoading\n    {\n        public CtlProgressBar progressBar;\n        public Image rotateIcon;\n\n        private UILoadingArg m_arg;\n        public UILoadingArg arg { get { return m_arg; } }\n        protected override void OnOpen(object arg = null)\n        {\n            base.OnOpen(arg);\n            m_arg = arg as UILoadingArg;\n            if(m_arg == null)\n            {\n                m_arg = new UILoadingArg();\n            }\n            UpdateText();\n        }\n\n        protected override void OnClose(object arg = null)\n        {\n            m_arg = null;\n            base.OnClose(arg);\n        }\n\n        public void ShowProgress(string title, float progress)\n        {\n            m_arg.title = title;\n            m_arg.progress = progress;\n        }\n\n        public void ShowProgress(float progress)\n        {\n            m_arg.progress = progress;\n        }\n\n        private void UpdateText()\n        {\n            if (txtTitle != null)\n            {\n                txtTitle.text = m_arg.title + \"(\" + (int)(m_arg.progress * 100) + \"%)\";\n            }\n            if (txtTips != null)\n            {\n                txtTips.text = m_arg.tips;\n            }\n        }\n\n        private void UpdateProgress()\n        {\n            if (progressBar != null)\n            {\n                progressBar.SetData(m_arg.progress);\n            }\n        }\n\n        protected override void OnUpdate()\n        {\n            if (m_arg != null)\n            {\n                UpdateText();\n                UpdateProgress();\n            }\n\n            if (rotateIcon != null)\n            {\n                rotateIcon.transform.Rotate(new Vector3(0, 0, -45 * UnityEngine.Time.deltaTime));\n            }\n        }\n\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UILoading.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing UnityEngine.UI;\n\nnamespace SGF.Unity.UI\n{\n    public class UILoadingArg\n    {\n        public string title = \"\";\n        public string tips = \"\";\n        public float progress = 0;//0~1\n\n        public override string ToString()\n        {\n            return string.Format(\"title:{0}, tips:{1}, progress:{2}\", title, tips, progress);\n        }\n    }\n\n    public abstract class UILoading:UIPanel\n    {\n        public override UITypeDef UIType { get { return UITypeDef.Loading; } }\n\n        public Text txtTitle;\n        public Text txtTips;\n\n        private UILoadingArg m_arg;\n        public UILoadingArg arg { get { return m_arg; } }\n\n\n        protected override void OnOpen(object arg = null)\n        {\n            base.OnOpen(arg);\n\n            m_arg = arg as UILoadingArg;\n            if (m_arg == null)\n            {\n                m_arg = new UILoadingArg();\n            }\n            UpdateText();\n        }\n\n        public void ShowProgress(string title, float progress)\n        {\n            m_arg.tips = title;\n            m_arg.progress = progress;\n        }\n\n        public void ShowProgress(float progress)\n        {\n            m_arg.progress = progress;\n        }\n\n\n        protected override void OnUpdate()\n        {\n            base.OnUpdate();\n\n            if (m_arg != null)\n            {\n                UpdateText();\n                UpdateProgress();\n            }\n        }\n\n        protected virtual void UpdateProgress()\n        {\n            \n        }\n\n\n        private void UpdateText()\n        {\n            if (txtTitle != null)\n            {\n                txtTitle.text = m_arg.title + \"(\" + (int)(m_arg.progress * 100) + \"%)\";\n            }\n            if (txtTips != null)\n            {\n                txtTips.text = m_arg.tips;\n            }\n        }\n\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UIManager.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * UI管理器\n * UI Manager\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing SGF.Utils;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\n\nnamespace SGF.Unity.UI\n{\n    public class UIManager : Singleton<UIManager>\n    {\n        public static string MainScene = \"Main\";\n        public static string MainPage = \"UIMainPage\";\n        public static string SceneLoading = \"SceneLoading\";\n\n        class UIPageTrack\n        {\n            public string name;\n            public object arg;\n            public Type type;\n        }\n\n\n        private Stack<UIPageTrack> m_pageTrackStack;\n        private UIPageTrack m_currentPage;\n\n        private List<UIPanel> m_listLoadedPanel;\n\n        private Action<string> onSceneLoadedOnly;\n\n\n        public UIManager()\n        {\n            m_pageTrackStack = new Stack<UIPageTrack>();\n            m_listLoadedPanel = new List<UIPanel>();\n        }\n\n\n        public void Init(string uiResRoot)\n        {\n            UIRes.UIResRoot = uiResRoot;\n\n            m_pageTrackStack.Clear();\n            m_listLoadedPanel.Clear();\n\n            SceneManager.sceneLoaded += (scene, mode) =>\n            {\n                if (onSceneLoadedOnly != null) onSceneLoadedOnly(scene.name);\n            };\n        }\n\n        public void Clean()\n        {\n            CloseAllLoadedPanel();\n\n            m_pageTrackStack.Clear();\n            m_listLoadedPanel.Clear();\n        }\n\n        private void CloseAllLoadedPanel()\n        {\n            for (int i = m_listLoadedPanel.Count - 1; i >= 0; i--)\n            {\n                var panel = m_listLoadedPanel[i];\n                if (panel == null)\n                {\n                    m_listLoadedPanel.RemoveAt(i);\n                }\n                else if (panel.IsOpen)\n                {\n                    panel.Close();\n                }\n\n            }\n        }\n\n\n        private string GetShortUIName(string name)\n        {\n            int i = name.LastIndexOf(\"/\");\n            if(i < 0) i = name.LastIndexOf(\"\\\\\");\n            if (i < 0) return name;\n            return name.Substring(i+1);\n        }\n\n        public T Open<T>(string name, object arg = null, Type implType = null) where T : UIPanel\n        {\n            T ui = UIRoot.Find<T>(GetShortUIName(name));\n            if (ui == null)\n            {\n                ui = Load<T>(name, implType);\n            }\n            if (ui != null)\n            {\n                if (m_listLoadedPanel.IndexOf(ui) < 0)\n                {\n                    m_listLoadedPanel.Add(ui);\n                }\n\n                ui.Open(arg);\n                UIRoot.Sort();\n            }\n            else\n            {\n                Debuger.LogError(\"UI不存在：{0}\", name);\n            }\n            return ui;\n        }\n\n\n        private T Load<T>(string name, Type implType) where T : UIPanel\n        {\n            T ui = default(T);\n            GameObject original = UIRes.LoadPrefab(name);\n            if (original != null)\n            {\n                GameObject go = GameObject.Instantiate(original);\n                ui = go.GetComponent<T>();\n                if (ui == null)\n                {\n                    try\n                    {\n                        ui = go.AddComponent(implType) as T;\n                    }\n                    catch (Exception e)\n                    {\n                        Debuger.LogError(\"无法自动添加抽象的UIPanel\");\n                    }\n\n                }\n\n                if (ui != null)\n                {\n                    go.name = GetShortUIName(name);\n                    UIRoot.AddChild(ui);\n                }\n                else\n                {\n                    Debuger.LogError(\"Prefab没有增加对应组件: \" + name);\n                }\n            }\n            else\n            {\n                Debuger.LogError(\"Res Not Found: \" + name);\n            }\n\n            return ui;\n        }\n\n\n        public UIPanel GetUI(string name)\n        {\n            string shortname = GetShortUIName(name);\n            for (int i = 0; i < m_listLoadedPanel.Count; i++)\n            {\n                if (m_listLoadedPanel[i].name == shortname || m_listLoadedPanel[i].name == name)\n                {\n                    return m_listLoadedPanel[i];\n                }\n            }\n            return null;\n        }\n\n\n        //==========================================================================================\n\n        public void LoadScene(string scene, Action onLoadComplete)\n        {\n            onSceneLoadedOnly = (sceneName) =>\n            {\n                if (sceneName == scene)\n                {\n                    onSceneLoadedOnly = null;\n                    if (onLoadComplete != null) onLoadComplete();\n                    CloseLoading(SceneLoading);\n                }\n            };\n\n            OpenLoading(SceneLoading);\n            SceneManager.LoadScene(scene);\n        }\n\n        //==========================================================================================\n        #region Page管理\n\n\n        public void OpenPage(string name, object arg = null)\n        {\n            Debuger.Log(\"name:{0}, arg:{1} \", name, arg);\n\n            if (m_currentPage != null)\n            {\n                if (m_currentPage.name != name)\n                {\n                    m_pageTrackStack.Push(m_currentPage);\n                }\n                \n            }\n\n            OpenPageWorker(name, arg, null);\n        }\n\n        public void GoBackPage()\n        {\n            if (m_pageTrackStack.Count > 0)\n            {\n                var track = m_pageTrackStack.Pop();\n                OpenPageWorker(track.name, track.arg, track.type);\n            }\n            else\n            {\n                EnterMainPage();\n            }\n        }\n\n        private void OpenPageWorker(string page, object arg, Type type)\n        {\n            m_currentPage = new UIPageTrack();\n            m_currentPage.name = page;\n            m_currentPage.arg = arg;\n            m_currentPage.type = type;\n\n            CloseAllLoadedPanel();\n\n            Open<UIPage>(page, arg, type);\n        }\n\n\n        public void EnterMainPage()\n        {\n            m_pageTrackStack.Clear();\n            OpenPageInScene(MainScene, MainPage, null, null);\n        }\n\n        public void OpenPageInScene(string scene, string page)\n        {\n            OpenPageInScene(scene, page, null, null);\n        }\n\n        private void OpenPageInScene(string scene, string page, object arg, Type type)\n        {\n            Debuger.Log(\"scene:{0}, page:{1}, arg:{2} \", scene, page, arg);\n\n            string oldScene = SceneManager.GetActiveScene().name;\n            if (oldScene == scene)\n            {\n                OpenPageWorker(page, arg, type);\n            }\n            else\n            {\n                LoadScene(scene, () =>\n                {\n                    OpenPageWorker(page, arg, type);\n                });\n            }\n        }\n        #endregion\n\n        //=======================================================================\n\n        #region UIWindow管理\n\n        public UIWindow OpenWindow(string name, object arg = null)\n        {\n            Debuger.Log(name);\n            UIWindow ui = Open<UIWindow>(name, arg);\n            return ui;\n        }\n\n\n        public void CloseWindow(string name, object arg = null)\n        {\n            Debuger.Log(name);\n            UIWindow ui = GetUI(name) as UIWindow;\n            if (ui != null)\n            {\n                ui.Close(arg);\n            }\n        }\n\n\n\n        #endregion\n\n        //=======================================================================\n\n        #region UIWidget管理\n\n        public UIWidget OpenWidget(string name, object arg = null)\n        {\n            Debuger.Log(name);\n            UIWidget ui = Open<UIWidget>(name, arg);\n            return ui;\n        }\n\n        public void CloseWidget(string name, object arg = null)\n        {\n            Debuger.Log(name);\n            UIWidget ui = GetUI(name) as UIWidget;\n            if (ui != null)\n            {\n                ui.Close(arg);\n            }\n        }\n\n        #endregion\n\n\n        //==========================================================================================\n        #region UILoading管理\n\n\n        public UILoading OpenLoading(string name, object arg = null)\n        {\n            Debuger.Log(name);\n            UILoading ui = Open<UILoading>(name, arg);\n            return ui;\n        }\n\n        public void CloseLoading(string name, object arg = null)\n        {\n            Debuger.Log(name);\n            UILoading ui = GetUI(name) as UILoading;\n            if (ui != null)\n            {\n                ui.Close(arg);\n            }\n        }\n\n\n        #endregion\n\n        //==========================================================================================\n\n\n\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UIPage.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing UnityEngine;\nusing UnityEngine.UI;\n\nnamespace SGF.Unity.UI\n{\n    public abstract class UIPage:UIPanel\n    {\n        public override UITypeDef UIType { get { return UITypeDef.Page; } }\n\n        /// <summary>\n        /// 返回按钮，大部分Page都会有返回按钮\n        /// </summary>\n        [SerializeField]\n        private Button m_btnGoBack;\n\n\n        /// <summary>\n        /// 当UIPage被激活时调用\n        /// </summary>\n        protected override void OnEnable()\n        {\n            Debuger.Log();\n            AddUIClickListener(m_btnGoBack, OnBtnGoBack);\n        }\n\n        /// <summary>\n        /// 当UI不可用时调用\n        /// </summary>\n        protected override void OnDisable()\n        {\n            Debuger.Log();\n            RemoveUIClickListeners(m_btnGoBack);\n        }\n\n        /// <summary>\n        /// 当点击“返回”时调用\n        /// 但是并不是每一个Page都有返回按钮\n        /// </summary>\n        private void OnBtnGoBack()\n        {\n            Debuger.Log();\n            UIManager.Instance.GoBackPage();\n        }\n\n\n\n\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UIPanel.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing System.Collections.Generic;\nusing SGF.SEvent;\nusing UnityEngine;\nusing UnityEngine.EventSystems;\n\nnamespace SGF.Unity.UI\n{\n    public abstract class UIPanel:MonoBehaviour, ILogTag\n    {\n        public virtual UITypeDef UIType { get { return UITypeDef.Unkown; } }\n\n        private int m_layer = UILayerDef.Unkown;\n        public int Layer { get { return m_layer; } set { m_layer = value; } }\n\n        public bool AutoBindUIElement = false;\n\n        [SerializeField]\n        private AnimationClip m_openAniClip;\n\n        [SerializeField]\n        private AnimationClip m_closeAniClip;\n\n        private float m_closeAniClipTime;\n        private object m_closeArg;\n        public Signal<object> onClose = new Signal<object>();\n\n\n        /// <summary>\n        /// 当前UI是否打开\n        /// </summary>\n        public bool IsOpen { get { return this.gameObject.activeSelf; } }\n\n\n\n        void Awake()\n        {\n            LOG_TAG = this.GetType().Name;\n            if (AutoBindUIElement)\n            {\n                UIElementBinder.BindAllUIElement(this);\n            }\n\n            OnAwake();\n        }\n\n        protected virtual void OnAwake()\n        {\n\n        }\n\n        protected virtual void OnDestroy()\n        {\n\n        }\n\n        protected virtual void OnEnable()\n        {\n\n        }\n\n        protected virtual void OnDisable()\n        {\n\n        }\n\n        \n\n\n        private void Update()\n        {\n            if (m_closeAniClipTime > 0)\n            {\n                m_closeAniClipTime -= UnityEngine.Time.deltaTime;\n                if (m_closeAniClipTime <= 0)\n                {\n                    CloseWorker();\n                }\n            }\n\n            OnUpdate();\n        }\n\n\n        public void Open(object arg = null)\n        {\n            LOG_TAG = this.GetType().Name;\n\n            this.Log(\"args:{0}\", arg);\n\n            if (!this.gameObject.activeSelf)\n            {\n                this.gameObject.SetActive(true);\n            }\n            \n            OnOpen(arg);\n\n            if (m_openAniClip != null)\n            {\n                var animation = GetComponent<Animation>();\n                if (animation != null)\n                {\n                    animation.Play(m_openAniClip.name);\n                }\n                else\n                {\n                    Debuger.LogError(\"设置了OpenAniClip，但是未找到 Animation组件！\");\n                }\n            }\n        }\n\n\n        public void Close(object arg = null)\n        {\n            this.Log(\"args:{0}\", arg);\n            m_closeArg = arg;\n            m_closeAniClipTime = 0;\n\n            if (m_closeAniClip != null)\n            {\n                var animation = GetComponent<Animation>();\n                if (animation != null)\n                {\n                    animation.Play(m_closeAniClip.name);\n                    m_closeAniClipTime = m_closeAniClip.length;\n                }\n                else\n                {\n                    Debuger.LogError(\"设置了CloseAniClip，但是未找到 Animation组件！\");\n                    CloseWorker();\n                }\n            }\n            else\n            {\n                CloseWorker();\n            }\n            \n        }\n\n\n\n        private void CloseWorker()\n        {\n\n            if (this.gameObject.activeSelf)\n            {\n                this.gameObject.SetActive(false);\n            }\n\n            OnClose(m_closeArg);\n            onClose.Invoke(m_closeArg);\n\n            m_closeArg = null;\n        }\n\n\n\n        protected virtual void OnOpen(object arg = null)\n        {\n            Layer = UILayerDef.GetDefaultLayer(UIType);\n        }\n\n        protected virtual void OnClose(object arg = null)\n        {\n            \n        }\n\n        protected virtual void OnUpdate()\n        {\n            \n        }\n\n\n\n        public string LOG_TAG { get; protected set; }\n\n\n\n        /// <summary>\n        /// 方便寻找Panel上的UI控件\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"controlName\"></param>\n        /// <returns></returns>\n        public T Find<T>(string controlName) where T : MonoBehaviour\n        {\n            Transform target = this.transform.Find(controlName);\n            if (target != null)\n            {\n                return target.GetComponent<T>();\n            }\n            else\n            {\n                Debuger.LogError(\"未找到UI控件：{0}\", controlName);\n                return default(T);\n            }\n        }\n\n\n\n        #region UI事件监听辅助函数\n        /// <summary>\n        /// 为UIPanel内的脚本提供便捷的UI事件监听接口\n        /// </summary>\n        /// <param name=\"controlName\"></param>\n        /// <param name=\"listener\"></param>\n        public void AddUIClickListener(string controlName, Action<string> listener)\n        {\n            Transform target = this.transform.Find(controlName);\n            if (target != null)\n            {\n                UIEventTrigger.Get(target).onClickWithName -= listener;\n                UIEventTrigger.Get(target).onClickWithName += listener;\n            }\n            else\n            {\n                Debuger.LogError(\"未找到UI控件：{0}\", controlName);\n            }\n        }\n\n        /// <summary>\n        /// 为UIPanel内的脚本提供便捷的UI事件监听接口\n        /// </summary>\n        /// <param name=\"controlName\"></param>\n        /// <param name=\"listener\"></param>\n        public void AddUIClickListener(string controlName, Action listener)\n        {\n            Transform target = this.transform.Find(controlName);\n            if (target != null)\n            {\n                UIEventTrigger.Get(target).onClick -= listener;\n                UIEventTrigger.Get(target).onClick += listener;\n            }\n            else\n            {\n                Debuger.LogError(\"未找到UI控件：{0}\", controlName);\n            }\n        }\n\n\n\n        /// <summary>\n        /// 为UIPanel内的脚本提供便捷的UI事件监听接口\n        /// </summary>\n        /// <param name=\"target\"></param>\n        /// <param name=\"listener\"></param>\n        public void AddUIClickListener(UIBehaviour target, Action listener)\n        {\n            if (target != null)\n            {\n                UIEventTrigger.Get(target).onClick -= listener;\n                UIEventTrigger.Get(target).onClick += listener;\n            }\n        }\n\n\n\n        /// <summary>\n        /// 移除UI控件的监听器\n        /// </summary>\n        /// <param name=\"controlName\"></param>\n        /// <param name=\"listener\"></param>\n        public void RemoveUIClickListener(string controlName, Action<string> listener)\n        {\n            Transform target = this.transform.Find(controlName);\n            if (target != null)\n            {\n                if (UIEventTrigger.HasExistOn(target))\n                {\n                    UIEventTrigger.Get(target).onClickWithName -= listener;\n                }\n            }\n            else\n            {\n                Debuger.LogError(\"未找到UI控件：{0}\", controlName);\n            }\n        }\n\n        /// <summary>\n        /// 移除UI控件的监听器\n        /// </summary>\n        /// <param name=\"controlName\"></param>\n        /// <param name=\"listener\"></param>\n        public void RemoveUIClickListener(string controlName, Action listener)\n        {\n            Transform target = this.transform.Find(controlName);\n            if (target != null)\n            {\n                if (UIEventTrigger.HasExistOn(target))\n                {\n                    UIEventTrigger.Get(target).onClick -= listener;\n                }\n            }\n            else\n            {\n                Debuger.LogError(\"未找到UI控件：{0}\", controlName);\n            }\n        }\n\n        /// <summary>\n        /// 移除UI控件的监听器\n        /// </summary>\n        /// <param name=\"target\"></param>\n        /// <param name=\"listener\"></param>\n        public void RemoveUIClickListener(UIBehaviour target, Action listener)\n        {\n            if (target != null)\n            {\n                if (UIEventTrigger.HasExistOn(target.transform))\n                {\n                    UIEventTrigger.Get(target).onClick -= listener;\n                }\n            }\n        }\n\n\n        /// <summary>\n        /// 移除UI控件的所有监听器\n        /// </summary>\n        /// <param name=\"controlName\"></param>\n        public void RemoveUIClickListeners(string controlName)\n        {\n            Transform target = this.transform.Find(controlName);\n            if (target != null)\n            {\n                if (UIEventTrigger.HasExistOn(target))\n                {\n                    UIEventTrigger.Get(target).onClick = null;\n                }\n            }\n            else\n            {\n                Debuger.LogError(\"未找到UI控件：{0}\", controlName);\n            }\n        }\n\n        /// <summary>\n        /// 移除UI控件的所有监听器\n        /// </summary>\n        /// <param name=\"target\"></param>\n        public void RemoveUIClickListeners(UIBehaviour target)\n        {\n            if (target != null)\n            {\n                if (UIEventTrigger.HasExistOn(target.transform))\n                {\n                    UIEventTrigger.Get(target).onClick = null;\n                }\n            }\n        }\n\n        #endregion \n\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UIRes.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing UnityEngine;\n\nnamespace SGF.Unity.UI\n{\n    public static class UIRes\n    {\n        public static string UIResRoot = \"ui/\";\n\n        /// <summary>\n        /// 加载UI的Prefab\n        /// </summary>\n        /// <param name=\"name\"></param>\n        /// <returns></returns>\n        public static GameObject LoadPrefab(string name)\n        {\n            GameObject asset = (GameObject)Resources.Load(UIResRoot + name);\n            return asset;\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UIRoot.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\n\nnamespace SGF.Unity.UI\n{\n    public class UIRoot:MonoBehaviour\n    {\n\n\n        /// <summary>\n        /// 从UIRoot下通过名字&类型寻找一个组件对象\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"name\"></param>\n        /// <returns></returns>\n        public static T Find<T>(string name) where T : MonoBehaviour\n        {\n            GameObject obj = Find(name);\n            if (obj != null)\n            {\n                return obj.GetComponent<T>();\n            }\n            return null;\n        }\n\n\n\n        public static GameObject Find(string name)\n        {\n            if (string.IsNullOrEmpty(name))\n            {\n                return null;\n            }\n\n\n            Transform obj = null;\n            GameObject root = FindUIRoot();\n            if (root != null)\n            {\n                //在新版Unity中，Find函数会将Name中的/当作分隔符\n                //obj = root.transform.FindChild(name);\n\n                Transform t = root.transform;\n                for (int i = 0; i < t.childCount; i++)\n                {\n                    Transform c = t.GetChild(i);\n                    if (c.name == name)\n                    {\n                        obj = c;\n                        break;\n                    }\n                }\n            }\n\n            if (obj != null)\n            {\n                return obj.gameObject;\n            }\n            return null;\n        }\n\n        public static GameObject FindUIRoot()\n        {\n            GameObject root = GameObject.Find(\"UIRoot\");\n            if (root != null && root.GetComponent<UIRoot>() != null)\n            {\n                return root;\n            }\n            Debuger.LogError(\"UIRoot Is Not Exist!!!\");\n            return null;\n        }\n\n\n        /// <summary>\n        /// 当一个UIPage/UIWindow/UIWidget添加到UIRoot下面\n        /// </summary>\n        /// <param name=\"child\"></param>\n        public static void AddChild(UIPanel child)\n        {\n            GameObject root = FindUIRoot();\n            if (root == null || child == null)\n            {\n                return;\n            }\n            child.transform.SetParent(root.transform, false);\n\n        }\n\n\n        public static void Sort()\n        {\n            GameObject root = FindUIRoot();\n            if (root == null)\n            {\n                return;\n            }\n\n            List<UIPanel> list = new List<UIPanel>();\n            root.GetComponentsInChildren<UIPanel>(true, list);\n            list.Sort((a, b) =>\n            {\n                return a.Layer - b.Layer;\n            });\n\n            for (int i = 0; i < list.Count; i++)\n            {\n                list[i].transform.SetSiblingIndex(i);\n            }\n        }\n\n\n        //==============================================================================\n        //UIRoot本身的逻辑\n        //==============================================================================\n        private static Camera m_uiCamera;\n        private static CanvasScaler m_canvasScaler;\n\n        public Camera UICamera;\n\n        void Awake()\n        {\n            //让UIRoot一直存在于所有场景中\n            DontDestroyOnLoad(gameObject);\n            m_uiCamera = UICamera;\n            m_canvasScaler = GetComponent<CanvasScaler>();\n        }\n\n        public CanvasScaler GetUIScaler()\n        {\n            return m_canvasScaler;\n        }\n\n        public Camera GetUICamera()\n        {\n            return m_uiCamera;\n        }\n\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UIUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing SGF.Unity.Utils;\nusing UnityEngine;\nusing UnityEngine.EventSystems;\nusing UnityEngine.UI;\n\nnamespace SGF.Unity.UI\n{\n    /// <summary>\n    /// 为UI操作提供基础封装，使UI操作更方便\n    /// </summary>\n    public static class UIUtils\n    {\n        /// <summary>\n        /// 设置一个UI元素是否可见\n        /// </summary>\n        /// <param name=\"ui\"></param>\n        /// <param name=\"value\"></param>\n        public static void SetActive(UIBehaviour ui, bool value)\n        {\n            if (ui != null && ui.gameObject != null)\n            {\n                GameObjectUtils.SetActiveRecursively(ui.gameObject, value);\n            }\n        }\n\n\n        public static void SetButtonText(Button btn, string text)\n        {\n            Text objText = btn.transform.GetComponentInChildren<Text>();\n            if (objText != null)\n            {\n                objText.text = text;\n            }\n        }\n\n        public static string GetButtonText(Button btn)\n        {\n            Text objText = btn.transform.GetComponentInChildren<Text>();\n            if (objText != null)\n            {\n                return objText.text;\n            }\n            return \"\";\n        }\n\n        public static void SetChildText(UIBehaviour ui, string text)\n        {\n            Text objText = ui.transform.GetComponentInChildren<Text>();\n            if (objText != null)\n            {\n                objText.text = text;\n            }\n        }\n\n\n        /// <summary>\n        /// 方便寻找Panel上的UI控件\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"controlName\"></param>\n        /// <returns></returns>\n        public static T Find<T>(MonoBehaviour parent, string controlName) where T : MonoBehaviour\n        {\n            Transform target = parent.transform.Find(controlName);\n            if (target != null)\n            {\n                return target.GetComponent<T>();\n            }\n            else\n            {\n                Debuger.LogError(\"未找到UI控件：{0}\", controlName);\n                return default(T);\n            }\n        }\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UIWidget.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nnamespace SGF.Unity.UI\n{\n    public abstract class UIWidget : UIPanel\n    {\n        public override UITypeDef UIType { get { return UITypeDef.Widget; } }\n\n\n    }\n}"
  },
  {
    "path": "SGFUnity/UI/UIWindow.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\nusing UnityEngine;\nusing UnityEngine.UI;\n\nnamespace SGF.Unity.UI\n{\n    public abstract class UIWindow:UIPanel\n    {\n        public override UITypeDef UIType { get { return UITypeDef.Window; } }\n\n        [SerializeField]\n        private Button m_btnClose;\n\n        /// <summary>\n        /// 当UI可用时调用\n        /// </summary>\n        protected override void OnEnable()\n        {\n            Debuger.Log();\n            AddUIClickListener(m_btnClose, OnBtnClose);\n        }\n\n        /// <summary>\n        /// 当UI不可用时调用\n        /// </summary>\n        protected override void OnDisable()\n        {\n            Debuger.Log();\n            RemoveUIClickListeners(m_btnClose);\n        }\n\n        private void OnBtnClose()\n        {\n            Close(0);\n        }\n\n    }\n}"
  },
  {
    "path": "SGFUnity/Utils/GameObjectUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing System;\nusing UnityEngine;\n\n\n\n\nnamespace SGF.Unity.Utils\n{\n    public static class GameObjectUtils\n    {\n        public static T EnsureComponent<T>(this GameObject target) where T : Component\n        {\n            T comp = target.GetComponent<T>();\n            if (comp == null)\n            {\n                return target.AddComponent<T>();\n            }\n            return comp;\n        }\n\n        public static Component EnsureComponent(this GameObject target, Type type)\n        {\n            Component comp = target.GetComponent(type);\n            if (comp == null)\n            {\n                return target.AddComponent(type);\n            }\n            return comp;\n        }\n\n        public static T FindComponent<T>(this GameObject target, string path) where T : Component\n        {\n            GameObject obj = FindGameObject(target, path);\n            if (obj != null)\n            {\n                return obj.GetComponent<T>();\n            }\n            return default(T);\n        }\n\n        public static GameObject FindGameObject(this GameObject target, string path)\n        {\n            if (target != null)\n            {\n                Transform t = target.transform.Find(path);\n                if (t != null)\n                {\n                    return t.gameObject;\n                }\n            }\n\n            return null;\n\n        }\n\n\n        private static GameObject FindGameObject2(GameObject target, string path)\n        {\n            if (target == null)\n            {\n                return null;\n            }\n\n            string[] array = path.Split('.');\n            Transform current = target.transform;\n\n            for (int i = 0; i < array.Length; ++i)\n            {\n                string name = array[i];\n                Transform child = current.Find(name);\n                if (child != null)\n                {\n                    current = child;\n                }\n                else\n                {\n                    char[] c = name.ToCharArray();\n                    if (Char.IsLower(c[0]))\n                    {\n                        c[0] = Char.ToUpper(c[0]);\n                    }\n                    else\n                    {\n                        c[0] = Char.ToLower(c[0]);\n                    }\n\n                    name = new string(c);\n                    child = current.Find(name);\n                    if (child != null)\n                    {\n                        current = child;\n                    }\n                    else\n                    {\n                        current = null;\n                        break;\n                    }\n                }\n            }\n\n            if (current == null)\n            {\n                return null;\n            }\n\n            return current.gameObject;\n\n        }\n\n        public static GameObject FindGameObjbyName(this GameObject root, string name)\n        {\n            if (root == null)\n            {\n                return GameObject.Find(name);\n            }\n\n            Transform[] childs = root.GetComponentsInChildren<Transform>();\n\n            foreach (Transform trans in childs)\n            {\n                if (trans.gameObject.name.Equals(name))\n                {\n                    return trans.gameObject;\n                }\n            }\n\n            return null;\n        }\n\n\n        public static GameObject FindFirstGameObjByPrefix(this GameObject root, string prefix)\n        {\n            Transform[] childs;\n            if (root != null)\n            {\n                childs = root.GetComponentsInChildren<Transform>();\n            }\n            else\n            {\n                childs = GameObject.FindObjectsOfType<Transform>();\n            }\n\n            foreach (Transform trans in childs)\n            {\n                if (trans.gameObject.name.Length >= prefix.Length)\n                {\n                    if (trans.gameObject.name.Substring(0, prefix.Length) == prefix)\n                    {\n                        return trans.gameObject;\n                    }\n                }\n\n            }\n\n            return null;\n        }\n\n\n        public static void SetActiveRecursively(this GameObject target, bool bActive)\n        {\n#if (!UNITY_3_5)\n            for (int n = target.transform.childCount - 1; 0 <= n; n--)\n                if (n < target.transform.childCount)\n                    SetActiveRecursively(target.transform.GetChild(n).gameObject, bActive);\n            target.SetActive(bActive);\n#else\n\t\ttarget.SetActiveRecursively(bActive);\n#endif\n        }\n        public static void SetLayerRecursively(this GameObject target, int layer)\n        {\n#if (!UNITY_3_5)\n            for (int n = target.transform.childCount - 1; 0 <= n; n--)\n            {\n                if (n < target.transform.childCount)\n                {\n                    SetLayerRecursively(target.transform.GetChild(n).gameObject, layer);\n                }\n            }\n            target.layer = layer;\n#else\n\t\ttarget.SetActiveRecursively(bActive);\n#endif\n        }\n\n\n    }\n\n}\n"
  },
  {
    "path": "SGFUnity/Utils/NetUtils.cs",
    "content": "﻿/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\nusing UnityEngine;\n\nnamespace SGF.Unity.Utils\n{\n    public class NetUtils\n    {\n        public static bool IsWifi()\n        {\n            return Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork;\n        }\n\n\n        public static bool IsAvailable()\n        {\n            return Application.internetReachability != NetworkReachability.NotReachable;\n        }\n\n\n        public static string SelfIP\n        {\n            get { return UnityEngine.Network.player.ipAddress; }\n        }\n\n    }\n}\n"
  },
  {
    "path": "SGFUnity/Utils/QRCodeUtils.cs",
    "content": "/*\n * Copyright (C) 2018 Slicol Tang. All rights reserved.\n * \n * Licensed under the MIT License (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n * http://opensource.org/licenses/MIT\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n * either express or implied. \n * See the License for the specific language governing permissions and limitations under the License.\n*/\n\n\n\nusing System;\nusing SGF;\nusing UnityEngine;\nusing ZXing;\nusing ZXing.Common;\n\n\nnamespace OT.Foundation\n{\n    public class QRCodeUtils\n    {\n        public const string LOG_TAG = \"QRCodeUtils\";\n\n        public static Texture2D EncodeToImage(string content, int width, int height)\n        {\n\t\t\tDebuger.Log(LOG_TAG, \"EncodeToImage\", \"content:{0}, width:{1}, height:{2}\", content, width, height);\n\n            Texture2D texEncoded = null;\n            BitMatrix bm = null;\n\n            try\n            {\n                MultiFormatWriter mfw = new MultiFormatWriter();\n                bm = mfw.encode(content, BarcodeFormat.QR_CODE, width, height);\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(LOG_TAG, \"EncodeToImage\", e.Message);\n                return null;\n            }\n\n            texEncoded = new Texture2D(width, height);\n\n            for (int x = 0; x < bm.Height; x++)\n            {\n                for (int y = 0; y < bm.Width; y++)\n                {\n                    int py = x;\n                    int px = y;\n\n                    if (bm[x, y])\n                    {\n                        \n                        texEncoded.SetPixel(px,py, Color.black);\n                    }\n                    else\n                    {\n                        texEncoded.SetPixel(px, py, Color.white);\n                    }\n                }\n            }\n\n            texEncoded.Apply();\n            return texEncoded;\n        }\n\n        \n        public static string DecodeFromImage(Texture2D image)\n        {\n            Debuger.Log(LOG_TAG, \"DecodeFromImage\");\n\n            try\n            {\n                Color32LuminanceSource src = new Color32LuminanceSource(image.GetPixels32(), image.width, image.height);\n\n                Binarizer bin = new GlobalHistogramBinarizer(src);\n                BinaryBitmap bmp = new BinaryBitmap(bin);\n\n                MultiFormatReader mfr = new MultiFormatReader();\n                Result result = mfr.decode(bmp);\n\n                if (result != null)\n                {\n                    return result.Text;\n                }\n                else\n                {\n                    Debuger.LogError(LOG_TAG, \"DecodeFromImage\", \"Decode 失败！\");\n                }\n            }\n            catch (Exception e)\n            {\n                Debuger.LogError(LOG_TAG, \"DecodeFromImage\",  e.Message);\n            }\n\n            return \"\";\n\n        }\n    }\n}\n"
  },
  {
    "path": "SGFUnityTest/Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// 有关程序集的一般信息由以下\n// 控制。更改这些特性值可修改\n// 与程序集关联的信息。\n[assembly: AssemblyTitle(\"SGFUnityTest\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"\")]\n[assembly: AssemblyProduct(\"SGFUnityTest\")]\n[assembly: AssemblyCopyright(\"Copyright ©  2018\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n//将 ComVisible 设置为 false 将使此程序集中的类型\n//对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型，\n//请将此类型的 ComVisible 特性设置为 true。\n[assembly: ComVisible(false)]\n\n// 如果此项目向 COM 公开，则下列 GUID 用于类型库的 ID\n[assembly: Guid(\"dc93629f-df4e-406f-ac5f-df96f3f98cbc\")]\n\n// 程序集的版本信息由下列四个值组成: \n//\n//      主版本\n//      次版本\n//      生成号\n//      修订号\n//\n//可以指定所有这些值，也可以使用“生成号”和“修订号”的默认值，\n// 方法是按如下所示使用“*”: :\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "SGFUnityTest/SGFUnityTest.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{DC93629F-DF4E-406F-AC5F-DF96F3F98CBC}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>SGFUnityTest</RootNamespace>\n    <AssemblyName>SGFUnityTest</AssemblyName>\n    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\n    <ReferencePath>$(ProgramFiles)\\Common Files\\microsoft shared\\VSTT\\$(VisualStudioVersion)\\UITestExtensionPackages</ReferencePath>\n    <IsCodedUITest>False</IsCodedUITest>\n    <TestProjectType>UnitTest</TestProjectType>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>bin\\Debug\\</OutputPath>\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>bin\\Release\\</OutputPath>\n    <DefineConstants>TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\">\n      <RequiredTargetFramework>3.5</RequiredTargetFramework>\n    </Reference>\n  </ItemGroup>\n  <Choose>\n    <When Condition=\"('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'\">\n      <ItemGroup>\n        <Reference Include=\"Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\" />\n      </ItemGroup>\n    </When>\n    <Otherwise>\n      <ItemGroup>\n        <Reference Include=\"Microsoft.VisualStudio.QualityTools.UnitTestFramework\" />\n      </ItemGroup>\n    </Otherwise>\n  </Choose>\n  <ItemGroup>\n    <Compile Include=\"UnitTest1.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n  </ItemGroup>\n  <Choose>\n    <When Condition=\"'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'\">\n      <ItemGroup>\n        <Reference Include=\"Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\n          <Private>False</Private>\n        </Reference>\n        <Reference Include=\"Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\n          <Private>False</Private>\n        </Reference>\n        <Reference Include=\"Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\n          <Private>False</Private>\n        </Reference>\n        <Reference Include=\"Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\n          <Private>False</Private>\n        </Reference>\n      </ItemGroup>\n    </When>\n  </Choose>\n  <Import Project=\"$(VSToolsPath)\\TeamTest\\Microsoft.TestTools.targets\" Condition=\"Exists('$(VSToolsPath)\\TeamTest\\Microsoft.TestTools.targets')\" />\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "SGFUnityTest/UnitTest1.cs",
    "content": "﻿using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace SGFUnityTest\n{\n    [TestClass]\n    public class UnitTest1\n    {\n        [TestMethod]\n        public void TestMethod1()\n        {\n        }\n    }\n}\n"
  }
]